+91 99301 12627
Python & SQL

SQL Window Functions Explained: ROW_NUMBER, RANK, LAG and Running Totals

By Mehul Prajapati

Grid of building windows representing SQL window functions over rows
On this page

Short answer: SQL window functions perform calculations across a set of rows related to the current row, without collapsing them like GROUP BY does. You write them with an OVER() clause, optionally using PARTITION BY to define groups and ORDER BY to define order. The most used are ROW_NUMBER, RANK, DENSE_RANK for ranking, LAG/LEAD for comparing with previous or next rows, and SUM()/AVG() OVER for running totals and moving averages. They are supported in MySQL 8+, PostgreSQL, SQL Server and other modern databases.

Key takeaways

  • Window functions keep every row; GROUP BY returns one row per group.
  • PARTITION BY = “per group”, ORDER BY inside OVER = “in this order”.
  • Know the difference between ROW_NUMBER, RANK and DENSE_RANK.
  • Top-N per group and month-over-month change are classic interview tasks.

Syntax

function_name(expression) OVER (
    PARTITION BY column
    ORDER BY column
    ROWS BETWEEN ... AND ...
)

Example table: sales

region month revenue
West 2026-01 100
West 2026-02 120
West 2026-03 120
North 2026-01 90
North 2026-02 110

GROUP BY vs window function

-- One row per region
SELECT region, SUM(revenue) AS total FROM sales GROUP BY region;

-- Every row, with the region total alongside
SELECT region, month, revenue,
       SUM(revenue) OVER (PARTITION BY region) AS region_total
FROM sales;

Ranking: ROW_NUMBER vs RANK vs DENSE_RANK

SELECT region, month, revenue,
  ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) AS rn,
  RANK()       OVER (PARTITION BY region ORDER BY revenue DESC) AS rnk,
  DENSE_RANK() OVER (PARTITION BY region ORDER BY revenue DESC) AS drnk
FROM sales;
West revenue ROW_NUMBER RANK DENSE_RANK
120 1 1 1
120 2 1 1
100 3 3 2
  • ROW_NUMBER: always unique (ties broken arbitrarily unless you add a tiebreaker)
  • RANK: ties share a rank, then it skips (1, 1, 3)
  • DENSE_RANK: ties share a rank, no gaps (1, 1, 2)

Top-N per group

WITH ranked AS (
  SELECT region, month, revenue,
         DENSE_RANK() OVER (PARTITION BY region ORDER BY revenue DESC) AS rnk
  FROM sales
)
SELECT * FROM ranked WHERE rnk <= 2;

You can’t filter on a window function directly in WHERE, so wrap it in a CTE or subquery.

LAG and LEAD: compare with previous or next rows

SELECT region, month, revenue,
  LAG(revenue) OVER (PARTITION BY region ORDER BY month) AS prev_revenue,
  revenue - LAG(revenue) OVER (PARTITION BY region ORDER BY month) AS change,
  ROUND(100.0 * (revenue - LAG(revenue) OVER (PARTITION BY region ORDER BY month))
        / LAG(revenue) OVER (PARTITION BY region ORDER BY month), 1) AS pct_change
FROM sales;

For West, February’s change is +20 (20%), and March’s is 0. The first month per region is NULL because there’s no previous row.

Running totals and moving averages

SELECT region, month, revenue,
  SUM(revenue) OVER (PARTITION BY region ORDER BY month
                     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total,
  AVG(revenue) OVER (PARTITION BY region ORDER BY month
                     ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg_3
FROM sales;

Why specify ROWS?

With ORDER BY and no frame, many databases default to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which treats rows with equal ORDER BY values as peers and can give surprising running totals. Specifying ROWS makes the frame explicit.

Other useful window functions

Function Use
NTILE(4) Split rows into quartiles or buckets
FIRST_VALUE / LAST_VALUE First or last value in the window
PERCENT_RANK / CUME_DIST Relative position as a percentage
COUNT(*) OVER (...) Group size alongside each row

Interview-style questions

  • Find the second-highest salary in each department (DENSE_RANK = 2)
  • Remove duplicates, keeping the latest record (ROW_NUMBER, keep rn = 1)
  • Calculate month-over-month growth (LAG)
  • Find each customer’s first order (ROW_NUMBER by order date)
  • Find users active on consecutive days (LAG on dates)

More practice: SQL interview questions.

Frequently asked questions

Does MySQL support window functions?

Yes, from MySQL 8.0 onwards. MySQL 5.7 and earlier do not.

What is the difference between PARTITION BY and GROUP BY?

GROUP BY collapses rows into one per group; PARTITION BY defines groups for the window calculation while keeping all rows.

Can I use window functions in WHERE?

No. Compute them in a CTE or subquery, then filter in the outer query (some databases, such as Snowflake and BigQuery, offer QUALIFY).

Are window functions used in data science?

Yes: for feature engineering (lags, rolling averages), cohort analysis and deduplication before modelling. See SQL for data science.

Conclusion

SQL window functions let you rank, compare and accumulate values while keeping every row. Learn OVER, PARTITION BY and ORDER BY, master ROW_NUMBER/RANK/DENSE_RANK and LAG/LEAD, and you’ll be ready for most analytics and interview tasks. Start with SQL joins if you haven’t already.

Practise advanced SQL in our MySQL course.

Learn with Mehul Prajapati in Borivali West

At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.

Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072

Visit the centre or call us to choose the right course and batch and to know the current fee structure.