Full answer
sql
CREATE TABLE pay_in (id INTEGER PRIMARY KEY, amount INTEGER);
CREATE TABLE pay_out (id INTEGER PRIMARY KEY, amount INTEGER);
INSERT INTO pay_in VALUES (1, 50), (2, 50), (3, 20);
INSERT INTO pay_out VALUES (1, 20);The query as written:
sql
SELECT amount FROM pay_in UNION SELECT -amount FROM pay_out ORDER BY amount;| amount |
|---|
| -20 |
| 20 |
| 50 |
The two payments of 50 appear once, so a total computed from this list is 50 short. UNION also sorts or hashes to find duplicates, which costs time on large inputs.
A corrected version:
sql
SELECT 'in' AS kind, id, amount FROM pay_in UNION ALL SELECT 'out', id, -amount FROM pay_out ORDER BY kind, id;| kind | id | amount |
|---|---|---|
| in | 1 | 50 |
| in | 2 | 50 |
| in | 3 | 20 |
| out | 1 | -20 |
UNION ALL keeps all four rows, and the kind and id columns make each row traceable. Summing the corrected list gives the net total:
sql
SELECT SUM(amount) AS net FROM (SELECT amount FROM pay_in UNION ALL SELECT -amount FROM pay_out);| net |
|---|
| 100 |
sql
CREATE TABLE pay_in (id INTEGER PRIMARY KEY, amount INTEGER);
CREATE TABLE pay_out (id INTEGER PRIMARY KEY, amount INTEGER);
INSERT INTO pay_in VALUES (1, 50), (2, 50), (3, 20);
INSERT INTO pay_out VALUES (1, 20);
SELECT amount FROM pay_in UNION SELECT -amount FROM pay_out ORDER BY amount;
SELECT 'in' AS kind, id, amount FROM pay_in UNION ALL SELECT 'out', id, -amount FROM pay_out ORDER BY kind, id;
SELECT SUM(amount) AS net FROM (SELECT amount FROM pay_in UNION ALL SELECT -amount FROM pay_out);Checked on SQLite 3.46.1, run twice with identical output.
Key points
- UNION removes duplicates
- UNION ALL keeps every row and is cheaper
- Add identifying columns to unioned events
Common mistakes
- Using UNION by habit
- Summing a deduplicated list
Follow-ups
- When is UNION the right choice?
- How would you compute the net total in one query?
Tips
- Say what UNION removed