Subquery vs Window Function — Which Wins?

Manish Sharma · Advanced ·📊 Data Analytics & Business Intelligence ·1mo ago

Key Takeaways

Compares Subquery and Window Function for scalable SQL queries

Full Transcript

This query fetches the highest paid employee from each department. It works, but look at what's happening. SQL ends up evaluating that correlated subquery repeatedly. Once for every single row in the table. In a small data set, fine, it's perfectly fine. >> [music] >> But in production, this kills your performance. There's a better [music] way to write this, and it's what interviewers actually want to see. We write this using row number, a window function. Partition by department {underscore} ID. This tells SQL [music] to restart ranking for each department. Order by salary descending. Highest salary gets rank one. Now, [music] every employee has a rank within their department. We just filter where RN equals to one. But here is where it gets powerful. Your manager changes his mind, [music] and now asks for top three performers per department. With the old query, you were rewriting the logic. It gets messy fast, right? But with this new approach, just change it to where RN less than equal to three. That's the [music] only change, one line. Window functions don't just make your query shorter, they make it scalable, readable, and production ready. I have covered every major window functions with real-world use cases and interview patterns [music] in my ebook Mastering SQL Window Functions. If you are serious about leveling up at work, >> [music] >> just check the pinned comment for the link of this book.

Original Description

Most SQL developers write correlated subqueries without realising the performance cost. For every row SQL processes, that subquery runs again. At scale, this becomes a serious problem.ROW_NUMBER fixes this — and makes your query scalable with one line change Many struggle to write confident SQL queries, especially when it comes to advanced concepts like window functions. This video addresses common sql problems and demonstrates how mistakes in sql queries can lead to production systems failures. Dive into understanding window functions and see both incorrect and correct SQL code examples. If you want to go deeper into real-world SQL concepts, grab a copy of my book Mastering SQL Window Functions 📘 ------------------------------------------------------------------------ ►►►LINKS◄◄◄ vidIQ to grow your channel faster! 🚀 https://vidiq.com/ManishSharma
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Related Reads

Up next
Data Don't Lie | Powered by the UFC Insight Engine from IBM watsonx
IBM
Watch →