Problems / Efficient Distinct with GROUP BY / Editorial
The anti-pattern this problem teaches you to avoid:
```sql
-- BAD: Two passes over the data
SELECT d.resource, d.method, COUNT(*) ...
FROM (SELECT DISTINCT resource, method FROM access_log) d
JOIN access_log a ON d.resource = a.resource AND d.method = a.method
GROUP BY d.resource, d.method
```
The optimized approach:
SUM(CASE WHEN ... THEN 1 ELSE 0 END)
The anti-pattern scans the table twice and adds a self-join. With 400 rows it's fast, but with 1B rows:
Versus a single GROUP BY: O(n) — one pass, no join.
Solve Efficient Distinct with GROUP BY yourself →