Row_number() in MySQL
Say hello to ROW_NUMBER()
: a SQL superstar that assigns a unique integer (row_num
) to each row in your_table
, sorted by id
. You have the power, just flip id
for the column you want to impose order on.
Emulating ROW_NUMBER() in previous MySQL versions
If you're teamed with a predates-MySQL 8.0 version, don't worry. We can fake ROW_NUMBER()
with user-defined variables. Check this out:
This acts as "ROW_NUMBER's stunt double." We increment a variable for every row, masquerading as ranking.
Partitioning dzata
Sequencing over partitions? You're speaking my language! Reset that awesome variable when a new partition column value pipes up:
Workarounds for older MySQL versions
Before MySQL 8.0, we programmers had to play MacGyver, applying everything from self-joins to variables. Below are some ingenious methods that deserve a hat tip.
Self-Join for maximum impact
Need to high-five the row with the highest value for each group? Self-join to the rescue:
This maneuver relies on the fact that there's no 'superior' row (same group, higher rank).
Groupwise maximum without lifeboats
Groupwise maximum is a proverbial "SQL head-scratcher." Here's how we can crack it without analytic functions:
Pivoting on user-defined variables
For custom rankings schemes, variables are your best friends. Here's a dandy to partition and order rows:
Our variable @rn
resets with each new category (by incrementing or reverting to 1), and @prev
traces the last category.
A word of wisdom and potential trips
- Putting things in order matters. Unordered data can mix up your ranking.
- MySQL variables aren’t known for session safety. Beware of conflicting queries!
- Test, test and re-test. Corner cases like duplicate values, null values, or surprising data types can trip your logic.
Was this article helpful?