In one sentence

PARTITION BY is similar to GROUP BY since it says which column to focus the activity on, except that it doesn’t collapse down the data.

function() OVER (
    PARTITION BY column    -- Like GROUP BY, but doesn't collapse
    ORDER BY column        -- Order within each partition
)

If you know Python

Pandas handles this reasonably well, though you have to bring back all the data unsummarized for it to do it.

df['running_total'] = df.groupby('customer_id')['amount'].cumsum()
df['rank'] = df.groupby('customer_id')['amount'].rank(ascending=False)

Without Pandas, it’s quite tedious to loop and summarize the data. Here is the same thing as a window function:

SELECT *,
       SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running_total,
       RANK() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rank
FROM orders

This returns all orders with the cumulative order amount for each customer, by date no less. It also ranks the amount of each purchase against the customer’s other purchases.

The usual mistake

Window functions seem to do aggregation-type activities, so can’t GROUP BY do this? The short answer is, not very well.

SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id

That gives one row per customer. But what if you want:

  • Each order row, plus the customer’s running total at that point?
  • Each order row, plus how it compares to the average?
  • Each order row, plus its rank within that customer’s orders?

GROUP BY can’t do this, but window functions can. The ORDER BY inside OVER is the order of the data in the partition. Very important for ranks, and running totals.

Example

Top 3 orders per customer, combining a CTE with a window function:

WITH ranked AS (
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn
    FROM orders
)
SELECT * FROM ranked WHERE rn <= 3

LAG() and LEAD() let you reference data from the previous or next row, for example the change since a customer’s previous order:

SELECT customer_id, order_date, amount,
       amount - LAG(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS change
FROM orders

Go deeper

Window Functions: The Feature Python Developers Miss Most, post 16 of SQL for Python Developers: ROW_NUMBER, RANK versus DENSE_RANK, aggregate functions over a partition, and more examples.