Question presented to candidate: "We keep finding negative prices and end dates before start dates in our products table. What is a CHECK constraint, how would you use one here, and what are its limits?"
What a strong answer should cover:
- A CHECK constraint is a boolean expression every row must satisfy on INSERT and UPDATE; a row is rejected only when the expression is FALSE
- A NULL (unknown) result passes, so CHECK does not replace NOT NULL
- Column-level vs table-level CHECKs, and naming constraints so errors are readable
- Limits: only the current row (no subqueries or other tables in PostgreSQL and SQLite); cross-row or cross-table rules need UNIQUE, foreign keys, exclusion constraints or triggers
- Adding one to a live table: PostgreSQL
NOT VALIDthenVALIDATE CONSTRAINT; SQLite cannot add one with ALTER TABLE - Engine facts: MySQL ignored CHECK before 8.0.16; SQLite type affinity can let a text value through a numeric check
Code / implementation expected: Yes β add CHECKs for price, a status list and a date window, and show what happens to a bad row and to a NULL.
Schema used by the examples: