1

I have a table with mixed types of data (real, integrer, character ...) but i would only recover columns that have real values.

I can construct this:

SELECT 'SELECT ' || array_to_string(ARRAY(
select 'o' || '.' || c.column_name 
from information_schema.columns as c
where table_name = 'final_datas'
and c.data_type = 'real'), ',') || ' FROM final_datas as o' As sqlstmt

that gives that:

"SELECT o.random,o.struct2d_pred2_num,o.pfam_num,o.transmb_num [...] FROM final_datas as o"

The i would like to create a table with these columns. Of course, do this, doesn't work:

create table table2 as (
SELECT 'SELECT ' || array_to_string(ARRAY(
select 'o' || '.' || c.column_name 
from information_schema.columns as c
where table_name = 'final_datas'
and c.data_type = 'real'), ',') || ' FROM final_datas as o' As sqlstmt
)

Suggestions?

1
  • Look into the pg_catalog for this. Run psql -E, then \d final_datas within it, and you'll see the relevant queries that you need to run. Commented Nov 24, 2013 at 20:50

1 Answer 1

1

You need to generate the whole CREATE TABLE statement as dynamic SQL:

SELECT 'CREATE TABLE table2 AS SELECT ' || array_to_string(ARRAY(
select 'o' || '.' || c.column_name 
from information_schema.columns as c
where table_name = 'final_datas'
and c.data_type = 'real'), ',') || ' FROM final_datas as o' As sqlstmt

The result can be run with EXECUTE sqlstmt;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.