CodeBlanks Logo Icon CodeBlanks

ORDER BY

Sort rows by a column with ORDER BY.

ORDER BY

With ORDER BY you sort rows by a column. The default direction is ascending; use DESC for descending.

SELECT name, price
FROM products
ORDER BY price;

This sorts products by price in ascending order.

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

ORDER BY — details

ORDER BY comes after WHERE and before LIMIT. If you give multiple columns it sorts by the first, then by the second for ties.

For example, ORDER BY city, name sorts cities alphabetically and then sorts customers within the same city by name.

Practice ORDER BY

Select name and price from products ordered by price.

Starter code

query.sql
-- add ordering
SELECT name, price
FROM products
ORDER

Sample solution

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

Expected output

name   price
Silgi  2
Kalem  5
Defter 12

Questions and answers

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

1 What is the default ORDER BY direction?

  • Ascending (ASC) Correct answer
  • Descending (DESC)
  • Random
  • Mixed

Explanation: The default direction is ascending (ASC).

2 Sorting

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

Explanation: Sorting uses ORDER BY; leaving out BY is a syntax error.

3 ORDER BY: match the terms

Term Meaning
ORDER BY sort
ASC ascending
DESC descending
LIMIT limit

All lessons in Beginner