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.
id | firstName | lastName | age |
---|---|---|---|
1 | John | Smith | 21 |
2 | Patrick | Casey | 26 |
3 | Sam | Adams | 19 |
4 | Mike | Garcia | NULL |
5 | Patrick | Dumont | 21 |
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;
firstName | age |
---|---|
John | 21 |
Mike | NULL |
Patrick | 21 |
Patrick | 26 |
Sam | 19 |
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;
firstName | age |
---|---|
Sam | 19 |
Patrick | 26 |
Patrick | 21 |
Mike | NULL |
John | 21 |
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;
firstName | age |
---|---|
Mike | NULL |
Sam | 19 |
John | 21 |
Patrick | 21 |
Patrick | 26 |
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