How can you use SQL to identify and resolve data anomalies?
Instruction: Discuss the types of data anomalies that can occur in a database and illustrate with SQL queries how you would identify and resolve such anomalies.
Updated
Official answer
Define the invariant before calling a row anomalous. For a rule that non-NULL email values should be unique, PostgreSQL can identify candidates:
SELECT email, COUNT(*) AS occurrences
FROM users
WHERE email IS NOT NULL
GROUP BY email
HAVING COUNT(*) > 1;
This is case-sensitive according to the column's comparison semantics; apply a separately defined canonicalization rule if needed. A unique row ID would not identify repeated real-world entities by itself.
To compare corresponding records while detecting a NULL-versus-value mismatch:
SELECT a.user_id, a.email AS email_a, b.email AS email_b
FROM table_a a
JOIN table_b b ON b.user_id = a.user_id
WHERE a.email IS DISTINCT FROM b.email;
For an optional parent relationship, distinguish NULL from an invalid non-NULL reference:
SELECT c.*
FROM child_table c
WHERE c.parent_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM parent_table p WHERE p.id = c.parent_id);
Investigate against an authoritative source, preserve related records and record an approved correction or merge. Recheck exact expected state in a transaction and reconcile afterward. Do not invent a parent or delete uncertain rows merely to clear an alert. Add appropriate constraints and repair the ingestion cause.