Build the DDL command dynamically. You can do it in two steps:
Build statement:
SELECT 'CREATE TABLE why.am_i_doing_this AS SELECT '
|| string_agg(column_name, ', ' ORDER BY ordinal_position)
|| ' FROM original.table'
FROM information_schema.columns
WHERE table_schema = 'original'
AND table_name = 'table'
AND column_name NOT IN ('column_1', 'column_2');
(Check it's good!) Then execute the generated statement in a second round trip to the server.
This is based on the information schema view information_schema.columns
. Alternatively, you could use pg_catalog.pg_attribute
. Related:
But it can be done in a single round trip to the server, too:
With a DO
statement from any client
DO
is just a simple wrapper for ad-hoc execution of PL/pgSQL code. You might do the same in a function or procedure.
DO
$$
BEGIN
EXECUTE (
SELECT 'CREATE TABLE why.am_i_doing_this AS SELECT '
|| string_agg(column_name, ', ' ORDER BY ordinal_position)
|| ' FROM original.table'
FROM information_schema.columns
WHERE table_schema = 'original'
AND table_name = 'table'
AND column_name NOT IN ('column_1', 'column_2')
);
END
$$;
Simpler with psql meta-command \gexec
Since you mentioned the default interactive terminal psql
. There you can use \gexec
. It ...
Sends the current query buffer to the server, then treats each column of each row of the query's output (if any) as a SQL statement to be executed.
So:
SELECT 'CREATE TABLE why.am_i_doing_this AS SELECT '
|| string_agg(column_name, ', ' ORDER BY ordinal_position)
|| ' FROM original.table'
FROM information_schema.columns
WHERE table_schema = 'original'
AND table_name = 'table'
AND column_name NOT IN ('column_1', 'column_2')\gexec