// SQL snippet

Preview rows failing a CHECK constraint

Express the planned CHECK as a predicate, then select rows where NOT (predicate) holds: exactly what ALTER TABLE ... ADD CONSTRAINT would reject.

Main statement
All engines

The task

You plan to add CHECK (total >= 0 AND (status <> 'shipped' OR total > 0)) to orders. If any existing row fails it, the ALTER fails; this preview finds the blockers first.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
-- Planned constraint:
-- CHECK (total >= 0 AND (status <> 'shipped' OR total > 0))
SELECT id, status, total
FROM orders
WHERE NOT (total >= 0 AND (status <> 'shipped' OR total > 0));

How it works

A CHECK constraint rejects a row only when its predicate is false; true and unknown (a NULL somewhere in the comparison) both pass. A WHERE clause keeps only rows where its condition is true, so WHERE NOT (predicate) returns exactly the rows where the predicate is false: the ones ALTER TABLE would reject. Rows with a NULL total make both sides unknown and are correctly left out, since the constraint would accept them. An empty result means the constraint can be added right now. (SQL Server can also add it WITH NOCHECK and skip existing rows, but then the optimizer treats the constraint as untrusted.)

Variations

Count the blockers per violation kind

SELECT 'negative total' AS violation, COUNT(*) AS rows_blocked
FROM orders WHERE NOT (total >= 0)
UNION ALL
SELECT 'shipped with non-positive total', COUNT(*)
FROM orders WHERE status = 'shipped' AND NOT (total > 0);

Questions that come up

Why wrap the predicate in NOT instead of rewriting it?

Because hand-inverting a compound rule is where previews go wrong. NOT (total >= 0 AND (status <> 'shipped' OR total > 0)) is guaranteed to be the exact complement of what the CHECK tests, with the same NULL behavior; a rewritten version such as total < 0 OR (status = 'shipped' AND total <= 0) happens to match here, but one misplaced parenthesis or flipped operator in a bigger rule and the preview no longer predicts the ALTER.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.