liveBook · Manning

Check constraint

As explained in Just Use Postgres!

A check constraint is a database rule that rejects a row when a specified Boolean condition is false.

A check constraint is a database rule that verifies a column value against a custom condition and rejects writes that fail it. It moves data-integrity checks into PostgreSQL rather than relying only on application code. section 2.3.1

Adding and testing a price rule

Add the constraint with ALTER TABLE: ALTER TABLE products.catalog ADD CONSTRAINT catalog_price_check CHECK (price > 0); An attempted update setting Morning Glory to -16 fails with an error identifying catalog_price_check and the failing row.

How Just Use Postgres! covers it

How deep it goes
Defines custom Boolean conditions and demonstrates CREATE TABLE, ALTER TABLE, inspection, and rejected writes.
Examples
Uses catalog categories, nonnegative stock, positive prices, review ranks, and pending-or-ordered order statuses.
What it assumes
Builds from SQL table definitions and ALTER TABLE operations while showing constraints both inline and after table creation.
What you can do after
Operate/configure PostgreSQL tables by declaring, adding, inspecting, and testing check constraints.
How it connects
Connects check constraints with NOT NULL, primary key, foreign key, unique, exclusion constraints, and application-level validation.

Also explained in

Compare how 2 books explain check constraint →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Just Use Postgres!. The section links point to the parts of the book it draws on.