Created
June 17, 2024 22:06
-
-
Save sbailliez/603d65b4fc38451ba3653694b4045a35 to your computer and use it in GitHub Desktop.
Redshift - Returns all columns datatype, encoding, nullable and default value. Useful for maintenance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WITH table_columns AS ( | |
SELECT | |
c.relowner as tableowner | |
,n.nspname AS schema_name | |
,c.relname AS table_name | |
,a.attnum AS ordinal | |
,QUOTE_IDENT(a.attname) AS column_name | |
,CASE WHEN STRPOS(UPPER(format_type(a.atttypid, a.atttypmod)), 'CHARACTER VARYING') > 0 | |
THEN REPLACE(UPPER(format_type(a.atttypid, a.atttypmod)), 'CHARACTER VARYING', 'VARCHAR') | |
WHEN STRPOS(UPPER(format_type(a.atttypid, a.atttypmod)), 'CHARACTER') > 0 | |
THEN REPLACE(UPPER(format_type(a.atttypid, a.atttypmod)), 'CHARACTER', 'CHAR') | |
ELSE UPPER(format_type(a.atttypid, a.atttypmod)) | |
END AS column_datatype | |
,CASE WHEN format_encoding((a.attencodingtype)::integer) = 'none' | |
THEN 'raw' | |
ELSE format_encoding((a.attencodingtype)::integer) | |
END AS column_encoding | |
,CASE WHEN a.atthasdef IS TRUE THEN 'DEFAULT ' + adef.adsrc ELSE '' END AS column_default | |
,CASE WHEN a.attnotnull IS TRUE THEN 'NOT NULL' ELSE '' END AS column_nullable | |
FROM pg_namespace AS n | |
INNER JOIN pg_class AS c ON n.oid = c.relnamespace | |
INNER JOIN pg_attribute AS a ON c.oid = a.attrelid | |
LEFT OUTER JOIN pg_attrdef AS adef ON a.attrelid = adef.adrelid AND a.attnum = adef.adnum | |
WHERE c.relkind = 'r' | |
AND a.attnum > 0 | |
ORDER BY a.attnum | |
) | |
SELECT * FROM table_columns; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment