What are SQL Window Functions and how do they differ from GROUP BY?
Theoretical ConceptWindow functions perform calculations across a set of table rows related to the current row without collapsing the rows.
Comprehensive AnswerWhile a GROUP BY clause aggregates rows and collapses them into a single summary row per group, Window Functions (using the OVER clause with PARTITION BY and ORDER BY) compute aggregate or ranking values while preserving the original row-level identity. This makes them indispensable for running totals, moving averages, and finding the Nth highest value.
Code Demonstration-- Finding the top 2 highest scoring students in each course
WITH RankedStudents AS (
SELECT
student_name,
course_name,
score,
DENSE_RANK() OVER (PARTITION BY course_name ORDER BY score DESC) as rank_pos
FROM student_evaluations
)
SELECT student_name, course_name, score
FROM RankedStudents
WHERE rank_pos <= 2;
Calculating month-over-month revenue growth where each transaction row needs to display both the current transaction amount and the running cumulative total for the year.
Related follow-up question: What is the difference between RANK() and DENSE_RANK()?