List table check constraints in PostgreSQL database

Query below lists table check constraints.

Query

select tc.table_schema,
       tc.table_name,
       string_agg(col.column_name, ', ') as columns,
       tc.constraint_name,
       cc.check_clause
from information_schema.table_constraints tc
join information_schema.check_constraints cc
     on tc.constraint_schema = cc.constraint_schema
     and tc.constraint_name = cc.constraint_name
join pg_namespace nsp on nsp.nspname = cc.constraint_schema
join pg_constraint pgc on pgc.conname = cc.constraint_name
                       and pgc.connamespace = nsp.oid
                       and pgc.contype = 'c'
join information_schema.columns col
     on col.table_schema = tc.table_schema
     and col.table_name = tc.table_name
     and col.ordinal_position = ANY(pgc.conkey)
where tc.constraint_schema not in('pg_catalog', 'information_schema')
group by tc.table_schema,
         tc.table_name,
         tc.constraint_name,
         cc.check_clause
order by tc.table_schema,
         tc.table_name;

Columns

  • table_schema - table's schema name constraint is defined for, null for not table-level check constraints
  • table_name - table name constraint is defined for, null for not table-level check constraints
  • columns - columns names constraint is defined for separated by ','
  • constraint_name - name of the constraint in the database
  • check_clause - SQL expression that defines this check constraint

Rows

  • One row represents one check constraint
  • Scope of rows: query returns all check constraints in the database
  • Ordered by table schema and table name

Sample results

List of table check constraints in pagila database.