Home

Topic: ORDER BY

Learning objective


What is ORDER BY?


Use the ORDER BY clause to sort the rows of the SQL query output by specified columns based on their values in ascending or descending order.


A simple example

Sort all columns and rows in the titles table by the value in the title column, numerically in ascending order.

SELECT *
FROM titles
ORDER BY emp_no
;



ASC and DESC order

By default, the order sorted is always ascending, for both numeric columns (smallest -> largest) and text columns (A -> Z). NULL values are sorted last.

This SQL query will yield the same result:

SELECT *
FROM titles
ORDER BY emp_no
;

as this:

SELECT *
FROM titles
ORDER BY emp_no ASC
;

Note that the sorting preference is indicated after the column.

To sort by emp_no in descending order:

SELECT *
FROM titles
ORDER BY emp_no DESC
;

Because ASC and DESC are both SQL reserve keywords, they should be styled as capitalized.



ORDER BY with multiple columns

To sort by multiple columns, the columns are separated by commas:

SELECT
    first_name,
    last_name
FROM employees
ORDER BY
    first_name,
    last_name
;    

The columns can be sorted in different orders.

Here, we can sort by first name alphabetically ascending (A -> Z) and then last name alphabetically descending (Z -> A).

SELECT
    first_name,
    last_name
FROM employees
ORDER BY
    first_name ASC,
    last_name DESC
;    

Questions?