🧠 What Are SQL Window Functions? A Beginner’s Guide to OVER()

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.




🚀 Window Functions and OVER()

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:

  • The function looks across multiple rows
  • The result is added to every row

You can think of OVER() as defining the group of rows the function can “see.”




📊 Example: Using SUM() OVER()

🧾 Sample Data

OrderID CustomerID Amount
1A100
2B200
3C300

SELECT OrderID, Amount,
       SUM(Amount) OVER () AS TotalAmount
FROM Orders;

Result:

OrderID Amount TotalAmount
1100600
2200600
3300600

The total (600) is calculated across all rows and shown on every row.




🧠 What’s Happening Here?

SUM(Amount) calculates a total across the dataset, and OVER() tells SQL:

  • Don’t collapse the rows like group by does
  • Attach the result to each row instead

That’s the foundation of all window functions.




🧪 Practice What You Just Learned

Total Revenue Across All Orders

For each order, show the total revenue across all orders using a window function.


Tables Used
orders
Column Type
orderid bigint
customerid bigint
orderdate timestamp without time zone
totalamount double precision
status text
Expected Output
Column
orderid
totalamount
total_revenue
Write Your Query:



➡️ Next Step

Right now, OVER() is looking at all rows.

Next, you’ll learn how to split your data into groups so each calculation resets.




Want to go deeper?