Concept · Advanced SQL

OVER

OVER defines the window of rows a function uses to calculate the value for the current row, without collapsing the result into a single row.

OVER example

SQL
SELECT id,
       customer_id,
       total,
       SUM(total) OVER (PARTITION BY customer_id) AS customer_total
FROM orders
ORDER BY customer_id, id;

The total is calculated per customer, but all four orders remain visible. With GROUP BY customer_id, by contrast, you would get one aggregated row per customer.

How to use OVER

Not all parts are required for all functions. For example, SUM(total) OVER (PARTITION BY customer_id) needs a partition but not an ordering if you just want to repeat each customer's total on all their rows.

What changes from case to case

The ORDER BY in OVER and the final ORDER BY do different jobs

The ORDER BY within OVER controls the logical order used by the window function. The ORDER BY at the end of the SELECT controls how the result rows are presented. They may coincide, but they are not the same mechanism.

ROW_NUMBER
SELECT id,
       customer_id,
       total,
       ROW_NUMBER() OVER (
         PARTITION BY customer_id
         ORDER BY total DESC, id
       ) AS position
FROM orders
ORDER BY customer_id, position;

When the window frame comes in

With aggregates used as windows, a frame lets you calculate running sums or moving windows. One explicit form that is easy to review is:

Running total
SUM(total) OVER (
  PARTITION BY customer_id
  ORDER BY id
  ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)

If the result depends on the frame, write it explicitly rather than relying on a default value that the reader may misinterpret.

Common mix-ups with OVER

!
Thinking that PARTITION BY groups the result

The partition divides the window for the calculation; it does not collapse rows. That is exactly one of the differences from GROUP BY.

!
Assuming that ORDER BY inside OVER sorts the output

Add an ORDER BY at the end if the result has to be shown in a guaranteed order.