How would you write SQL to compare an expected dataset with an actual dataset and show differences?
Answer
Compare both directions, because expected EXCEPT actual detects missing or changed rows while actual EXCEPT expected detects unexpected rows. EXCEPT uses set semantics in many databases, so duplicate multiplicity may need an additional grouped comparison. Engines without EXCEPT can use joins or NOT EXISTS.
Strong answer includes
- compares expected-to-actual and actual-to-expected directions
- recognizes distinct-set behavior and duplicate-count limitations
- adapts the comparison for database dialect and NULL semantics
Practical example
Dialect · Portable SQLRuntime · SQLite sample DB
Runs against the resettable SQLite sample database used by the playground.
SQL
Result
Run the query to see the result.
EXCEPT returns distinct rows from the left result that are absent from the right result. Run EXCEPT in both directions to detect both missing and unexpected rows.
Expected result: Zero differences when expected and actual distinct datasets match.