← All notes

PostgreSQL constraints: CHECK, NOT NULL, UNIQUE and foreign keys

Short answer

Constraints let the database reject bad data. CHECK tests a Boolean expression; foreign keys make sure a referenced row exists. Name your constraints so errors are clear. [S1][S2]

Example

CREATE TABLE cities (name text PRIMARY KEY);
CREATE TABLE weather (
  city  text REFERENCES cities(name),
  price numeric CONSTRAINT positive_price CHECK (price > 0)
);

Inserting a city not in cities fails with a foreign-key error. [S2]

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted).

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: PostgreSQL Global Development Group, PostgreSQL: Documentation: 18: 5.5. Constraints, PostgreSQL License; PostgreSQL Global Development Group, PostgreSQL: Documentation: 18: 3.3. Foreign Keys, PostgreSQL License.

Cite this

Permanent ID: iil:note:c1fzvexe

iinventedlight. 2026. "PostgreSQL constraints: CHECK, NOT NULL, UNIQUE and foreign keys." iinventedlight Library, iil:note:c1fzvexe, version of 2026-11-04. https://iinventedlight.com/library/notes/postgres-constraints-foreign-keys/. License: CC-BY-4.0.

@misc{iil_note_c1fzvexe,
  author = {{iinventedlight}},
  title = {{PostgreSQL constraints: CHECK, NOT NULL, UNIQUE and foreign keys}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-04},
  url = {https://iinventedlight.com/library/notes/postgres-constraints-foreign-keys/},
  note = {Permanent ID iil:note:c1fzvexe. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com.

For language models and agents: start at /llms.txt. This page in Markdown: /library/notes/postgres-constraints-foreign-keys.md.