From a table, how can I create another table without the data and with only the primary key columns?
I am able to get the primary key columns using the following query:
SELECT column_name
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name
WHERE tc.table_schema = 'MY_SCHEMA'
AND tc.table_name = 'MY_TABLE'
AND tc.constraint_type = 'PRIMARY KEY';
Then, I thought of using this method to create the new table:
CREATE TABLE MY_NEW_SCHEMA.MY_NEW_TABLE AS
SELECT TOP 0 WROTE_HERE_A_WAY_TO_GET_THE_PRIMARY_COLUMN_DYNAMICALLY
FROM OLD_SCHEMA.OLD_TABLE;
However, I need to replace WROTE_HERE_A_WAY_TO_GET_THE_PRIMARY_COLUMN_DYNAMICALLY with the result of the first SQL query dynamically, and I’m not sure how to achieve that.
It’s important to note that when I try to use LISTAGG for this purpose, I encounter the following error:
ERROR: Specified types or functions (one per INFO message) not supported on Redshift tables. [ErrorId: 1-6759af45-0bca22fc1857f4ec7ecb34c6]
Info: Column "c.conkey" has unsupported type "smallint[]".
Example of the LISTAGG query I attempted:
SELECT LISTAGG(column_name, ', ')
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name
WHERE tc.table_schema = 'MY_SCHEMA'
AND tc.table_name = 'MY_TABLE'
AND tc.constraint_type = 'PRIMARY KEY';