Expert

Handling Ties in Window Functions

SQL Mastery Team
April 4, 2026
5 min read

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?

  • User A is #1.
  • You run it again.
  • User B (who has the same score) is #1.
  • 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.*

    Ready to put your knowledge into practice?

    Join SQL Mastery and learn through interactive exercises.