SQL Window Functions: OVER, PARTITION BY and ORDER BY
How window functions compute values across related rows without collapsing them: the OVER clause, PARTITION BY, ORDER BY and running totals, the default frame and ties, where windows run in a query, why they can't go in WHERE, windows over grouped rows, and named windows.
kvi5hnuCode Sprout team member11 min readOn this page
GROUP BY answers "what's the average price per category?" by collapsing each category into a single row. Often you want that number next to each product, to compare the product with its category, or to show its share of the category's total. With GROUP BY alone, you'd compute the averages in a subquery and join them back. Window functions do it directly: they compute a value over a set of rows related to the current row, and add it to the row without removing anything.
Window functions are one of the most useful features of modern SQL. Running totals, rankings, moving averages, comparisons with the previous row and percentages of a total are all short, readable window queries. This article introduces the OVER clause and its two main parts, PARTITION BY and ORDER BY. The rest of Part 6 builds on it: ranking (article 27), frames for running and moving calculations (article 28), and access to neighbouring rows (article 29).
The OVER clause
A window function is a function followed by OVER (...). The parentheses describe the window: the set of rows the function looks at for the current row.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Each product with values computed over the whole table and over its category
SELECT name,
category,
price,
ROUND(AVG(price) OVER (), 2) AS avg_all,
ROUND(AVG(price) OVER (PARTITION BY category), 2) AS cat_avg,
COUNT(*) OVER (PARTITION BY category) AS in_category,
ROUND(100.0 * price / SUM(price) OVER (PARTITION BY category), 1) AS pct_of_category
FROM products
ORDER BY category, price;
name | category | price | avg_all | cat_avg | in_category | pct_of_category
-------------------+----------+--------+---------+---------+-------------+-----------------
Merino socks | clothing | 16.00 | 137.21 | 16.00 | 1 | 100.0
Basecamp lantern | lighting | 27.00 | 137.21 | 30.75 | 2 | 43.9
Glow head torch | lighting | 34.50 | 137.21 | 30.75 | 2 | 56.1
Day 18 backpack | packs | 54.00 | 137.21 | 71.98 | 2 | 37.5
Trail 30 backpack | packs | 89.95 | 137.21 | 71.98 | 2 | 62.5
Ridge 2 tent | tents | 249.99 | 137.21 | 369.50 | 2 | 33.8
Summit 4 tent | tents | 489.00 | 137.21 | 369.50 | 2 | 66.2
(7 rows)
Every product row is still there, with new columns:
AVG(price) OVER (): the empty parentheses make the window every row of the result, so each row shows the overall average, 137.21.AVG(price) OVER (PARTITION BY category):PARTITION BYsplits the rows into groups, called partitions, and each row's window is its own partition. So each row shows its category's average.COUNT(*) OVER (PARTITION BY category): the number of rows in the row's partition.price / SUM(price) OVER (PARTITION BY category): the row's share of its category's total. Mixing a row's own value with a value computed over its window is the typical use.

That's the key difference from GROUP BY:
GROUP BYreturns one row per group. A window function returns one value per row, computed over the row's window.
The familiar aggregates, COUNT, SUM, AVG, MIN and MAX, all work as window functions when you add OVER. There are also functions that only work with OVER, such as ROW_NUMBER, RANK and LAG, which the next articles cover.
PARTITION BY accepts several columns and expressions, just like GROUP BY: PARTITION BY category, brand makes one partition per (category, brand) pair. All NULLs go into the same partition, as they do in GROUP BY.
ORDER BY inside OVER: running totals
Adding ORDER BY inside OVER changes the window. For aggregate functions, the window becomes the rows from the start of the partition up to the current row, in that order. That turns SUM into a running total:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- A running total: ORDER BY inside OVER makes the window grow row by row
WITH order_values AS (
SELECT o.order_id, o.placed_on, SUM(oi.qty * oi.unit_price) AS value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.order_id, o.placed_on
)
SELECT order_id,
placed_on,
value,
SUM(value) OVER (ORDER BY placed_on) AS running_total,
COUNT(*) OVER (ORDER BY placed_on) AS orders_so_far
FROM order_values
ORDER BY placed_on;
-- With ties in the ORDER BY, tied rows are included together
SELECT day,
COUNT(*) OVER (ORDER BY day) AS rows_up_to_this_day
FROM (VALUES (DATE '2026-03-01'), (DATE '2026-03-01'), (DATE '2026-03-02')) AS v (day);
order_id | placed_on | value | running_total | orders_so_far
----------+------------+--------+---------------+---------------
101 | 2026-03-02 | 297.99 | 297.99 | 1
102 | 2026-03-05 | 69.00 | 366.99 | 2
103 | 2026-03-09 | 154.45 | 521.44 | 3
104 | 2026-03-15 | 489.00 | 1010.44 | 4
105 | 2026-03-20 | 54.00 | 1064.44 | 5
106 | 2026-03-22 | 16.00 | 1080.44 | 6
(6 rows)
day | rows_up_to_this_day
------------+---------------------
2026-03-01 | 2
2026-03-01 | 2
2026-03-02 | 3
(3 rows)
For order 101, the window holds one row, so the running total is 297.99. For order 102 it holds two rows, giving 366.99, and so on, until the last row's total equals the grand total, 1080.44. COUNT(*) with the same window counts the orders so far.
The ORDER BY inside OVER only defines the window. It doesn't sort the query's output. The final ORDER BY does that. They can differ, and often do: you might compute a running total by date and display the rows by customer.
Ties: the default frame
The second query shows a detail that surprises many people. Two rows share the date March 1. Both get 2, not 1 and 2. When OVER has an ORDER BY and no explicit frame, the window is defined as:
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
RANGE means "up to the current row and every row that ties with it in the ORDER BY". Rows with the same sort value are peers, and they're always included together. So a running total over non-unique dates jumps by all of the date's rows at once, and every row of that date shows the same total.
If you want the running total to advance one row at a time even through ties, say so with ROWS instead of RANGE, and add a tie-breaker to the ORDER BY so the order of tied rows is defined:
SUM(value) OVER (ORDER BY placed_on, order_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
Article 28 covers frames, ROWS, RANGE and GROUPS, in detail.
PARTITION BY and ORDER BY together
With both, the window restarts at each partition and grows in order within it:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- PARTITION BY and ORDER BY together: number each customer's orders, and count them
SELECT customer_id,
order_id,
placed_on,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY placed_on) AS nth_order,
COUNT(*) OVER (PARTITION BY customer_id) AS customer_orders
FROM orders
ORDER BY customer_id, placed_on;
customer_id | order_id | placed_on | nth_order | customer_orders
-------------+----------+------------+-----------+-----------------
1 | 101 | 2026-03-02 | 1 | 2
1 | 103 | 2026-03-09 | 2 | 2
2 | 102 | 2026-03-05 | 1 | 1
3 | 104 | 2026-03-15 | 1 | 1
4 | 105 | 2026-03-20 | 1 | 1
(null) | 106 | 2026-03-22 | 1 | 1
(6 rows)
ROW_NUMBER() numbers the rows of each partition from 1, in the ORDER BY order, so each customer's orders are numbered 1, 2, and so on. COUNT(*) with only PARTITION BY gives the partition's size. Together they answer questions like "is this the customer's first order?" (nth_order = 1) or "is it the last?" (nth_order = customer_orders). The guest order has a NULL customer, and forms a partition of its own.
Where window functions run in a query
Window functions are computed late in the logical processing order from article 4:
FROMand joinsWHEREGROUP BYHAVING- window functions
SELECTlist (the rest of it),DISTINCTORDER BYLIMIT/OFFSET/FETCH
Three consequences follow, and each one matters in practice.
1. Window functions can't be used in WHERE, GROUP BY or HAVING, because those clauses run before the windows are computed:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Window functions can't be used in WHERE
SELECT name, price
FROM products
WHERE price > AVG(price) OVER (PARTITION BY category);
-- Compute the window in a derived table (or CTE), then filter
SELECT name, category, price, ROUND(cat_avg, 2) AS cat_avg
FROM (SELECT name, category, price,
AVG(price) OVER (PARTITION BY category) AS cat_avg
FROM products) AS t
WHERE price > cat_avg
ORDER BY category;
psql:/workspace/solution.sql:22: ERROR: window functions are not allowed in WHERE
LINE 3: WHERE price > AVG(price) OVER (PARTITION BY category);
^
name | category | price | cat_avg
-------------------+----------+--------+---------
Glow head torch | lighting | 34.50 | 30.75
Trail 30 backpack | packs | 89.95 | 71.98
Summit 4 tent | tents | 489.00 | 369.50
(3 rows)
To filter on a window function's result, compute it in a derived table or a CTE, and filter in the outer query, as in the second query. It finds the products priced above their category's average, the same result as the correlated subquery in article 23. Some systems, including Snowflake, BigQuery, DuckDB, Databricks, Teradata and Oracle AI Database 26ai, have a QUALIFY clause for filtering on window functions directly. PostgreSQL, MySQL and SQL Server don't, so the derived-table pattern is the portable one.
2. WHERE decides which rows the window sees, but ORDER BY and LIMIT don't:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- WHERE runs first, so the window only sees the rows that survive it
SELECT name, price,
COUNT(*) OVER () AS rows_in_window,
ROUND(AVG(price) OVER (), 2) AS avg_of_window
FROM products
WHERE category IN ('tents', 'packs')
ORDER BY price DESC
LIMIT 2; -- LIMIT runs after the window: still 4 rows seen
-- Windows over grouped rows: each category's share of the grand total
SELECT category,
SUM(price) AS category_total,
SUM(SUM(price)) OVER () AS grand_total,
ROUND(100 * SUM(price) / SUM(SUM(price)) OVER (), 1) AS pct
FROM products
GROUP BY category
ORDER BY category;
name | price | rows_in_window | avg_of_window
---------------+--------+----------------+---------------
Summit 4 tent | 489.00 | 4 | 220.74
Ridge 2 tent | 249.99 | 4 | 220.74
(2 rows)
category | category_total | grand_total | pct
----------+----------------+-------------+------
clothing | 16.00 | 960.44 | 1.7
lighting | 61.50 | 960.44 | 6.4
packs | 143.95 | 960.44 | 15.0
tents | 738.99 | 960.44 | 76.9
(4 rows)
In the first query, WHERE keeps the four tents and packs, so the window holds four rows, and the average is over those four. The LIMIT 2 removes rows only after the window functions have been computed, so the two rows shown still report a window of 4 rows. If you want a window over "the top 2", select the top 2 first, in a subquery.
3. Window functions can be applied to grouped results. In the second query, GROUP BY produces one row per category, and SUM(SUM(price)) OVER () then adds up the four category totals. The inner SUM is the grouped aggregate, and the outer SUM ... OVER () is a window function over the grouped rows. It looks strange at first, but it follows directly from the order of evaluation: windows run after grouping, so they see the groups. The result is each category's percentage of the total, in one query.
Named windows
When several functions use the same window, the WINDOW clause names it once:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- A named window, defined once and used by several functions
SELECT name,
category,
price,
MIN(price) OVER w AS cheapest_in_category,
MAX(price) OVER w AS dearest_in_category,
COUNT(*) OVER w AS in_category
FROM products
WINDOW w AS (PARTITION BY category)
ORDER BY category, price;
name | category | price | cheapest_in_category | dearest_in_category | in_category
-------------------+----------+--------+----------------------+---------------------+-------------
Merino socks | clothing | 16.00 | 16.00 | 16.00 | 1
Basecamp lantern | lighting | 27.00 | 27.00 | 34.50 | 2
Glow head torch | lighting | 34.50 | 27.00 | 34.50 | 2
Day 18 backpack | packs | 54.00 | 54.00 | 89.95 | 2
Trail 30 backpack | packs | 89.95 | 54.00 | 89.95 | 2
Ridge 2 tent | tents | 249.99 | 249.99 | 489.00 | 2
Summit 4 tent | tents | 489.00 | 249.99 | 489.00 | 2
(7 rows)
WINDOW w AS (PARTITION BY category) comes after HAVING (if any) and before ORDER BY. Each OVER w refers to it. A named window can also be extended: OVER (w ORDER BY price) adds an ORDER BY to the named partitioning. The WINDOW clause is supported by PostgreSQL, MySQL, SQLite, Oracle 21c and later, and SQL Server 2022 and later.
Window functions versus the alternatives
Before window functions, the same results needed joins or correlated subqueries. Compare three ways of putting the category average on each row:
| Approach | Query shape |
|---|---|
| Correlated subquery | (SELECT AVG(p2.price) FROM products p2 WHERE p2.category = p.category) in the SELECT list |
| Join to a grouped derived table | JOIN (SELECT category, AVG(price) AS a FROM products GROUP BY category) g USING (category) |
| Window function | AVG(price) OVER (PARTITION BY category) |
The window version is the shortest, and it reads the table once. The others are still useful in databases without window functions, and the correlated subquery can be faster when you only need a few rows and there's a suitable index. For running totals, rankings and comparisons between rows, windows are far simpler than any alternative.
Support
Window functions are supported by PostgreSQL (8.4+), Oracle, SQL Server (2005+, with frames from 2012), MySQL (8.0+), MariaDB (10.2+) and SQLite (3.25+). MySQL 5.7 has none, which still matters for older systems.
What's current
- SQL Server 2022 added the
WINDOWclause andIGNORE NULLSfor some window functions. - Oracle 21c added the
WINDOWclause andGROUPSframes. - PostgreSQL 16 lets functions such as
ROW_NUMBERandRANK, whose result doesn't depend on the frame, run in the fasterROWSmode internally even when the defaultRANGEframe is in effect. QUALIFYfor filtering on window results is in analytical systems such as Snowflake, BigQuery, DuckDB and Databricks, and in Oracle AI Database 26ai (release 23.26).
Common questions
What's the difference between GROUP BY and PARTITION BY?
GROUP BY collapses each group into one row. PARTITION BY, inside OVER, only defines which rows a window function looks at. Every row is kept.
Why doesn't my running total increase on every row?
Several rows have the same ORDER BY value. The default RANGE frame includes all peers, so they share one total. Use ROWS and a unique tie-breaker.
Does ORDER BY inside OVER sort the result?
No. It only orders the rows within each window. Add a final ORDER BY to sort the output.
Can I filter on a window function?
Not in WHERE or HAVING. Compute it in a derived table or CTE and filter in the outer query.
Can I use a window function in ORDER BY?
Yes. ORDER BY runs after the windows, so ORDER BY SUM(price) OVER (PARTITION BY category) DESC is allowed.
What does OVER () mean?
A window that contains all the rows of the result, after WHERE, GROUP BY and HAVING. Every row gets the same value.
Can I combine window functions with GROUP BY?
Yes. The window functions then run over the grouped rows, so they can use the group aggregates, as in SUM(SUM(x)) OVER ().
Are window functions slow? They usually need the rows sorted by the partition and order columns, which costs a sort unless an index provides that order. One window query is generally faster than the equivalent self-join or correlated subquery.
Summary
- A window function is a function with an
OVERclause. It computes a value over a set of related rows and returns it on every row, without collapsing rows. OVER ()uses all rows.PARTITION BYsplits the rows into independent partitions.ORDER BYinsideOVERmakes aggregates cumulative: the window runs from the start of the partition to the current row and, by default, its peers.- Window functions run after
WHERE,GROUP BYandHAVING, and beforeORDER BYandLIMIT. Filter on them in an outer query. - They can be applied to grouped results, as in
SUM(SUM(x)) OVER (). - The
WINDOWclause names a window for reuse.
Practice questions
Write a query that shows each product's name, price and the price of the most expensive product in its category.
Answer
SELECT name, category, price,
MAX(price) OVER (PARTITION BY category) AS category_max
FROM products
ORDER BY category, price;
Both tents show 489.00, both packs 89.95, both lighting products 34.50, and the socks 16.00.
What does COUNT(*) OVER () return on each row of SELECT name, COUNT(*) OVER () FROM products WHERE price < 50?
Answer
3 on each of the three rows. WHERE runs first and keeps the socks, the lantern and the head torch, and OVER () makes the window all remaining rows.
A query computes SUM(amount) OVER (ORDER BY sale_date) and several sales share each date. Why do rows with the same date show the same running total, and how do you make it increase on every row?
Answer
Without an explicit frame, ORDER BY in OVER gives a RANGE frame that includes all peers, rows with the same sale_date, so they all get the total up to the end of that date. To advance row by row, use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW and add a unique tie-breaker, such as ORDER BY sale_date, sale_id.
Write a query that lists each customer's orders with the order number within that customer (1 for the first order by date), and keep only each customer's first order.
Answer
SELECT customer_id, order_id, placed_on
FROM (SELECT customer_id, order_id, placed_on,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY placed_on) AS nth
FROM orders
WHERE customer_id IS NOT NULL) AS t
WHERE nth = 1
ORDER BY customer_id;
The window function can't be filtered in the same query's WHERE, so it's computed in a derived table. The result is orders 101, 102, 104 and 105.
What does SUM(COUNT(*)) OVER () compute in SELECT category, COUNT(*), SUM(COUNT(*)) OVER () FROM products GROUP BY category?
Answer
The total number of products, 7, on every row. COUNT(*) is computed per category by GROUP BY, and the window function then adds up those per-category counts across all the grouped rows.
Previous: Recursive CTEs: Sequences, Hierarchies and Graph Walks
Next: Ranking in SQL: ROW_NUMBER, RANK, DENSE_RANK, NTILE and Top-N per Group

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.