ORDER BY

Basic SQL
≈ 1 min read

ORDER BY defines result order

Without explicit sorting, SQL does not promise that rows will be returned in a convenient or stable order. ORDER BY makes the required order part of the query itself.

SELECT name, price
FROM products
ORDER BY price ASC;

ASC means ascending order and is usually the default direction. DESC is used for the reverse order.

You can sort by multiple columns

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

Rows are first ordered by category. If several rows have the same category, the second criterion is applied between them — price in descending order.

If order matters, specify it explicitly. If the database happens to return rows in the same order several times without ORDER BY, that does not make the order guaranteed.