Lesson 8 +10 XP

ORDER BY

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

Ascending (default)


sql

### SELECT * FROM Customers

### ORDER BY Country;

Sorts alphabetically from A to Z.

Descending


sql

### SELECT * FROM Customers

### ORDER BY Country DESC;

Sorts from Z to A.

Multiple sort keys


sql

### 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:


sql

### 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.