← Back to Chapters

MySQL ORDER BY

? MySQL ORDER BY

? Quick Overview

The ORDER BY clause sorts query results by one or more columns. You can sort ascending (ASC) or descending (DESC), and chain multiple columns to set precedence.

? Key Concepts

  • ORDER BY — defines which column(s) to sort by.
  • ASC — ascending order (default).
  • DESC — descending order.
  • Multiple columns can be specified to form secondary sort keys.
  • Datatype matters: numeric vs text sorting behave differently.

? Syntax / Theory

? View Code Example
// Syntax for ORDER BY: select columns and specify sorting directions
SELECT column1, column2
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];

? Code Example(s)

? View Code Example
// Select all students and order by age in ascending order
SELECT * FROM students
ORDER BY age ASC;
? View Code Example
// Select students and order by department (asc) then age (desc)
SELECT * FROM students
ORDER BY department ASC, age DESC;

? Explanation & Live Output

Explanation

  • ORDER BY: Specifies the column(s) to sort by in the result set.
  • ASC: Sorts ascending (lowest → highest, A → Z).
  • DESC: Sorts descending (highest → lowest, Z → A).
  • When multiple columns are used, sorting follows the column order in the clause (primary, secondary, ...).

Sample result (conceptual)

Imagine a students table — sorting by age ASC will list youngest students first; department ASC, age DESC groups by department, and within each department shows the oldest students first.

✅ Tips & Best Practices

  • Always specify ASC or DESC when you need a particular order; otherwise ASC is default.
  • Be mindful of column datatypes — sorting numbers stored as text can produce unexpected order (e.g., '10' before '2').
  • Combine ORDER BY with LIMIT to get top/bottom results efficiently.
  • For deterministic results, include a unique column (like primary key) as the final sort key when needed.

? Try It Yourself

  • Write a query to select all records from the students table and order by name in descending order.
  • Sort records by multiple columns: e.g., order by department, then age.
  • Test ordering numeric vs text columns to observe differences (convert types if necessary).