facebook pixel
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
https://www.instagram.com/p/DU5FSWDEjV1
Posted on Instagram ยท

ย 311

ย 3

    Suggested Credits

    Credits on Gondola describe each credited role and may be incomplete. A brand or featured person is not necessarily the creator.

    Tags, Events, and Projects