Ranking rows without collapsing them: window functions
GROUP BY answers "how much per group?" by collapsing rows: one row in, one summary row out. But sometimes you want the rank and the rows: which station is the hottest in each region — while still seeing every station? A window function computes a value for each row by looking at a "window" of related rows. Nothing collapses; you just get a new column.
The code
SELECT
name,
region,
temp_c,
RANK() OVER (PARTITION BY region ORDER BY temp_c DESC) AS heat_rank
FROM weather_stations;
| name | region | temp_c | heat_rank |
|---|---|---|---|
| Houston | gulf | 38.2 | 1 |
| Corpus Christi | gulf | 35.4 | 2 |
| Phoenix | desert | 41.7 | 1 |
| Tucson | desert | 40.3 | 2 |
Reading it piece by piece:
PARTITION BY region— splits the rows into buckets by region, internally likeGROUP BY. The key difference: every row survives. Each bucket is just the "window" the function looks at.ORDER BY temp_c DESCinside theOVER (...)— sorts rows within each bucket, soRANK()numbers them: hottest station per region gets 1.OVERis the magic marker. Any function followed byOVERbecomes a window function: plainSUM(amount)collapses rows;SUM(amount) OVER (ORDER BY day)keeps every row and gives you a running total instead.
In practice
A data engineer reaches for window functions whenever the question is "which rows, ranked, inside each group": top-3 sensors per county, latest reading per station, deduplicating by keeping only row #1 per key. ROW_NUMBER() gives unique numbers (ties get arbitrary order); RANK() gives ties the same number and skips the next; DENSE_RANK() gives ties the same number without skipping. GROUP BY tells you how much per group — window functions tell you which rows matter inside each group.
Python bridge: the same idea in one pandas line, which ranks temp_c within each region and keeps every row:
df["heat_rank"] = df.groupby("region")["temp_c"].rank(method="min", ascending=False)
Pandas' groupby is the PARTITION BY, and .rank() is the RANK() OVER — SQL just runs it inside the warehouse instead of in your notebook.
Further reading
SQL Window Functions Explained: Stop Collapsing Your Data with GROUP BY — dev.to
Try it
Practice question: using the same weather_stations table above (columns: name, region, temp_c), write a query that ranks stations by temperature descending across the whole table — no partitions — so the hottest station in the world gets rank 1. Show name, temp_c, and the rank.
Show answer
SELECT
name,
temp_c,
RANK() OVER (ORDER BY temp_c DESC) AS heat_rank
FROM weather_stations;
| name | temp_c | heat_rank |
|---|---|---|
| Phoenix | 41.7 | 1 |
| Tucson | 40.3 | 2 |
| Houston | 38.2 | 3 |
| Corpus Christi | 35.4 | 4 |
Leaving PARTITION BY out of the OVER (...) makes the window the entire table, so the ranking runs globally. Add a PARTITION BY and the same query would restart the rank at 1 inside each region — the lesson-8 example above.