Ordering SQL Results with Two Fields

An ORDER BY list uses its first key first and later keys to resolve ties. Supply a complete rule when consumers need stable order.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace two matching dates
  2. State directions explicitly
  3. Use a tie dataset whose order exposes the second key
  4. Write directions for each key when composing cursors

Trace two matching dates

If documents 8 and 9 share a publication date, selecting ascending ID as a second key places 8 before 9 among them. Key-based sorting uses the same lexicographic ordering idea.

State directions explicitly

Descending date and ascending ID express a particular combination. A page cursor needs those choices to decide what comes next. See cursor boundaries.[1]

Use a tie dataset whose order exposes the second key

A report sorts newer days first and IDs ascending within a day. IDs seven and four share the newer day, so four appears before seven. A row on an older day follows both despite a smaller ID. See key-based sorting.

WITH docs(id, day_number) AS (VALUES (7, 3), (4, 3), (2, 2))
SELECT id FROM docs ORDER BY day_number DESC, id ASC;
-- Expected IDs: 4, 7, 2.

Write directions for each key when composing cursors

Descending day and ascending ID require different comparisons at a continuation boundary. If the second field is unique, it breaks every tie. Test same-day and different-day comparisons.

References

  1. PostgreSQL Global Development Group, Queries ↩