Compare employees to employeesarchive: return empid, name, and a side column (liveonly or archiveonly) for rows whose…
SQLLevel: IntermediateDuplicates and data quality
Compare employees to employees_archive: return emp_id, name, and a side column (live_only or archive_only) for rows whose FULL column set does not match the other table. Changed rows appear on both sides; missing or extra rows on one.
Table definitions (from the source exercise):
CREATE TABLE employees(emp_id INTEGER PRIMARY KEY, name TEXT, department_id INTEGER, manager_id INTEGER, salary INTEGER, hire_date TEXT, job_title TEXT, gender TEXT);
CREATE TABLE employees_archive(emp_id INTEGER PRIMARY KEY, name TEXT, department_id INTEGER, manager_id INTEGER, salary INTEGER, hire_date TEXT, job_title TEXT, gender TEXT);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: Two anti-joins matching on every column, glued with UNION ALL. NOT EXISTS with all columns compared is cleanest.
SELECT e.emp_id, e.name, 'live_only' AS side
FROM employees e
WHERE NOT EXISTS (
SELECT 1 FROM employees_archive a
WHERE a.emp_id = e.emp_id AND a.name = e.name
AND a.department_id = e.department_id
AND COALESCE(a.manager_id, -1) = COALESCE(e.manager_id, -1)
AND a.salary = e.salary AND a.hire_date = e.hire_date
AND a.job_title = e.job_title AND a.gender = e.gender
)
UNION ALL
SELECT a.emp_id, a.name, 'archive_only'
FROM employees_archive a
WHERE NOT EXISTS (
SELECT 1 FROM employees e
WHERE e.emp_id = a.emp_id AND e.name = a.name
AND e.department_id = a.department_id
AND COALESCE(e.manager_id, -1) = COALESCE(a.manager_id, -1)
AND e.salary = a.salary AND e.hire_date = a.hire_date
AND e.job_title = a.job_title AND e.gender = a.gender
);
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT