1

I want to get the list of all constraints, their tables and their columns, something like

constraint                    | table | columns
------------------------------|-------|---------------
table1_colum1_colum2_key       table1   {colum1, colum2}

How can this be done?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
mljrg
  • 4,430
  • 2
  • 36
  • 49
  • 1
    You could retrive that from `INFORMATION_SCHEMA`. Here example for Foreign Keys [Postgres: SQL to list table foreign keys](https://stackoverflow.com/questions/1152260/postgres-sql-to-list-table-foreign-keys) – Lukasz Szozda Dec 30 '18 at 21:05
  • Which constraints are you referring to? Primary Key? Unique constraints? Check Constraints? Not null constraint? Foreign key constraints? Exclusion constraints? –  Dec 30 '18 at 21:22
  • @a_horse_with_no_name All constraints. – mljrg Dec 30 '18 at 21:24

1 Answers1

2

The constraints can be queried via pg_constraint. Tables are included in pg_class and columns in pg_attributes. Schemas are in pg_namespace.

Something like the following may work for you.

SELECT con.conname "constraint",
       concat(nsp.nspname, '.', rel.relname) "table",
       (SELECT array_agg(att.attname)
               FROM pg_attribute att
                    INNER JOIN unnest(con.conkey) unnest(conkey)
                               ON unnest.conkey = att.attnum
               WHERE att.attrelid = con.conrelid) "columns"
       FROM pg_constraint con
            INNER JOIN pg_class rel
                       ON rel.oid = con.conrelid
            INNER JOIN pg_namespace nsp
                       ON nsp.oid = rel.relnamespace;
sticky bit
  • 36,626
  • 12
  • 31
  • 42