RANK

Rankings per group

SQLite in your browser
Lesson concept What you'll do
1 / 4

Rank books within each genre, or members by loans, ties included.

RANK() gives places; PARTITION BY starts the ranking again for each group.

The database
10 rows
loan_idbook_idmember_idloan_datereturned
1101042026-01-222026-02-07
231012026-02-232026-03-09
391052026-03-112026-03-29
481012026-03-272026-04-20
591052026-04-032026-07-19
641052026-04-062026-04-26
751042026-04-072026-04-14
821032026-04-252026-05-11
991012026-07-192026-08-09
1071032026-10-05NULL
Click a name to type it
Your query
 
Hint: click the green edit button on the board, or type it yourself
Query output Ready to run

Run your query to see the result table.

Press the green Run button or Ctrl+Enter.

Study notes

How RANK, PARTITION BY works

ROW_NUMBER() OVER (PARTITION BY genre ORDER BY year) numbers the rows 1, 2, 3 again inside each genre.

genretitleyearposition
HorrorFrankenstein18181starts again at 1
HorrorDracula18972
HorrorCarrie19743
Science FictionBrave New World19321starts again at 1
Science FictionDune19652
Science FictionThe Hunger Games20083

query

SELECT genre, title, year, 
  ROW_NUMBER() OVER (PARTITION BY genre ORDER BY year) AS position
FROM books;

Every row stays: GROUP BY would squash each genre into one row instead.

Recap: window functions side by side
  • What does RANK do?

    RANK() OVER (ORDER BY pages DESC) gives 1 to the first row, 2 to the next... Rows that tie share a place, and the next place is skipped: 1, 2, 2, 4.

  • RANK, DENSE_RANK or ROW_NUMBER?

    On 3, 2, 2, 1 loans: ROW_NUMBER gives 1, 2, 3, 4 (ties in no fixed order), RANK gives 1, 2, 2, 4, and DENSE_RANK gives 1, 2, 2, 3 (no gaps).

  • What does PARTITION BY do?

    It splits the rows into groups and ranks each group on its own: PARTITION BY genre gives each genre its own number 1. Unlike GROUP BY, every row stays.

  • Can I rank by a total?

    Yes, with GROUP BY in the same query: RANK() OVER (ORDER BY COUNT(*) DESC) ranks the groups by their count.

  • How is this like Excel?

    RANK.EQ gives the same places as RANK: =RANK.EQ(F2, $F$2:$F$12). Ranking within a group needs COUNTIFS in Excel; in SQL it's one PARTITION BY.

Know someone fighting with a spreadsheet? Send them this page.