Skip to main content
SPARC - Sardar Patel Academy & Research Centre Open menu

SQL Window Functions: A Practical Guide for Data Analysts

Learn SQL window functions with tested examples: OVER, PARTITION BY, ROW_NUMBER, RANK, running totals, LAG and more. A practical guide for data analysts.

SQL Window Functions: A Practical Guide for Data Analysts

Every analyst eventually hits the same wall. You need each salesperson's revenue and their rank inside the region, or a sales figure that keeps growing as the month moves on. GROUP BY gives you totals, but it collapses rows and discards the detail. So you reach for self-joins and nested subqueries, and the query becomes hard to maintain.

SQL window functions remove that trade-off. They calculate across a set of related rows while keeping every original row in the output.

This guide explains how SQL window functions work, from the OVER clause to ranking, running totals and row-to-row comparisons, and then shows where they earn their place in everyday reporting. If SELECT, WHERE and GROUP BY still feel shaky, start with SQL queries explained easily.

Every query below was run on SQLite 3.45.1, and the result tables are the real output (decimals rounded for display). The syntax is standard, but frame options, date arithmetic and NULL ordering differ between engines, so notes appear wherever that matters.

Sample Data Setup

Run this once in PostgreSQL, MySQL 8, SQLite or SQL Server. The tables are tiny on purpose, so you can check every result by eye. New to joins? Start with SQL Joins with Examples, then come back.

CREATE TABLE sales_reps (rep VARCHAR(30), region VARCHAR(20), revenue INT);
INSERT INTO sales_reps VALUES
  ('Asha','North',9000), ('Bilal','North',7500),
  ('Chitra','North',7500), ('Dev','North',6000),
  ('Esha','South',8200), ('Farhan','South',8200),
  ('Gita','South',5400);

CREATE TABLE daily_orders (order_date DATE, amount INT);
INSERT INTO daily_orders VALUES
  ('2025-03-01',1200), ('2025-03-02',800), ('2025-03-03',1500),
  ('2025-03-04',700),  ('2025-03-05',1100);

CREATE TABLE monthly_revenue (month_start DATE, revenue INT);
INSERT INTO monthly_revenue VALUES
  ('2025-01-01',40000), ('2025-02-01',46000), ('2025-03-01',43000);

CREATE TABLE customers_raw (customer_id INT, email VARCHAR(40), updated_at DATE);
INSERT INTO customers_raw VALUES
  (1,'old@x.com','2025-01-10'), (1,'new@x.com','2025-03-02'),
  (2,'b@x.com','2025-02-14');

What Are SQL Window Functions?

A window function performs a calculation over a group of rows related to the current row and attaches the result to that row. Unlike a regular aggregate, it does not squash the group into one output line. The PostgreSQL tutorial on window functions describes it the same way: rows keep their separate identities. Some databases, BigQuery among them, call these analytic functions. It is the same idea under another name.

Picture a class register. GROUP BY would hand you one summary line per class. A window function leaves every student's line in place and adds a column beside it, such as "rank in this section" or "marks so far this term".

Window Functions vs GROUP BY



GROUP BY with aggregates


Window function


Rows returned

One per group

One per input row

Row-level detail

Lost unless grouped
Kept

Typical use

Totals and counts per group

Rankings, running totals, comparison with a group average

Key syntax

GROUP BY

OVER (...)

This query shows every rep's revenue beside the regional average:

SELECT rep, region, revenue,
       AVG(revenue) OVER (PARTITION BY region) AS region_avg
FROM sales_reps;
rep
region
revenue
region_avg
Asha
North
9000
7500.00
Bilal
North
7500
7500.00
Chitra
North
7500
7500.00
Dev
North
6000
7500.00
Esha
South
8200
7266.67
Farhan
South
8200
7266.67
Gita
South
5400
7266.67

SQL Server note: AVG on an INT column returns an integer there (7266, not 7266.67). Use AVG(revenue * 1.0) to get decimals.

A GROUP BY version would return two rows and drop the reps. Here every rep stays visible, and the comparison with the average sits one column away. That "detail plus context" pattern sits behind most SQL analytics queries.

How the OVER Clause Works

The OVER keyword right after a function is what makes it a window function. Inside the parentheses, you describe the window with up to three optional parts:

function_name(...) OVER (
    PARTITION BY column_list
    ORDER BY column_list
    ROWS BETWEEN ... AND ...
)

Leave all three out, as in OVER (), and the window becomes the entire result set. This is the part beginners usually find most confusing. If layered queries read slowly, work through them clause by clause: FROM, then WHERE, then GROUP BY, and SELECT last.

Here is how the parts act on the North partition when rows are ordered by revenue, highest first, and the current row is Chitra:


Row


Revenue


Inside the partition?


Inside the frame ROWS BETWEEN 2 PRECEDING AND CURRENT ROW?


Asha

9000
Yes
Yes
Bilal

7500
Yes
Yes

Chitra (current)

7500
Yes
Yes

Dev
6000
Yes

No, it comes after the current row

Esha, Farhan, Gita

South

No, a separate partition

No

PARTITION BY

Divides rows into independent groups. The function is calculated separately inside each group, much like GROUP BY but without collapsing anything.

ORDER BY

Sets the row order inside each partition. Ranking and row-to-row functions need it, because "first" or "previous" means nothing without an order. Watch out for NULLs: engines differ on whether they sort first or last. SQL Server treats NULL as the lowest possible value, while SQLite lets you write NULLS FIRST or NULLS LAST explicitly.

Window Frame

The frame narrows a partition to a range around the current row using ROWS or RANGE. For example, ROWS BETWEEN 2 PRECEDING AND CURRENT ROW covers three rows, as the SQL Server OVER clause documentation illustrates.

One default is worth memorising. When ORDER BY is present, and no frame is written, the frame runs from the start of the partition to the current row, plus any rows that tie with the current one. The next example uses a named window, a WINDOW clause that PostgreSQL, MySQL 8 and SQLite all support (SQL Server supports it from SQL Server 2022), to make that visible:

SELECT rep, region, revenue,
       RANK()       OVER w AS rnk,
       SUM(revenue) OVER w AS running_sum
FROM sales_reps
WINDOW w AS (PARTITION BY region ORDER BY revenue DESC);
rep
region
revenue
rnk
running_sum
Asha
North
9000
1
9000
Bilal
North
7500
2
24000
Chitra
North
7500
2
24000
Dev
North
6000
4
30000
Esha
South
8200
1
16400
Farhan
South
8200
1
16400
Gita
South
5400
3
21800

Two ties show up. In the North, Bilal and Chitra both show 24000, the total including both of them. In the South, Esha and Farhan share rank 1 and Gita jumps to 3, the same skip you will meet again in RANK. Remember this result; it explains the explicit frame we use for running totals later. You write the window once and reuse it, which keeps queries with several window functions short.

Ranking Rows with ROW_NUMBER, RANK and DENSE_RANK

Ranking is the usual first stop when learning SQL window functions. Here is the North region again, with all three ranking functions side by side:

SELECT rep, revenue,
       ROW_NUMBER() OVER (ORDER BY revenue DESC) AS row_num,
       RANK()       OVER (ORDER BY revenue DESC) AS rnk,
       DENSE_RANK() OVER (ORDER BY revenue DESC) AS dense_rnk
FROM sales_reps
WHERE region = 'North';
rep
revenue
row_num
rnk
dense_rnk
Asha
9000
1
1
1
Bilal
7500
2
2
2
Chitra
7500
3
2
2
Dev
6000
4
4
3

Bilal and Chitra are tied, and that is where the three functions part ways:

  • ROW_NUMBER never repeats a number. Tied rows get consecutive values in no guaranteed order, so add a tiebreaker such as rep if the output must be repeatable.
  • RANK gives tied rows the same position, then skips ahead. Dev lands at 4 because two reps share 2.
  • DENSE_RANK also repeats on ties but never skips, so Dev is 3. It suits questions like "who has the second-highest revenue?"

Ties are an easy place to slip, because "second-highest" means something different under RANK and DENSE_RANK. Working through SQL interview questions for freshers is a good way to make the distinction stick.

Top Performer per Region

Adding PARTITION BY restarts the numbering inside each region:

WITH ranked AS (
  SELECT rep, region, revenue,
         ROW_NUMBER() OVER (
           PARTITION BY region
           ORDER BY revenue DESC, rep
         ) AS rn
  FROM sales_reps
)
SELECT rep, region, revenue
FROM ranked
WHERE rn = 1;
rep
region
revenue
Asha
North
9000
Esha
South
8200

South has a tie between Esha and Farhan, and the rep tiebreaker settles it. The CTE is needed because window functions are evaluated after WHERE, GROUP BY and HAVING, so they are only allowed in the SELECT list and ORDER BY, a rule set out in the MySQL 8.0 documentation on window functions. Change rn = 1 to rn <= 3 for a top-three list per region, the classic "top N per group" pattern.

Running Totals and Moving Averages

Running totals are among the most requested uses of SQL window functions. A running total, also called a cumulative sum, is simply SUM() with an ORDER BY inside OVER:

SELECT order_date, amount,
       SUM(amount) OVER (
         ORDER BY order_date
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS running_total
FROM daily_orders;
order_date
amount
running_total
2026-03-01 1200
1200
2026-03-02 800 2000
2026-03-03 1500 3500
2026-03-04 700 4200
2026-03-05 1100 5300

Why spell out ROWS? Because of the default frame we saw earlier. If two orders share a date, the default treats them as peers, and both rows show the combined total, exactly as Bilal and Chitra did above. An explicit ROWS frame adds one row at a time and removes the ambiguity. To restart the total for each region, add PARTITION BY region.

For a moving average, shrink the frame:

SELECT order_date, amount,
       AVG(amount) OVER (
         ORDER BY order_date
         ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
       ) AS avg_3_day
FROM daily_orders;
order_date
amount
avg_3_day
2026-03-01 1200 1200.00
2026-03-02 800 1000.00
2026-03-03 1500 1166.67
2026-03-04 700 1000.00
2026-03-05 1100 1100.00

The first two rows average whatever rows exist so far, which is why 1200 and 1000 look different from the steady three-row values later on.

You can reproduce these calculations in pandas, but when the data already sits in a database, SQL saves you from pulling it all out first. SQL vs Python for an analytics career compares where each one fits.

LAG, LEAD and Other Functions for SQL Analytics Queries

Beyond ranking and totals, a second group of SQL window functions looks at other rows, or slices the result into buckets:


Function


What it returns


Typical use


LAG(col)

Value from a previous row

Month-over-month change

LEAD(col)

Value from a following row

Gap until the next event

FIRST_VALUE(col)

Value from the first row of the frame

Comparison with a starting point

NTILE(n)

Bucket number from 1 to n

Halves, quartiles and deciles

The BigQuery window function reference groups these under navigation and numbering functions, which is a handy way to browse the full list for any engine. First, a month-over-month comparison:

SELECT month_start, revenue,
       revenue - LAG(revenue) OVER (ORDER BY month_start) AS change_vs_prev
FROM monthly_revenue;
month_start
revenue
change_vs_prev
2026-01-01 40000 NULL
2026-02-01 46000 6000
2026-03-01 43000 -3000

The first month has no predecessor, so LAG returns NULL there. You can pass a default value as a third argument if you would rather see a number.

NTILE splits ordered rows into a chosen number of buckets. Here it labels each day as part of the stronger half or the weaker half by order amount:

SELECT order_date, amount,
       NTILE(2) OVER (ORDER BY amount DESC) AS half
FROM daily_orders
ORDER BY order_date;
order_date
amount
half
2026-03-01 1200
1
2026-03-02 800 2
2026-03-03 1500 1
2026-03-04 700 2
2026-03-05 1100 1

With five rows and two buckets, the first bucket gets three rows and the second gets two. Finally, "per cent of total" uses an empty OVER () so every row sees the grand total:

SELECT order_date, amount,
       ROUND(100.0 * amount / SUM(amount) OVER (), 1) AS pct_of_total
FROM daily_orders;
order_date
amount
pct_of_total
2026-03-01 1200 22.6
2026-03-02 800 15.1
2026-03-03 1500 28.3
2026-03-04 700 13.2
2026-03-05 1100 20.8

Where Analysts Use Window Functions in Real Work

The functions above are building blocks. In day-to-day SQL analytics queries, they usually show up in a handful of recurring jobs:

Task

Pattern


Keep the latest record per customer

ROW_NUMBER partitioned by customer, newest date first, keep rn = 1

Find each customer's first purchase

The same pattern with the oldest date first

Measure days between orders

LAG on the order date, then subtract (date arithmetic syntax varies by engine)

Show each item's share of a total

SUM() with an empty OVER

Top N per group

ROW_NUMBER or DENSE_RANK inside a CTE

De-duplication deserves a closer look because messy source tables are common. In customers_raw, customer 1 appears twice, and you want only the newest row:

WITH ordered AS (
  SELECT customer_id, email, updated_at,
         ROW_NUMBER() OVER (
           PARTITION BY customer_id
           ORDER BY updated_at DESC
         ) AS rn
  FROM customers_raw
)
SELECT customer_id, email, updated_at
FROM ordered
WHERE rn = 1;
customer_id
email
updated_at
1
new@x.com
2026-03-02
2
b@x.com
2026-03-02

Queries like this usually run against cleaned tables in an analytics store. If you are still sorting out where that data lives, it helps to understand how a data warehouse, a data lake and a lakehouse differ.

Running These Queries on Different Databases

Most modern databases support SQL window functions, but details differ, so check the documentation for your engine:

  • PostgreSQL and MySQL: both are documented in the references linked earlier. MySQL needs version 8.0 or later.
  • SQLite: support arrived in version 3.25.0; see the SQLite window function documentation.
  • SQL Server: ROWS and RANGE frames require SQL Server 2012 or later; the named WINDOW clause needs SQL Server 2022, and AVG on an integer column returns an integer.
  • BigQuery: window functions can also appear in a QUALIFY clause, which filters on them without a CTE.

A Note on Performance
Window calculations need the engine to group and sort rows. On large tables, read the execution plan before assuming anything is slow. An index that matches your PARTITION BY and ORDER BY columns can sometimes spare the engine an extra sort, though the benefit depends on the database and the data.

Common Mistakes to Avoid

  • Filtering on a window function in WHERE. Use a CTE or subquery, then filter outside (or QUALIFY where it exists).
  • Leaving ORDER BY out of OVER. Without it, a "running total" returns the partition total on every row.
  • Ignoring ties. ROW_NUMBER picks arbitrarily between equal values unless you add a tiebreaker.
  • Trusting the default frame. Write ROWS explicitly when you need one-row-at-a-time totals.
  • Over-partitioning. Partitioning by a unique column makes every group a single row.
  • Forgetting NULLs. Check how your engine sorts them before ranking a column that contains them.

A Simple Practice Path

Reading about SQL window functions only gets you so far. A short routine works better:

  1. Run the setup script, then each query above.
  2. Change one thing at a time, such as swapping RANK for DENSE_RANK, and note what shifts.
  3. Try the two exercises below.
  4. Move to a real dataset like orders or web traffic, and rewrite an old self-join as a window function.
Exercise 1. Using sales_reps, find the rep with the second-highest revenue in each region. Hint: DENSE_RANK inside a CTE.

Exercise 2.
Using daily_orders, find the day with the biggest increase over the previous day. Hint: LAG, then subtract.

Answers to check against:
Exercise 1 gives Bilal and Chitra (7500) for the North and Gita (5400) for the South. Exercise 2 gives 2025-03-03, up 700 from the day before.

If you prefer a guided route, the Data Analytics Course with AI at Sardar Patel Academy & Research Centre covers Excel, SQL, Python and Power BI across 8 months and 40+ projects.

Ready to practise SQL on real business datasets?

Advance Your SQL Skills

Conclusion

SQL window functions let you keep row-level detail while adding rankings, running totals and comparisons in the same result. Start with ROW_NUMBER, RANK and DENSE_RANK, then move on to cumulative sums and LAG, and use the set-up tables to test each idea before trying it on real data.

When you want structured practice, take a look at the programmes from Sardar Patel Academy & Research Centre.

About the publisher. Sardar Patel Academy & Research Centre has offered skill-based computer training in Delhi since 2003, with its flagship campus at Hudson Lane, GTB Nagar.

FAQs

SQL window functions calculate a value for each row using a related group of rows that you define with an OVER clause. The result keeps every row instead of shrinking the output.

GROUP BY returns one row per group. A window function returns one row per input row and adds the group-level calculation as a new column.

ROW_NUMBER gives every row a unique number. RANK repeats the number for ties and then skips the following positions. DENSE_RANK repeats the number for ties without skipping.

Use SUM() with OVER (ORDER BY your_column), and add ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW so that ties on the ordering column do not blur the result.

No. Window functions are only allowed in the SELECT list and in ORDER BY. Wrap the query in a CTE or subquery and filter on the alias, or use QUALIFY in databases that offer it.

Yes, the two names describe the same feature. BigQuery, for example, documents window functions as analytic functions. The syntax revolves around the same OVER clause.

Most current ones do, including PostgreSQL, MySQL 8.0 and later, SQLite 3.25.0 and later, SQL Server and BigQuery. Frame options, NULL ordering and date arithmetic vary, so confirm details against your version's documentation.

There is no universal answer. Window calculations need rows to be grouped and sorted, so speed depends on data size, indexes and the engine. Compare execution plans on your own data before drawing conclusions.

Sardar Patel Academy - SPARC Team

Career Guidance | Skill Development | Industry Insights | Educational Awareness

Sardar Patel Academy - SPARC Team is a dedicated group of education experts, career counselors, trainers, and content specialists focused on delivering practical and career-oriented educational guidance to students. The team specializes in creating reliable, easy-to-understand, and research-based content related to Digital Marketing, Commerce, Accounting, Skill Development, Career Opportunities, and Professional Courses. Through informative blogs, career updates, and industry-focused content, the SPARC Team helps students make smarter academic and career decisions. Their mission is to simplify learning and provide affordable, skill-based education opportunities for students from all backgrounds.

Read Full Bio

Start Your Career Journey Today

Join SPARC and become part of a community that believes in affordable, quality education

Areas We Serve : North Delhi| Rani Bagh| Janak Puri| Nangloi| Dwarka Mor| Nazafgarh
Call Now Chat Now