LEFT JOIN in SQL
A left join keeps every left row, filling the right side with NULL when nothing matches.
SELECT
c.id,
c.name,
COALESCE(SUM(o.total), 0) AS spent
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.id
AND o.status = 'paid'
GROUP BY c.id, c.name
ORDER BY spent DESC;
How it works
- Use it to find rows that have no partner at all.
IS NULLon a right-hand column isolates the unmatched rows.COALESCEturns a missing number into a zero.
Keywords and builtins used here
ANDASBYCOALESCEDESCFROMGROUPJOINLEFTONORDERSELECTSUMc
The run, in numbers
- Lines
- 10
- Characters to type
- 186
- Tokens
- 59
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 42 seconds.
Step 2 of 9 in Joins, step 10 of 22 in Joins & aggregation.