Query:
SELECT string_agg(column_name::text, ',')
FROM information_schema.columns
WHERE table_name = 'my_table' and column_name !='id'
returns list of columns in my_table except 'id':
date_of_birth,first_name,last_name,e_mail
I would like to use this list in INSERT INTO statement when defining columns names. How should I do it, because following don't work.
INSERT INTO my_table2 (
SELECT string_agg(column_name::text, ',')
FROM information_schema.columns
WHERE table_name = 'my_table' and column_name !='id'
)
VALUES ('a', 'b', ...);
I have changing column count and order in my_table2 and my_table so I must assign names automatically .
You have to use dynamic SQL, that is, construct a second query from the result of the first one. There is no way to do it in a single statement.
With psql
's \gexec
, you could use
SELECT format($$INSERT INTO my_table2 (%s) VALUES ('a', 'b', ...)$$,
string_agg(quote_ident(column_name), ', ')
)
FROM information_schema.columns
WHERE table_name = 'my_table'
AND column_name <> 'id' \gexec