OVER example
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.
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:
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
The partition divides the window for the calculation; it does not collapse rows. That is exactly one of the differences from GROUP BY.
Add an ORDER BY at the end if the result has to be shown in a guaranteed order.