Loading…
Window functions are a game-changer for data analysis. They perform calculations across a set of rows while keeping all rows in the result.
GROUP BY collapses rows:
SELECT category, COUNT(*) FROM products GROUP BY category;
-- Returns 3 rows (one per category)
Window functions keep ALL rows:
SELECT name, category, COUNT(*) OVER() as total
FROM products;
-- Returns 10 rows with a total column added
Assigns a unique sequential number to each row:
SELECT name, price,
ROW_NUMBER() OVER (ORDER BY price DESC) as rank
FROM products;
Result:
| name | price | rank |
|---|---|---|
| Laptop | 999 | 1 |
| Tablet | 499 | 2 |
| Phone | 299 | 3 |
Rank all products by price (highest = 1) and show name, price, and rank.
Downloading SQL engine… (one-time)
This runs entirely in your browser and is cached for next time.