CodeBlanks Logo Icon CodeBlanks

Multi-column ordering

Sort by multiple columns.

Multi-column ordering

To sort by multiple columns you separate them with commas. It sorts by the first, then by the second for ties.

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

It sorts by category ascending, then by price descending within each category.

name, category, price is selected from products. The result is sorted by category, price in descending order.

Multi-column ordering — details

You can give each column its own direction. ORDER BY category ASC, price DESC is valid. A secondary column breaks ties.

For example, to list products in each category starting from the cheapest, you write ORDER BY category, price ASC.

Practice Multi-column ordering

Select name, category and price from products ordered by category then price descending.

Starter code

query.sql
-- sort by two columns
SELECT name, category, price
FROM products
ORDER BY

Sample solution

query.sql
SELECT name, category, price
FROM products
ORDER BY category, price DESC

Expected output

name   category   price
Kalem  kırtasiye 5
Silgi  kırtasiye 2
Çanta  aksesuar   25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Multi-column ordering: match the terms

Term Meaning
comma separate columns
ASC ascending
DESC descending
ORDER BY sort

2 Two-column sort

Question
SELECT name FROM products
ORDER BY category, ____;
Answer
SELECT name FROM products
ORDER BY category, price;

Explanation: ORDER BY category, price sorts by category first, then by price within each category.

3 What does ORDER BY category, price do?

  • Only by category
  • Only by price
  • By category first, then by price Correct answer
  • Random

Explanation: Primary column first, secondary for ties.

All lessons in Beginner