Previous Next JavaScript must be enabled to correctly display this content

## Ordering Results

Use the ORDER BY clause to order the results by a primary key column or a non-primary key column.

To order using the required column, specify the sort column in the ORDER BY clause:

ORDER BY using the primary key column:

    SELECT id, lastname FROM Users ORDER BY id;
     +----+----------+
     | id | lastname |
     +----+----------+
     |  1 | Morrison |
     |  2 | Anderson |
     |  3 | Morgan   |
     |  4 | Smith    |
     |  5 | Scully   |
     +----+----------+

ORDER BY using a non-primary key column:

    SELECT id, lastname FROM Users ORDER BY lastname;
     +----+----------+
     | id | lastname |
     +----+----------+
     |  2 | Anderson |
     |  3 | Morgan   |
     |  1 | Morrison |
     |  5 | Scully   |
     |  4 | Smith    |
     +----+----------+

Using this example data, you can order by more than one column. For example, to order users by age and income:

    SELECT id, lastname, age, income FROM Users ORDER BY age, income;
     +----+----------+-----+--------+
     | id | lastname | age | income |
     +----+----------+-----+--------+
     |  1 | Morrison |  25 | 100000 |
     |  2 | Anderson |  35 | 100000 |
     |  4 | Smith    |  38 |  80000 |
     |  3 | Morgan   |  38 |   NULL |
     |  5 | Scully   |  47 | 400000 |
     +----+----------+-----+--------+

By default, sorting is performed in ascending order. To sort in descending order use the DESC keyword in the ORDER BY clause:

    SELECT id, lastname FROM Users ORDER BY id DESC;
     +----+----------+
     | id | lastname |
     +----+----------+
     |  5 | Scully   |
     |  4 | Smith    |
     |  3 | Morgan   |
     |  2 | Anderson |
     |  1 | Morrison |
     +----+----------+