SQL

SQL Order By

SQL Order By

This page covers SQL Order By clause.

As the name suggests ,the “order by” statement can perform sorting operations.

This tutorial encompasses:

  • ascending order
  • descending order
  • multiple order

Let’s use the table “student_info” from the previous tutorials.

idfirstNamelastNameage
1JohnSmith21
2PatrickCasey26
3SamAdams19
4MikeGarciaNULL
5PatrickDumont21

Order By

The “order by” clause sorts the result in either ascending (default) or descending order.

The arrangement follows an alphabetic order (a, b, c, etc.) for strings and numeric for numbers (0, 1, 2, 3, etc.).

The following is an ascending order.

SELECT firstName, age FROM student_info
ORDER BY firstName;
firstNameage
John21
MikeNULL
Patrick21
Patrick26
Sam19

We sort the result by the first name (ascending order).

Descending order

We can also retrieve data and sort it in descending order.

The syntax follows the same logic, with the difference of adding “desc”.

SELECT firstName, age FROM student_info
ORDER BY firstName DESC;
firstNameage
Sam19
Patrick26
Patrick21
MikeNULL
John21

The outcome is the same as the previous example, but in reverse order.

Multiple order

Multiple sorting is allowed in SQL.

To do this, we add and separate by comma all choices. The first column is always the main order.

The second sorts the result in the case where we have the same values in the first column (e.g. two students named Patrick).

SELECT firstName, age FROM student_info
ORDER BY age, firstName;
firstNameage
MikeNULL
Sam19
John21
Patrick21
Patrick26

The above statement first sorts the result by the “age” column. We have two students with the same age, 21 years old.

In this scenario, the student “John” is before “Patrick”, as the letter “J” is first in the alphabet.


Next: SQL Group By