My query checked 1M rows... 1M times. I didn't know correlated subqueries did this. ๐
What I wrote:
SELECT
customer_id,
name,
(SELECT COUNT(*)
FROM orders o
WHERE o.customer_id = c.customer_id) as order_count
FROM customers c;
-- โฑ๏ธ 3 minutes 47 seconds
What actually happened:
For EACH customer โ Run the subquery
1M customers = 1M subqueries
Database: melting
The fix:
SELECT
c.customer_id,
c.name,
COUNT(o.order_id) as order_count
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.name;
-- โฑ๏ธ 1.2 seconds
The rule:
Correlated subquery = Loop in disguise
JOIN + GROUP BY = Run once
190x faster. Same data.
How many correlated subqueries are hiding in
your code right now? ๐
#SQL#Performance#DataEngineering#SQLTips