# @dataengineeringtamil on Instagram

- **Type:** Image
- **Original URL:** https://www.instagram.com/p/DU5FSWDEjV1
- **Gondola URL:** https://gondola.cc/posts/63366115-dataengineeringtamil-instagram
- **Thumbnail:** https://img.gondola.cc/tr:w-,h-,fo-auto/postThumbnails/51dc87f27a.jpg
- **Posted:** 2026-02-18T08:05:29.000+00:00
- **Account Owner:** Data Engineering Tamil (@dataengineeringtamil) — https://gondola.cc/dataengineeringtamil

## Caption

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

## Stats

- **Views:** 0
- **Likes:** 311
- **Shares:** 0
- **Comments:** 3

## Tags

dataengineering, sqltips, sql, performance

---
Copyright (c) Gondola