ORDER BY
In this page:
Sorting Your Results
By default, databases do not guarantee any order for query results unless you explicitly ask for one. We use the ORDER BY clause at the end of our query to sort our rows, which is essential any time the display order actually matters to your users.
Example: Sorting Your Results
SELECT * FROM products ORDER BY price;
Sorting in Descending Order
To sort from highest to lowest, we add the DESC keyword after the column name. This is great for showing the newest items or highest prices first, such as a leaderboard or a 'recently added' product feed.
Example: Sorting in Descending Order
SELECT * FROM products ORDER BY price DESC;
Sorting in Ascending Order
We can use the ASC keyword to sort from lowest to highest. This is the default setting in MySQL, but writing it explicitly can make your query clearer to teammates who might assume the sort direction otherwise.
Example: Sorting in Ascending Order
SELECT * FROM products ORDER BY price ASC;
Sorting by Multiple Fields
You can sort your results by more than one column, such as sorting by department and then by salary within each department. You just separate the columns with a comma. MySQL will sort by the first column first, then use the second column only to break ties.
Example: Sorting by Multiple Fields
SELECT * FROM employees ORDER BY department, salary DESC;
Sorting using Math Expressions
We can also sort using calculations instead of a plain column, like ordering by total_price minus discount. MySQL will run the calculation on each row and sort the rows using the calculated answers rather than any stored value.
Example: Sorting using Math Expressions
SELECT * FROM orders ORDER BY total_price - discount;
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: