SQLPathLab
Basic Query · Basic

ORDER BY

Sorts query results by one or more columns.

Overview

ORDER BY sorts the final result by one or more expressions. ASC is the default and DESC reverses the direction. Add a unique tie-breaker when sort values can repeat so the order remains deterministic. Without ORDER BY, a database does not guarantee row order.

Basic syntax

SELECT * FROM orders ORDER BY amount DESC, id;

Examples

ORDER BY example

Sort orders by amount descending, use id as a deterministic tie-breaker, and verify that the largest amount appears first.

Sample table

Table:orders
orders
idcustomer_idproduct_idnamedepartmentamountstatuscreated_atdiscount
1 101 201 Alice Sales 1200 paid 2026-01-03 0
2 102 202 Bob IT 900 pending 2026-01-08 50
3 101 201 Cindy Sales 1500 paid 2026-02-02 100
4 104 203 David HR 700 cancelled 2026-02-15 0

Run result

result
idcustomer_idproduct_idnamedepartmentamountstatuscreated_atdiscount
3 101 201 Cindy Sales 1500 paid 2026-02-02 100
1 101 201 Alice Sales 1200 paid 2026-01-03 0
2 102 202 Bob IT 900 pending 2026-01-08 50
4 104 203 David HR 700 cancelled 2026-02-15 0

Common issues

What order is used when ASC or DESC is omitted?

ASC is the default; write DESC explicitly for descending order.

Can ORDER BY sort by multiple columns?

Yes. Later columns break ties left by earlier sort columns.

Why is ORDER BY important with LIMIT?

Without ORDER BY, the selected subset has no stable business meaning.

Tags

CommonFiltering

Was this explanation clear?