PostgreSQL constraints can be written after a column definition (column level) or after the column list (table level). Both are the same kind of catalog object, but they differ in reach: table-level constraints may span several columns and can be added or dropped later with ALTER TABLE, whereas column-level constraints apply to a single column and must be declared at creation time. Understanding the distinction helps when reading constraint names in pg_catalog and when choosing how to express a complex rule.
Written after a column definition and applies to that column only. Auto-named `
__`.
table_constraint
Written after the column list and may span several columns. Auto-named `
_`, or named explicitly with CONSTRAINT.
Returns:Neither form returns anything. Query pg_constraint to see the resulting names and definitions; use pg_get_constraintdef(oid) for the full SQL text.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
SELECT conname, pg_get_constraintdef(oid) AS definition
FROM pg_constraint WHERE conrelid = 'products'::regclass
ORDER BY conname
conname | definition
------------------------------+------------------------------------
products_name_not_blank | CHECK (((name)::text <> ''::text))
products_name_not_null | NOT NULL name
products_pkey | PRIMARY KEY (product_id)
products_price_check | CHECK ((price > (0)::numeric))
products_price_not_null | NOT NULL price
products_product_id_not_null | NOT NULL product_id
products_stock_not_null | NOT NULL stock
products_stock_positive | CHECK ((stock > 0))
(8 rows)
QDoes it matter whether the same constraint is written at column or table level?
AFunctionally there is almost no difference — PostgreSQL stores identical entries in pg_constraint. The practical differences are readability and maintainability: the table-level form can span columns, gives you free naming, and can be added or dropped later, while the column-level form is more compact and suits simple single-column rules.
QWhy do some constraint names end in _check and others in __check?
AAuto-naming depends on how many columns the constraint involves: a single-column constraint becomes `
__check`, while one spanning several columns (or a column-level check that references another column) becomes `
_check`. To keep names predictable, name constraints explicitly with CONSTRAINT.
Web-Tutorial Tech Team
A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.