SQL Flow Field Guide

Sort rows with a tie-breaker

Add a unique tie-breaker so equal sort values have a predictable order.

What you are trying to do

A ticket screen sorts by priority and needs tied tickets to appear in a consistent order.

Work through it

  1. Read the primary sort direction for Priority.
  2. Find tickets with the same priority.
  3. Use TicketId to order those ties.

Check your work

Ticket 107 appears first. The priority-1 tickets follow in TicketId order as 101, 102, and 104.

Practice SQL

Open in SQL Flow
SELECT TicketId, Priority
FROM (VALUES (104, 1), (102, 1), (107, 2), (101, 1)) AS Ticket(TicketId, Priority)
ORDER BY Priority DESC, TicketId ASC;

Knowledge check

Commands in this lesson

Next lesson Read one ordered page