🧠 SQL ORDER BY in Window Functions: Control the Sequence

Xorthax had totals for each customer—but something still felt off. He couldn’t tell what happened first, what came next, or how values changed over time.

To make window functions more useful, he needed order.




🚀 ORDER BY + OVER()

ORDER BY inside a window function controls the sequence of rows.

FUNCTION(...) OVER (
  PARTITION BY column
  ORDER BY column
)

This tells SQL:

  • How to arrange rows within each group
  • What “first”, “next”, and “previous” mean



📊 Example: Same Data, Different Order

🧾 Sample Data

OrderIDCustomerIDOrderDateAmount
1A2024-01-10200
2A2024-01-01100
3A2024-01-05150

SELECT OrderID, OrderDate, Amount,
       SUM(Amount) OVER (
         PARTITION BY CustomerID
         ORDER BY OrderDate
       ) AS Value
FROM Orders;

Result:

OrderIDOrderDateAmountValue
22024-01-01100100
32024-01-05150250
12024-01-10200450

Notice how adding order by changes the result.




🧠 What’s Happening Here?

PARTITION BY CustomerID creates a group for each customer.

ORDER BY OrderDate arranges rows from earliest to latest.

The function processes rows in that order—one step at a time.




🧪 Practice What You Just Learned

Running Total of Orders

For each order, calculate a running total of totalamount across all orders, ordered by orderdate.


Tables Used
orders
ColumnType
orderidbigint
customeridbigint
orderdatetimestamp without time zone
totalamountdouble precision
statustext
Expected Output
Column
orderid
orderdate
totalamount
running_total
Write Your Query:



➡️ Next Step

Right now, the function processes rows in order—but it still considers all previous rows.

Next, you’ll learn how to control exactly which rows are included in each calculation.




Want to go deeper?