← Back to MySQL Course | Chapter 6: Filtering & Sorting | Lesson 7 of 8

ORDER BY

ORDER BY is like lining up the rows by height or name. Without it, the database may give them back in any order it likes.
Syntax
sql
SELECT column1, column2
FROM table_name
ORDER BY column1 [ASC | DESC];

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

sql
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

sql
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

sql
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

sql
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

sql
SELECT * FROM orders ORDER BY total_price - discount;
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting a specific row order without ORDER BY.
  2. Forgetting that ASC is the default, so the highest values appear last, not first.
  3. Putting ORDER BY before WHERE, or sorting by a column that is not in a DISTINCT select.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.