Menu

SQL Window Functions in 5 Minutes: ROW_NUMBER, RANK, Running Totals, Top N
📰

SQL Window Functions in 5 Minutes: ROW_NUMBER, RANK, Running Totals, Top N

DEV Community: database·Muiduzzaman Lipu·about 3 hours ago
#hRKhULTG
#devtodatabase#devto#dev#salary#enter
Reading 0:00
15s threshold

Running totals, rankings, "top 3 per category": without window functions these need messy self-joins and subqueries. With them, each one is a single line. Here's everything you need, with real results. I ran every query in SQLite and PostgreSQL.

Video version:

The sample data

-- employees -- name dept salary -- Ann Eng 120 -- Bob Eng 100 -- Cara Eng 100 -- Dan Eng 80 -- Eve Sales 90 -- Finn Sales 75 -- Gia Sales 60

Enter fullscreen mode

Exit fullscreen mode

The big idea: GROUP BY collapses rows, OVER keeps them

GROUP BY dept squashes each department into one row.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.