Handling Ties in Window Functions
It's **Day 73**, and we're talking about **Determinism**.
The Mystery of the Changing Rank
Have you ever run a query twice and seen the ranks change?
This happens because your `ORDER BY` is not unique. If numbers are tied, the database chooses an order randomly based on which row it found first on the physical disk.
The Professional Solution: The Tie-Breaker
Always include a unique column (like ID) as your second sort condition.
-- Dangerous (Inconsistent)
RANK() OVER(ORDER BY score DESC)
-- Professional (Consistent)
RANK() OVER(ORDER BY score DESC, user_id ASC)
Why this matters for APIs
If your mobile app shows a leaderboard, users will be very upset if their position jumps around every time they refresh the screen!
Your Task for Today
Add a secondary `ORDER BY` column to one of your window functions to ensure the results are 100% consistent every time.
*Day 74: Window Functions vs Subqueries—A Face Off.*