PgPostgreSQL Lab
GitHub
Browser investigation

Make invalid data impossible

Two application paths disagree about whether an order may have a negative total. Encode the rule where every writer must obey it.

You will learn to use checks, uniqueness, and foreign keys, reason about NULL, and distinguish statement-time checks from deferred validation. Prerequisite: basic DDL and transactions. The first editor creates the payment table used by the rest of the chapter.

The page loads a fresh order dataset automatically. Select Run SQL in each numbered editor in order. The editors share one database, so later experiments use changes from earlier ones.

Sections on this page

Put the invariant in the schema

An invariant is a condition that must remain true after valid changes. A CHECK rejects a row when its expression is false. Predict whether a missing amount makes the following check false.

Enable JavaScript to start the browser database.
SQL 01
Ctrl / ⌘ + Enter

Both rows are accepted. SQL has an unknown truth value for comparisons involving NULL; a CHECK accepts true or unknown. Ordinary UNIQUE also allows multiple NULL values by default. Missing data and invalid data need separate rules.

Observe a rejected statement

For this exercise, a temporary helper executes a statement and returns its error as a query result. The exception block rolls back that attempted statement. This makes failures visible without stopping the lesson; catching every error is not a production validation strategy.

SQL 02
Ctrl / ⌘ + Enter

Predict which existing row prevents adding NOT NULL. Repair that row and apply the stronger rule.

SQL 03
Ctrl / ⌘ + Enter

Read result for the first ALTER and the final insert. The ALTER identifies the preexisting NULL. The next statements fill it and add the required-value rule. The final insert tests that new rule. If missing references should conflict too, PostgreSQL supports UNIQUE NULLS NOT DISTINCT; choose that behavior explicitly instead of assuming all uniqueness works alike.

Protect relationships

A foreign key requires a non-NULL reference to match a referenced unique key. Predict whether a payment can refer to an account that does not exist yet.

SQL 04
Ctrl / ⌘ + Enter

The transaction temporarily contains an unresolved reference. Because this constraint is deferred, PostgreSQL checks it at commit, after the account exists. Deferral does not waive the rule. A nondeferrable constraint would reject the insert immediately. SET CONSTRAINTS ... IMMEDIATE can bring a deferred check forward within a transaction.

Define deletion behavior

Predict which constraint the delete will violate. The default foreign-key action protects a referenced account from deletion.

The helper catches statement errors, while an initially deferred foreign key can fail only when the surrounding execution commits. Make this foreign key immediate by default before testing the delete, so the helper can return that statement's error. Changing validation timing does not change the rule.

SQL 05
Ctrl / ⌘ + Enter

Compare the delete's result with accounts_remaining. The failed delete leaves account 9 in place. ON DELETE CASCADE instead makes deleting a parent delete its children. A foreign key also does not automatically create an index on its referencing columns; check parent-delete and join workloads separately before adding one.

Explain the rule

Why did the first NULL amount pass? Why could the deferred insert refer to account 9 before it existed? Which rule determines whether deleting an account deletes its payments?

A hint for explaining the results

Separate the truth value of a check, the timing of validation, and the action chosen for deletion.

Worked explanation

A NULL comparison is unknown, so the CHECK does not reject it. NOT NULL closes that gap. The deferred foreign key permits temporary inconsistency inside the transaction, but the committed state must contain the account. Deletion behavior comes from the declared foreign-key action; default protection and cascading deletion encode different business rules.

Transfer the idea

After the original experiments, replace SQL 05 with the following and select Run SQL. The helper in this chapter reports each rejected write in its own result.

CREATE TABLE reservation_demo (
  starts_at timestamp NOT NULL,
  ends_at timestamp NOT NULL CHECK (ends_at > starts_at)
);
SELECT pg_temp.attempt($$INSERT INTO reservation_demo VALUES ('2025-01-01', '2025-01-01')$$) AS empty_duration;
SELECT pg_temp.attempt($$INSERT INTO reservation_demo VALUES (NULL, '2025-01-02')$$) AS missing_start;

Which constraint name or column appears in each message? A row-level check compares the two values on one reservation. To reject overlaps with another row, research exclusion constraints.

Next: work with sets and windows.

Primary sources: Constraints and SET CONSTRAINTS.