UNION
SELECT employee_id AS person_id FROM full_time_employeesUNIONSELECT intern_id FROM interns;- Cost: the whole combined result is sorted or hashed to find duplicates
Two tables hold ids.
Table: full_time_employees
| employee_id |
|---|
| 1 |
| 2 |
| 3 |
Table: interns
| intern_id |
|---|
| 3 |
| 4 |
Task
Return one list of ids from both tables without duplicates. Then say when you would use UNION ALL instead.
Expected output
| person_id |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
Work out your query on your own, then open Answers & Optimization to compare.
Found a mistake in this question?
Report a problemA basic answer first, then the optimized one.
UNION removes duplicates, which needs a sort or hash step.UNION ALL keeps every row and skips that work, so it is faster.SELECT employee_id AS person_id FROM full_time_employeesUNIONSELECT intern_id FROM interns;-- Ids can never overlap between the tables? UNION ALL is enoughSELECT employee_id AS person_id FROM full_time_employeesUNION ALLSELECT intern_id FROM interns; -- Overlap possible, but employee_id is unique inside its own table:-- remove only the cross-table duplicates with an anti-joinSELECT employee_id AS person_idFROM full_time_employeesUNION ALLSELECT i.intern_idFROM interns iWHERE NOT EXISTS (SELECT 1 FROM full_time_employees f WHERE f.employee_id = i.intern_id);Log in to mark questions completed and keep your streak.
Log inSpotted a mistake in these answers?
Report a problem