Rank, compare and running-total rows without collapsing them — then structure long queries with CTEs and subqueries.
GROUP BY answers "how much per customer" but collapses each customer to one row. Often you want both: every order and its customer's total, its rank, or the previous order's date. That's a window function — an aggregate or ranking computed over a set of related rows (the window) and attached to each row.
The shape is function(...) OVER (PARTITION BY … ORDER BY … frame). PARTITION BY says which rows belong together, ORDER BY sorts them inside the window, and the optional frame says which of those rows the function uses.
SELECT order_id, customer_id, amount,
sum(amount) OVER (PARTITION BY customer_id) AS customer_total,
count(*) OVER (PARTITION BY customer_id) AS customer_orders
FROM orders;Reach the last step for the run summary: the key takeaways from this lesson.