Introduced in modern ANSI standards, Window Functions (also known as Analytic Functions) represent one of the most significant advancements in SQL. Unlike standard GROUP BY aggregations which collapse rows, window functions compute metrics across a sliding subset of rows (a window) while retaining every individual record in the output.
Figure 4.2: Window Function architecture showing row preservation with sliding partition calculations.
function_name() OVER (
[PARTITION BY partition_column]
[ORDER BY sort_column]
[ROWS|RANGE frame_clause]
)
Consider three students where two tie with identical GPAs of 3.85:
SELECT
first_name,
gpa,
ROW_NUMBER() OVER (ORDER BY gpa DESC) AS row_num,
RANK() OVER (ORDER BY gpa DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY gpa DESC) AS dense_rnk
FROM students;
| first_name | gpa | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|---|
| Pooja | 3.92 | 1 | 1 | 1 |
| Aman | 3.85 | 2 | 2 | 2 |
| Rahul | 3.85 | 3 | 2 | 2 |
| Neha | 3.68 | 4 | 4 (Skips 3!) | 3 (No Skip) |
By adding PARTITION BY course, ranks reset back to 1 for every distinct course:
-- Rank students within their respective courses
SELECT
student_id,
first_name,
course,
gpa,
DENSE_RANK() OVER (
PARTITION BY course
ORDER BY gpa DESC
) AS rank_in_course
FROM students;
Next, let us learn time-series analytics using SQL LEAD, LAG & Value Window Functions!
GROUP BY collapses multiple rows into a single summary row, losing individual row details. Window Functions perform aggregate or ranking calculations across a partition of rows while preserving every individual original row in the output.
ROW_NUMBER() assigns strictly consecutive integers (1, 2, 3, 4) with no ties. RANK() assigns the same rank to ties but skips ranks afterwards (1, 2, 2, 4). DENSE_RANK() assigns the same rank to ties without skipping subsequent ranks (1, 2, 2, 3).
Window functions execute in Step 5 (alongside SELECT), after WHERE, GROUP BY, and HAVING have executed.
Proceed to the next class in sequence to build production mastery of relational database architecture.
Continue to Class 43: LEAD & LAG Functions → Previous: ← Common Table Expressions | Full Syllabus
Accessing previous and subsequent rows without self-joins.
Preserving individual rows while displaying group sums.
Filtering on ROW_NUMBER() in a CTE to get top-1 per group.
Understanding default window framing (RANGE vs ROWS BETWEEN).