pbPassingBI
/
Window functions intermediate 6 min

Introduction to window functions

OVER() versus GROUP BY, and keeping detail while aggregating.

What you'll be able to do
  • Explain what a window function does
  • Write a basic OVER clause
  • Know why windows cannot go in WHERE

The difference from GROUP BY

4 input rows row 1row 2row 3row 4 GROUP BY 1 row OVER() row 1 + totalrow 2 + totalrow 3 + totalrow 4 + total
GROUP BY collapses the rows. A window function computes across them and keeps every row.

Percent of total

SELECT order_id, region, total,
       ROUND(100.0 * total / SUM(total) OVER (PARTITION BY region), 1) AS pct_of_region
FROM orders;

One query gives the detail and its share of the group.

The empty OVER

SUM(total) OVER ()    -- grand total on every row

With no PARTITION BY, the window is the entire result set.

Windows cannot go in WHERE

Window functions are evaluated with SELECT, after WHERE. So this fails:

-- invalid
WHERE ROW_NUMBER() OVER (ORDER BY total DESC) <= 3

Wrap it and filter one level up:

SELECT * FROM (
  SELECT *, ROW_NUMBER() OVER (ORDER BY total DESC) AS rn
  FROM orders
) t WHERE rn <= 3;
Key points
  • Window functions keep every row; GROUP BY collapses them
  • PARTITION BY defines the group the window is computed over
  • Windows are evaluated after WHERE, so filtering needs a wrapper
Check yourself