Take care with nulls and never forget that SQL's three-valued logic is treats constraints differently i.e.
P(row) | WHERE P(row) | CHECK(P(row))
--------+--------------+-------------------------
TRUE | Row accepted | Row satisfies constraint
FALSE | Row rejected | Row violates constraint
UNKNOWN | Row rejected | Row satisfies constraint <-- careful here!
My personal approach is the write a SELECT * FROM
query and add columns returning a ternary value for each constraint:
SELECT T.*,
CASE
WHEN ( LEFT(Barcode, 1) <> 0 ) THEN 'TRUE'
WHEN NOT ( LEFT(Barcode, 1) <> 0 ) THEN 'FALSE'
ELSE 'UNKNOWN'
END AS result__Barcode__first_char_cannot_be_0,
CASE
WHEN ( LEFT(Foo, 1) <> 'X' ) THEN 'TRUE'
WHEN NOT ( LEFT(Foo, 1) <> 'X' ) THEN 'FALSE'
ELSE 'UNKNOWN'
END AS result__Foo__first_char_cannot_be_X
FROM YourTable AS T;
Alternatively:
SELECT T.*,
CASE
WHEN NOT ( LEFT(Barcode, 1) <> 0 ) THEN '{{violates constraint}}'
ELSE '{{satisfies constraint}}'
END AS result__Barcode__first_char_cannot_be_0,
CASE
WHEN NOT ( LEFT(Foo, 1) <> 'X' ) THEN '{{violates constraint}}'
ELSE '{{satisfies constraint}}'
END AS result__Foo__first_char_cannot_be_X
FROM YourTable AS T;
These results can be used for further analysis e.g. tally failure modes, tally failures per failure mode, (tally of) rows that satisify all constraints, (tally of) rows that fail at least one constraint, etc.
Consider using a unit test framework such as tSQLt to add data that would otherwise violate constraints that are actually in force (FakeTable
command in tSQLt): if your query doesn't highlight this data then you need to rewrite your query!
p.s. ensure you do not waste time testing the DBMS itself. If the constraint is declared and in force (not deferred, not in NO CHECK
mode, etc) then you should trust the DBMS. By all means query the INFORMATION SCHEMA to ensure an expected key exists on the required columns but there is simply no point in testing that the values comprising the key are actually unique: if they weren't then the DBMS would have a serious bug and we'd all know about it!