Lesson 8 +10 XP

ORDER BY

ORDER BY

The ORDER BY keyword sorts the result, either ascending or descending.

Ascending (default)

SELECT * FROM Customers
ORDER BY Country;

Sorts alphabetically from A to Z.

Descending

SELECT * FROM Customers
ORDER BY Country DESC;

Sorts from Z to A.

Multiple sort keys

SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
  • First sort by Country (A to Z).
  • Within the same country, sort CustomerName from Z to A.

ORDER BY and WHERE together

ORDER BY comes after WHERE:

SELECT CustomerName, Country FROM Customers
WHERE Country = 'Mexico'
ORDER BY CustomerName;

The full SELECT order so far

OrderKeyword
1SELECT
2FROM
3WHERE
4ORDER BY

TL;DR

  • ORDER BY sorts results.
  • ASC is ascending (default); DESC is descending.
  • Multiple keys: list them with commas.
  • ORDER BY always goes after WHERE.