Check Constraints Fire On Updates Too
CHECK constraints re-validate on UPDATE as well as INSERT, so a row that inserted cleanly can still fail when columns change.
Code
-- CHECK constraints fire on INSERT and UPDATE alike: a row that
-- inserted cleanly can still fail the moment an UPDATE bends it out of range
CREATE TABLE subscription (
user_id int PRIMARY KEY,
seats int NOT NULL CHECK (seats >= 1),
expires_on date NOT NULL CHECK (expires_on > DATE '2020-01-01')
);
INSERT INTO subscription VALUES (1, 5, DATE '2026-12-01'); -- satisfies the constraint on both sides
-- a row accepted on INSERT is stopped by the same constraint when UPDATE sets an invalid value:
-- UPDATE subscription SET seats = 0 WHERE user_id = 1;
-- -> ERROR: new row for relation "subscription" violates check constraint "subscription_seats_check"
-- the fix is to bring the column back to a valid value, not to drop the constraint
UPDATE subscription SET seats = 2 WHERE user_id = 1;
SELECT user_id, seats FROM subscription WHERE user_id = 1;How the snippet works
SELECT / INSERT / UPDATE / CREATE statements share the script, touching subscription.
Mechanically, the statements are built from: a WHERE clause limiting a statement to the rows that qualify; a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
The subscription table is the working surface here.
Statements that matter
SELECT user_id, seats FROM subscription WHERE user_id = 1;
UPDATE subscription SET seats = 2 WHERE user_id = 1;
CREATE TABLE subscription (
user_id int PRIMARY KEY,
seats int NOT NULL CHECK (seats >= 1),
expires_on date NOT NULL CHECK (expires_on > DATE '2020-01-01')
);
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What are the relations in play here?
- `subscription` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.