ORDER BY
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.
Check yourself
Exercise review
The mentor knows the solution and will help you reach it independently
Sign in to use the Mentor
The Mentor uses the current exercise and your conversation history.
Sign in
Review the key nuances and the answer after making your own attempt.
Sign in to view the solution
The solution and explanation are available after signing in.
Sign in