So far, Xorthax has used window frames to look at rows behind the current row. But what if he wants to look further back—or even ahead?
There are a few more options that give you more control over your window.
Window frames can be defined using additional keywords:
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
These let you extend the frame to the beginning or end of the dataset.
| OrderDate | Amount |
|---|---|
| 2024-01-01 | 100 |
| 2024-01-05 | 150 |
| 2024-01-10 | 200 |
SELECT OrderDate, Amount,
SUM(Amount) OVER (
ORDER BY OrderDate
ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
) AS FutureTotal
FROM Orders;
Result:
| OrderDate | Amount | FutureTotal |
|---|---|---|
| 2024-01-01 | 100 | 450 |
| 2024-01-05 | 150 | 350 |
| 2024-01-10 | 200 | 200 |
Each row now includes values from itself and all rows after it.
ORDER BY OrderDate defines the sequence.
The frame starts at the current row and extends forward to the end.
That means each row includes its own value plus all future values.
This is the opposite of a running total, which looks backward.
So far, you’ve used ROWS to define frames.
ROWS counts a fixed number of rows relative to the current row.
RANGE works differently—it groups rows with the same value in the ORDER BY column.
| OrderDate | Amount |
|---|---|
| 2024-01-01 | 100 |
| 2024-01-01 | 150 |
| 2024-01-05 | 200 |
SELECT OrderDate, Amount,
SUM(Amount) OVER (
ORDER BY OrderDate
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS Total
FROM Orders;
Result:
| OrderDate | Amount | Total |
|---|---|---|
| 2024-01-01 | 100 | 100 |
| 2024-01-01 | 150 | 250 |
| 2024-01-05 | 200 | 450 |
SELECT OrderDate, Amount,
SUM(Amount) OVER (
ORDER BY OrderDate
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS Total
FROM Orders;
Result:
| OrderDate | Amount | Total |
|---|---|---|
| 2024-01-01 | 100 | 250 |
| 2024-01-01 | 150 | 250 |
| 2024-01-05 | 200 | 450 |
With RANGE, both rows with the same date are included together.
With ROWS, each row is handled one at a time.
In most beginner cases, ROWS is easier to understand and gives more predictable results.
For each order, calculate the total remaining totalamount from the current order through all future orders based on orderdate.
| Column | Type |
|---|---|
| orderid | bigint |
| customerid | bigint |
| orderdate | timestamp without time zone |
| totalamount | double precision |
| status | text |
| Column |
|---|
| orderid |
| orderdate |
| totalamount |
| remaining_total |
Now that you understand how frames define groups and sequences, you can start comparing rows directly.
Next, you’ll learn how to look at previous and next rows.