PyCodeItPython trace & interview prep
DashboardMastery MapSQL PracticeDailyInterviewCompaniesBlogLeaderboardCommunity
Learning Center/sql
sql

Window Functions in SQL: RANK, ROW_NUMBER, and LEAD Explained

Aggregate without collapsing rows - the core skill data engineers and analysts get tested on.

AA

Ameer Abdullah

Data Science Graduate · AI/ML & Data Science

7 min read

Concept in Simple Words: Regular aggregate functions (like SUM or AVG) collapse multiple rows into a single summary row. Window functions perform calculations across a group of related rows, but they do NOT collapse the rows. Each row retains its individual identity while displaying the computed metric.

Deep Walkthrough & Code: Let's look at how ROW_NUMBER(), RANK(), and DENSE_RANK() assign ranking integers based on order criteria:

SELECT name, salary,
       ROW_NUMBER() OVER (ORDER BY salary DESC) as row_num,
       RANK() OVER (ORDER BY salary DESC) as rk,
       DENSE_RANK() OVER (ORDER BY salary DESC) as dense_rk
FROM employees;
Step-by-Step Dry Run: Suppose we have salaries [100k, 100k, 80k].
- Row 1 (100k): row_num = 1, rk = 1, dense_rk = 1.
- Row 2 (100k): row_num = 2 (unique index), rk = 1 (tie), dense_rk = 1 (tie).
- Row 3 (80k): row_num = 3, rk = 3 (skips 2 due to rank tie), dense_rk = 2 (next consecutive integer).
Understanding how rankings handle ties is a common interview screening question.

Production Level Issue & Fix: Running window functions without a PARTITION BY clause on tables with millions of rows forces the database to load the entire dataset into a single memory block to sort it, leading to disk-spill slowdowns. In production, always filter the dataset in a subquery or CTE first to reduce the volume of rows processed by the window function.

Practice what you just learned

Apply these concepts in PyCodeIt's interactive sandbox with real problems.

Open SQL Sandbox

Related SQL Tutorials

  • SQL Joins Explained for Technical Interview Candidates

    Read tutorial

  • CTEs vs Subqueries: When to Use Each and Why It Matters

    Read tutorial

  • GROUP BY and HAVING: The Misconceptions That Cause Wrong Answers

    Read tutorial

PyCodeIt

Free interactive learning platform for Python code tracing, SQL queries, and technical interviews. Built for bootcamp grads, computer science students, and engineers.

Python Practice

  • Learning Center
  • For loop tracing
  • List tracing
  • Dictionary tracing
  • Decorators practice
  • Python Tracing Guide
  • Python Output Questions

SQL Practice

  • SQL Fundamentals
  • Relational JOINs
  • Window Functions
  • CTEs & Set Operators
  • SQL JOINs Guide
  • Window Functions Guide

Legal

  • About
  • Contact
  • Privacy Policy
  • Terms of Service

© 2026 PyCodeIt. Sandbox keys are processed strictly client-side.