Xorthax the Merchant needed a way to analyze his trading data without losing detail. He didn’t want a single total—he wanted insight on every row. That’s what SQL window functions do.
A window function performs a calculation across a set of rows and returns a result for each row.
Every window function uses the OVER() clause:
FUNCTION(...) OVER ()
At its simplest, this means:
You can think of OVER() as defining the group of rows the function can “see.”
| OrderID | CustomerID | Amount |
|---|---|---|
| 1 | A | 100 |
| 2 | B | 200 |
| 3 | C | 300 |
SELECT OrderID, Amount,
SUM(Amount) OVER () AS TotalAmount
FROM Orders;
Result:
| OrderID | Amount | TotalAmount |
|---|---|---|
| 1 | 100 | 600 |
| 2 | 200 | 600 |
| 3 | 300 | 600 |
The total (600) is calculated across all rows and shown on every row.
SUM(Amount) calculates a total across the dataset, and OVER() tells SQL:
That’s the foundation of all window functions.
For each order, show the total revenue across all orders using a window function.
| Column | Type |
|---|---|
| orderid | bigint |
| customerid | bigint |
| orderdate | timestamp without time zone |
| totalamount | double precision |
| status | text |
| Column |
|---|
| orderid |
| totalamount |
| total_revenue |
Right now, OVER() is looking at all rows.
Next, you’ll learn how to split your data into groups so each calculation resets.