CHECK & UNIQUE Constraints
Enforce rules close to data. Practical PostgreSQL patterns for production queries.
Search across all documentation pages
Enforce rules close to data. Practical PostgreSQL patterns for production queries.
ALTER TABLE app.accounts ADD CONSTRAINT accounts_name_len CHECK (char_length(name) <= 200);
CREATE UNIQUE INDEX accounts_name_active_unique ON app.accounts (name) WHERE deleted_at IS NULL;When to reach for this: This pattern appears in application or reporting SQL you maintain.
INSERT INTO app.accounts (name) VALUES ('Acme'); -- second 'Acme' fails while activeWhat this demonstrates:
| Alternative | Use When | Don't Use When |
|---|---|---|
| ORM query builder | Team standardizes on one stack | Complex SQL becomes opaque |
| Materialized view | Repeat expensive aggregates | Needs refresh strategy |
| Warehouse replica | Heavy BI scans | Not for OLTP latency |
Use multiline template strings or SQL files; lint in CI.
When you need unique rows without aggregates.
Sort can use index order if query matches index columns.
Stack versions: This page was written for PostgreSQL 18.4 (stable 18, maintenance 17), pgvector 0.8+, PgBouncer 1.x, Patroni 3.x, and PostGIS 3.5+.
Reviewed by Chris St. John·Last updated Jul 18, 2026