There is a much easier way.
SELECT pg_typeof(col)::text FROM tbl LIMIT 1
Only the precondition is that the template table contains at least one row. See the manual at pg_typeof ()
As Mylene wrote, you need EXECUTE dynamic DDL statements like this.
A simpler DO statement:
DO $$BEGIN EXECUTE 'CREATE TABLE egg (id ' || (SELECT pg_typeof(col)::text FROM tbl LIMIT 1) || ')'; END$$;
Or, if you are not sure that the template table has any rows:
DO $$BEGIN EXECUTE ( SELECT format('CREATE TABLE egg (id %s)' , format_type(atttypid, atttypmod)) FROM pg_catalog.pg_attribute WHERE attrelid = 'tbl'::regclass
These conditions seem redundant since you are looking for a specific column any
format() requires Postgres 9.1 +.
on this topic:
- How to check if a table exists in a given schema
Erwin brandstetter
source share