Deviopath › PostgreSQL

Clean Up, Then Lock It Down

Medium · Constraints

ALTER TABLE t ADD CONSTRAINT name CHECK (condition) adds a rule that every row must follow. Postgres checks the existing rows first and refuses to add the constraint if any row breaks it, so bad data has to be fixed before.

Some products have a negative stock, which is a data-entry error. Set those to 0, then add a CHECK constraint named stock_not_negative that requires stock >= 0.

The check shows the stock levels, the names of the CHECK constraints on products, and whether inserting a product with negative stock is now rejected.

Next: Every Day, Even the Quiet Ones