MySQL
MySQL

ORDER BY

ORDER BY sorts a query's results by one or more columns. Without it, MySQL doesn't guarantee any particular row order. SELECT * FROM students ORDER BY age; sorts rows from smallest age to largest ascending order, which is the default. SELECT * FROM students ORDER BY age DESC; sorts from largest to smallest descending order. You can sort by more than one column: ORDER BY age, name sorts primarily by age, and for any rows that tie on age, sorts those by name next. Each column in the list can have its own direction: ORDER BY age DESC, name ASC. ORDER BY is usually the last major clause in a query (after WHERE), and it doesn't change what data exists only the order it's presented in.

Why this matters

  • ·ORDER BY makes results predictable and easy to read, instead of arriving in arbitrary order.
  • ·Sorting by multiple columns lets you break ties meaningfully (like sorting by age, then name).
  • ·DESC is useful for common patterns like 'newest first' or 'highest score first.'

Common mistakes

  • ·Assuming rows come back in a meaningful order without ORDER BY is unreliable MySQL makes no such guarantee.
  • ·Sorting a very large table on a column with no index (covered later) can be slow.
  • ·Forgetting DESC when you meant 'largest first' silently returns results in the opposite order.
Your codePHP
Expected output
+----+------+-----+
| id | name | age |
+----+------+-----+
| 2  | Sara | 17  |
| 1  | Ali  | 16  |
+----+------+-----+
2 rows in set

PHP runs on a server, not in the browser this shows the expected output instead of a live one.

Frequently asked questions

Ascending (ASC) smallest to largest, or A to Z for text unless you specify DESC.

Practice questions

Question 1

Write a query that returns students sorted by age, youngest first.

Your codePHP
Expected output

PHP runs on a server, not in the browser this shows the expected output instead of a live one.

Question 2

Write a query that returns students sorted by name in descending (Z to A) order.

Your codePHP
Expected output

PHP runs on a server, not in the browser this shows the expected output instead of a live one.

Quick check

Just for this topic answer honestly, then check yourself.

1 / 3

What is MySQL's default row order without ORDER BY?