Find rows violating a business rule
Turn each business rule into a boolean condition, then select every row where at least one condition fails, optionally with the name of the rule it breaks.
The task
Domain rules say totals are never negative, shipped orders have a positive total, and no order is dated in the future. The schema enforces none of them, so you audit for violators before adding constraints.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT id, customer_id, status, total, order_date
FROM orders
WHERE total < 0
OR (status = 'shipped' AND total <= 0)
OR order_date > CURRENT_TIMESTAMP;
How it works
Each line of the WHERE clause is one business rule expressed as a predicate; OR-ing them collects every violator in a single pass. Keep the rules in one place and the query doubles as the definition of 'clean' for this table. A row with a NULL total or order_date fails none of these tests, because comparisons with NULL are unknown; add explicit IS NULL rules if a missing value is itself a violation. The future-date rule compares against CURRENT_TIMESTAMP because every engine and version has it (SQL Server only gained CURRENT_DATE in 2025); today's date sorts before the current timestamp, so only later days count as future.
Variations
Violations per rule
SELECT 'negative total' AS rule_name, COUNT(*) AS violations
FROM orders WHERE total < 0
UNION ALL
SELECT 'shipped with non-positive total', COUNT(*)
FROM orders WHERE status = 'shipped' AND total <= 0
UNION ALL
SELECT 'order dated in the future', COUNT(*)
FROM orders WHERE order_date > CURRENT_TIMESTAMP;
One row per violation, rule named
SELECT id, 'negative total' AS broken_rule
FROM orders WHERE total < 0
UNION ALL
SELECT id, 'shipped with non-positive total'
FROM orders WHERE status = 'shipped' AND total <= 0
UNION ALL
SELECT id, 'order dated in the future'
FROM orders WHERE order_date > CURRENT_TIMESTAMP
ORDER BY id, broken_rule;
Questions that come up
Should these rules become CHECK constraints?
Usually yes, once the existing violators are cleaned up. This query tells you the size of the cleanup, and the check-constraint-violation-preview recipe confirms no row would fail before you run ALTER TABLE. A CHECK accepts a row when its condition is unknown, so a NULL total passes CHECK (total >= 0); add NOT NULL to the column if that is not what you want.
Keep reading
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.