Arman Pouyaei Start a conversation
Lesson 8  ·  Oct 13, 2026
Data Engineering Fundamentals

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;
nameregiontemp_cheat_rank
Houstongulf38.21
Corpus Christigulf35.42
Phoenixdesert41.71
Tucsondesert40.32

Reading it piece by piece:

  1. PARTITION BY region — splits the rows into buckets by region, internally like GROUP BY. The key difference: every row survives. Each bucket is just the "window" the function looks at.
  2. ORDER BY temp_c DESC inside the OVER (...) — sorts rows within each bucket, so RANK() numbers them: hottest station per region gets 1.
  3. OVER is the magic marker. Any function followed by OVER becomes a window function: plain SUM(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;
nametemp_cheat_rank
Phoenix41.71
Tucson40.32
Houston38.23
Corpus Christi35.44

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.

← All posts