0PricingLogin
SQL Academy · Lesson

Sorting by Multiple Columns

Break ties with secondary sort keys.

The Problem of Ties

When you sort by a single column, rows with the same value have no defined order among themselves. Three products all priced at 20 could come back in any sequence.

To make the order fully predictable, add a second sort key.

-- Ties on price are ordered arbitrarily
SELECT name, price
FROM products
ORDER BY price;

Listing Multiple Sort Keys

ORDER BY accepts a comma-separated list of columns. The database sorts by the first column, then breaks ties with the second, and so on.

Here, products are sorted by price; ties are settled alphabetically by name.

SELECT name, price
FROM products
ORDER BY price, name;

All lessons in this course

  1. Sorting with ORDER BY
  2. Sorting by Multiple Columns
  3. LIMIT and OFFSET
  4. Finding Top-N Records
← Back to SQL Academy