SQL Window Functions
A window function works out a value from a set of rows and puts it beside each row. Every row stays in the result, and the new value appears as an extra column.
Numbering the products
Headphones takes number 1 as the dearest product, and Pencil takes number 8 as the cheapest.
SELECT name, price, ROW_NUMBER() OVER (ORDER BY price DESC) AS row_num
FROM products
ORDER BY price DESC;The average beside every row
The same average, 20.1575, lands beside all eight rows, and no row drops out.
SELECT name, price, AVG(price) OVER () AS average_price
FROM products
ORDER BY price DESC;The same average, grouped
One row comes back instead of eight: 8 products, average price 20.1575.
SELECT COUNT(*) AS products, AVG(price) AS average_price
FROM products;Example
SELECT name, price, ROW_NUMBER() OVER (ORDER BY price DESC) AS row_num, ROUND(AVG(price) OVER (), 2) AS average_price
FROM products
ORDER BY price DESC
LIMIT 3;Key points
- Window function: a function that works over a set of rows and adds a value beside each row
- OVER: the clause that opens the window for a window function
- A window function leaves every row in place.
- GROUP BY folds rows away; a window function keeps them.
- ROW_NUMBER: a window function that numbers rows in order, starting at 1
- An aggregate inside OVER works the same way, and every row keeps its own value too.
In this example, ROW_NUMBER numbers the products from the dearest down, and only the first three rows are kept. AVG over all eight products sits beside each row, rounded to 20.16. The dearest three are Headphones, Backpack and Desk Lamp.
Try it Yourself
Edit the code, then press Run.
Running is simulated · DB Fiddle
Exercise
What does a window function do to the rows?