00:00

MySQL ORDER BY

Last updated:

Rows in a table have no guaranteed order. ORDER BY sorts the result of a query by one or more columns or expressions, in ascending or descending order. Use it whenever order matters: leaderboards, newest-first lists, alphabetical directories, reports.

1. Syntax

syntax.sql
SELECT ... FROM ... [WHERE ...]
ORDER BY expr1 [ASC | DESC], expr2 [ASC | DESC], ...;
  • ASC (ascending, the default): smallest to largest, A to Z, oldest to newest.
  • DESC: largest to smallest, Z to A, newest first.
  • ORDER BY is processed after SELECT, so it can use column aliases.

2. Ascending and Descending

query.sql
SELECT name, salary FROM staff ORDER BY salary;

Result: 7 rows

namesalary
arun58000
Prem61000
Lokesh67000
Om72000
Nihal84000
Kavya91000
Mira98000
query.sql
SELECT name, salary FROM staff ORDER BY salary DESC;

Result: 7 rows

namesalary
Mira98000
Kavya91000
Nihal84000
Om72000
Lokesh67000
Prem61000
arun58000

3. Sorting by Several Columns

Sorting by two columnsORDER BY dept ASC, salary DESC sorts rows by department first. Within each department, rows are sorted by salary from highest to lowest.ORDER BY dept ASC, salary DESCdeptnamesalaryFinanceKavya91000FinanceLokesh67000ITMira98000ITNihal84000ITOm72000SalesPrem61000← within IT,  highest salary first1st key:dept A→Z
Figure 1: the second sort column only decides the order within equal values of the first.
query.sql
SELECT dept, name, salary FROM staff ORDER BY dept ASC, salary DESC;

Result: 7 rows

deptnamesalary
FinanceKavya91000
FinanceLokesh67000
ITMira98000
ITNihal84000
ITOm72000
SalesPrem61000
Salesarun58000

4. Sorting by Expressions and Aliases

query.sql
SELECT name, salary, ROUND(salary * 0.12) AS monthly_tax
FROM staff
ORDER BY monthly_tax DESC
LIMIT 3;

Result: 3 rows

namesalarymonthly_tax
Mira9800011760
Kavya9100010920
Nihal8400010080
query.sql
SELECT name FROM staff ORDER BY CHAR_LENGTH(name) DESC, name;   -- longest names first

Result: 7 rows

name
Lokesh
Kavya
Nihal
arun
Mira
Prem
Om
You can also sort by column position (ORDER BY 2 DESC), but it is fragile: reordering the SELECT list silently changes the sort. Prefer names or aliases.

5. Where NULLs Go

MySQL treats NULL as smaller than any value: first in ASC order, last in DESC order.

query.sql
SELECT name, joined FROM staff ORDER BY joined;

Result: 7 rows

namejoined
PremNULL
Kavya2019-08-30
Mira2021-04-12
Om2022-11-21
Lokesh2023-01-09
Nihal2024-06-03
arun2025-02-14

MySQL has no NULLS LAST keyword. Sort on IS NULL first to push NULLs to the end:

query.sql
SELECT name, joined FROM staff ORDER BY joined IS NULL, joined;

Result: 7 rows

namejoined
Kavya2019-08-30
Mira2021-04-12
Om2022-11-21
Lokesh2023-01-09
Nihal2024-06-03
arun2025-02-14
PremNULL

6. Custom Sort Orders with FIELD and CASE

Ratings are text, so alphabetical order (high, low, medium) is meaningless. FIELD() returns a value's position in a list:

query.sql
SELECT name, rating FROM staff ORDER BY FIELD(rating, 'high', 'medium', 'low'), name;

Result: 7 rows

namerating
NihalNULL
Kavyahigh
Mirahigh
arunmedium
Lokeshmedium
Ommedium
Premlow

FIELD returns 0 for values not in the list (including NULL), which sorts them first. CASE gives full control:

query.sql
SELECT name, rating
FROM staff
ORDER BY CASE rating WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END, name;

Result: 7 rows

namerating
Kavyahigh
Mirahigh
arunmedium
Lokeshmedium
Ommedium
Premlow
NihalNULL

7. Sorting Text: Case and Collation

With the default case-insensitive collation, arun sorts among the A's, not after all capital letters:

query.sql
SELECT name FROM staff ORDER BY name;

Result: 7 rows

name
arun
Kavya
Lokesh
Mira
Nihal
Om
Prem

A binary collation compares raw character codes, where uppercase letters come before lowercase:

query.sql
SELECT name FROM staff ORDER BY name COLLATE utf8mb4_bin;

Result: 7 rows

name
Kavya
Lokesh
Mira
Nihal
Om
Prem
arun

8. Random Order

query.sql
SELECT name FROM staff ORDER BY RAND() LIMIT 2;   -- different every run

Result: 2 rows

name
Mira
Nihal
ORDER BY RAND() generates a random number for every row and sorts them all, which is slow on big tables. Pick random IDs in the application instead.

9. ORDER BY and Indexes

If an index matches the sort, MySQL reads rows in order and can stop early with LIMIT. Otherwise it must sort them (Using filesort in EXPLAIN):

explain.sql
EXPLAIN SELECT name, salary FROM staff ORDER BY salary DESC LIMIT 3;
CREATE INDEX idx_salary ON staff (salary);
EXPLAIN SELECT name, salary FROM staff FORCE INDEX (idx_salary) ORDER BY salary DESC LIMIT 3;

Without an index: filesort

typekeyExtra
ALLNULLUsing filesort

With an index: read in order

typekeyExtra
indexidx_salaryBackward index scan
On a 7-row table MySQL may still prefer a quick sort; FORCE INDEX just shows the difference. On big tables the optimizer chooses the index on its own.

10. Practice Exercises

Exercise 1: List staff by joining date, newest first, with unknown dates at the end.
solution.sql
SELECT name, joined FROM staff ORDER BY joined IS NULL, joined DESC;

Result: 7 rows

namejoined
arun2025-02-14
Nihal2024-06-03
Lokesh2023-01-09
Om2022-11-21
Mira2021-04-12
Kavya2019-08-30
PremNULL
Exercise 2: Show the highest-paid person in each department first, then the rest of that department by name.
solution.sql
SELECT dept, name, salary,
       salary = (SELECT MAX(salary) FROM staff s2 WHERE s2.dept = s.dept) AS is_top
FROM staff s
ORDER BY dept, is_top DESC, name;

Result: 7 rows

deptnamesalaryis_top
FinanceKavya910001
FinanceLokesh670000
ITMira980001
ITNihal840000
ITOm720000
SalesPrem610001
Salesarun580000

11. Summary

  • ORDER BY col [ASC|DESC] sorts results; ASC is the default.
  • Several columns sort by the first, then break ties with the next.
  • Sort by expressions or aliases; avoid column numbers.
  • NULLs sort first in ASC; use ORDER BY col IS NULL, col to put them last.
  • FIELD() and CASE give custom orders; collations control text order; indexes avoid filesorts.