The SQL ORDER BY clause defines in what order to return a data set retrieved with a SQL SELECT statement.
The SQL ORDER BY clause is used to sort the result-set by a specified column and sort the records in ascending order by default or it can use the ASC keyword. If want to sort the records in a descending order, it can use the DESC keyword. The SQL ORDER BY clause syntax
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
|
P_Id
|
LastName
|
FirstName
|
Address
|
City
|
|---|---|---|---|---|
|
1
|
Hansen | Ola | Timoteivn 10 | Sandnes |
|
2
|
Svendson | Tove | Borgvn 23 | Sandnes |
|
3
|
Pettersen | Kari | Storgt 20 | Stavanger |
|
4
|
Nilsen | Tom | Vingvn 23 | Stavanger |
Now we want to select all the persons from the table above, however, we want to sort the persons by their last name. We use the following SQL SELECT statement:
SELECT * FROM Customers ORDER BY LName
The result-set will look like this:
|
P_Id
|
LastName
|
FirstName
|
Address
|
City
|
|---|---|---|---|---|
|
1
|
Hansen | Ola | Timoteivn 10 | Sandnes |
|
4
|
Nilsen | Tom | Vingvn 23 | Stavanger |
|
3
|
Pettersen | Kari | Storgt 20 | Stavanger |
|
2
|
Svendson | Tove | Borgvn 23 | Sandnes |
Now we want to select all the persons from the table above, however, we want to sort the persons descending by their last name. We use the following SQL SELECT statement:
SELECT * FROM Customers ORDER BY LName DESC
The result-set will look like this:
|
P_Id
|
LastName
|
FirstName
|
Address
|
City
|
|---|---|---|---|---|
|
2
|
Svendson | Tove | Borgvn 23 | Sandnes |
|
3
|
Pettersen | Kari | Storgt 20 | Stavanger |
|
4
|
Nilsen | Tom | Vingvn 23 | Stavanger |
|
1
|
Hansen | Ola | Timoteivn 10 | Sandnes |