Skip to content

Instantly share code, notes, and snippets.

@jacobsimeon
Created October 24, 2011 16:30
Show Gist options
  • Save jacobsimeon/1309443 to your computer and use it in GitHub Desktop.
Save jacobsimeon/1309443 to your computer and use it in GitHub Desktop.
A handy query for getting information about tables and columns in a postgresql database.
SELECT col.attrelid::regclass as table,
col.attname as name,
format_type(col.atttypid, col.atttypmod) as type,
col.attnotnull as not_null,
def.adsrc as default,
( SELECT d.refobjid
FROM pg_depend d
WHERE col.attrelid = d.refobjid
AND col.attnum = d.refobjsubid
LIMIT 1
) IS NOT NULL as primary_key
FROM pg_attribute as col
LEFT JOIN pg_attrdef def
ON col.attrelid = def.adrelid
AND col.attnum = def.adnum
JOIN pg_tables tbl
ON col.attrelid::regclass = tbl.tablename::regclass
WHERE tbl.schemaname = ANY (current_schemas(false))
AND col.attnum > 0
ORDER BY primary_key DESC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment