SQL Window Functions Explained: OVER and PARTITION BY

Window functions put a group result on every row. OVER(), PARTITION BY and ORDER BY explained with running totals, and how they differ from GROUP BY.

In this chapter

OVER(): a group result on every row

SQL window functions: common questions

What is the difference between GROUP BY and a window function?

GROUP BY returns one row per group. A window function keeps every row and adds the group result beside it.

What does PARTITION BY do?

It splits rows into groups for the window function, like GROUP BY, without collapsing them.

More on Window functions

Keep learning

Overview

chapters · window functions OVER() adds a group's result to every row, without merging the rows You want each product's price next to its category's average. GROUP BY can work out the average, but it merges each category into one row, so the products disappear. Write OVER (PARTITION BY category) after AVG(price) instead: the database works out the same average, then writes it on every row of that category. 6 rows in, 6 rows out. 2 rows: the products are gone How to read AVG(price) OVER (PARTITION BY category) Read it left to right AVG(price)what to calculate

1. GROUP BY squashes. OVER() does not.

Click through the three versions. Watch the row count: 6 in, then 2 out or 6 out. Click a product to see exactly which rows feed its average.

2. Three things go inside OVER()

PARTITION BY Which rows are neighbours. One window per shop, per customer, per category. Leave it out and the whole table is one window. ORDER BY The line-up inside the window. Needed for ranking, running totals, LAG/LEAD and FIRST_VALUE. It does not sort your final output. Frame (ROWS BETWEEN) How far from the current row the calculation may look: all of it, everything so far, or just the last 3 rows. Move the current row down the list and change the frame. The green rows are the ones the calculation uses for the blue row. ! Real-life check A running total ("sales so far this month") is SUM(...) OVER (PARTITION BY shop ORDER BY day). A 7-day moving average is the same with ROWS BETWEEN 6 PRECEDING AND CURRENT ROW. Careful: once you write ORDER BY inside OVER(), the default frame becomes "start to here", so SUM(x) OVER () is a grand total but SUM(x) OVER (ORDER BY day) is a running total.

3. Numbering rows: ROW_NUMBER, RANK, DENSE_RANK

All three hand out 1, 2, 3 in the order you choose. They only differ when two rows tie. Try Price DESC with PARTITION BY on, then switch the filter to 2, 3, or 4 to see how many rows a "top N" query really keeps. ROW_NUMBER() 1, 2, 3, 4. Every row unique. Pick it when you need exactly one winner or exactly N rows. RANK() 1, 2, 3, 3, 5. Ties share a place and the next place is skipped, like a race with a dead heat. DENSE_RANK() 1, 2, 3, 3, 4. Ties share a place and nothing is skipped: "the third cheapest price level".

4. Keep the row where rn is 1

The classic job is "the most expensive product in each category", or "each customer's first order". Number the rows inside each group, then keep number 1. You cannot filter on the number in the same SELECT, because WHERE runs long before the window is computed: Order in which SQL runs FROM / JOIN GROUP BY window functions ORDER BY So wrap the numbering in a WITH (or a subquery) and filter outside. The same idea gives a customer's 1st, 2nd and 3rd order: PARTITION BY CustomerID ORDER BY OrderDate. In the Northwind sample, ALFKI's orders get 1, 2, 3 and ANATR starts again at 1. ! Real-life check Snowflake, BigQuery and Teradata have a QUALIFY clause that filters on a window directly. MySQL, PostgreSQL and SQL Server do not, so the WITH wrapper is the standard way. If two rows tie for first, ROW_NUMBER keeps only one of them, and which one is not guaranteed: add a second column to ORDER BY.

5. The window family at a glance

Four jobs, the next chapters cover them one by one Real-life example Aggregate beside each row SUM, AVG, COUNT, MIN, MAX with OVER Running total, share of total, price vs category average Rank and bucket ROW_NUMBER, RANK, DENSE_RANK, NTILE Top 3 per team, salary quartiles Look at a neighbour LAG, LEAD Day-over-day change, time between orders Look at the edge of the window FIRST_VALUE, LAST_VALUE, NTH_VALUE Gap to the best price in the category ! Real-life check Window functions need MySQL 8.0 or newer (5.7 and older have none). PostgreSQL, SQL Server, Oracle, SQLite 3.25+ and MariaDB 10.2+ have them too, with the same core syntax. Windows can only appear in SELECT and ORDER BY, never in WHERE, GROUP BY or HAVING.

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.