// SQL snippet

List check constraints

Check constraints encode business rules directly in the schema: price > 0, status IN (...), start < end. This recipe lists every one with the expression it enforces.

Main statement
SQL Server
Couvre également
PostgreSQL MySQL

The task

An insert is rejected with a check-constraint error, or you are documenting which business rules the database enforces on its own. Either way you need the expressions.

The snippet

Written for SQL Server. Versions for PostgreSQL and MySQL are under Variations.

SQL Server
SELECT t.name AS table_name,
       cc.name AS constraint_name,
       cc.definition
FROM sys.check_constraints cc
JOIN sys.tables t ON t.object_id = cc.parent_object_id
ORDER BY t.name, cc.name;

Fonctionnement

sys.check_constraints stores each constraint's expression in definition, normalized by SQL Server (qty > 0 comes back as ([qty]>(0))). Joining to sys.tables attaches the table name. A constraint added or re-enabled WITH NOCHECK has is_not_trusted = 1: existing rows were never checked, and the optimizer will not use it to skip work in query plans.

Variations

PostgreSQL

PostgreSQL
SELECT n.nspname AS schema_name,
       c.relname AS table_name,
       con.conname AS constraint_name,
       pg_get_constraintdef(con.oid) AS definition,
       con.convalidated AS validated
FROM pg_constraint con
JOIN pg_class c ON c.oid = con.conrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE con.contype = 'c' AND n.nspname = 'public'
ORDER BY c.relname;

MySQL

MySQL
-- check_constraints has no table column; get it from
-- table_constraints. CHECK is enforced from MySQL 8.0.16.
SELECT tc.table_name, cc.constraint_name, cc.check_clause,
       tc.enforced
FROM information_schema.check_constraints cc
JOIN information_schema.table_constraints tc
  ON tc.constraint_schema = cc.constraint_schema
 AND tc.constraint_name = cc.constraint_name
 AND tc.constraint_type = 'CHECK'
WHERE cc.constraint_schema = 'mydb'
ORDER BY tc.table_name, cc.constraint_name;

Questions that come up

What does convalidated = false mean on PostgreSQL?

The constraint was added with NOT VALID, so existing rows were never checked and only new writes are enforced. ALTER TABLE ... VALIDATE CONSTRAINT scans the existing rows under a SHARE UPDATE EXCLUSIVE lock, which lets reads and writes continue, and flips convalidated to true if every row passes.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.