Back
Next
Here SQL Tutorial will guide that we have seen how to get data out of a table using SELECT command. Often, however, we
need to list the output in a particular order. This
could be in ascending order, in descending order, or
could be based on either numerical value or text value.
In such cases, we can use the SQL ORDER BY keyword to achieve our desired output for
the stored data.
The syntax for an SQL ORDER BY statement is as follows:
SQL Order by clause syntax
SELECT "column_name"
FROM "table_name"
[WHERE "condition"]
ORDER BY "column_name" [ASC, DESC]
The [] means that the WHERE statement is optional.
However, if a WHERE clause exists, it comes before the
SQL ORDER BY clause. ASC means that the results will be shown
in ascending order, and DESC means that the results will be
shown in descending order. If neither is specified, the default is order will be ASC
mean ascending.
It is possible to order by more than one column. In this case, the ORDER BY clause above becomes
SQL Order by with Sorting [ASC, DESC]
ORDER BY "column_name1" [ASC, DESC], "column_name2" [ASC, DESC]
Assuming that we choose ascending order for both columns, the output
will be ordered in ascending order according to column 1. If there is
a tie for the value of column 1, we the sort in ascending order by column 2.
For example, we may wish to list the contents of Table Employee
by first names of employees, in descending order:
Table Employees
| FirstName |
LastName |
Email |
DOB |
Phone |
| Austin |
Hennery |
austin.it@gamail.com |
24/11/1978 |
446 102-2222 |
| Creston |
Narvon |
narvon_crest@hotmail.com |
22/04/1976 |
443 325-4545 |
| Kate |
Bladen |
kbladen@usa.net |
01/05/1980 |
326 503-3232 |
| Angela |
Julie |
julieee@yahoo.co.uk |
11/12/1977 |
326 323-8888 |
| Bobbi |
Ferguson |
bobi123@kiwibox.com |
10/02/1970 |
506 252-9875 |
| Cute |
Alfa |
cafa@gmail.com |
19/05/1972 |
506 272-4566 |
we key in,
SQL Order by clause Example with Sorting
SELECT FirstName,LastName,Email,DOB,Phone
FROM Employees
ORDER BY FirstName ASC
Result of above SQL Order by example with ASC sorting.
| FirstName |
LastName |
Email |
DOB |
Phone |
| Angela |
Julie |
julieee@yahoo.co.uk |
11/12/1977 |
326 323-8888 |
| Austin |
Hennery |
austin.it@gamail.com |
24/11/1978 |
446 102-2222 |
| Bobbi |
Ferguson |
bobi123@kiwibox.com |
10/02/1970 |
506 252-9875 |
| Creston |
Narvon |
narvon_crest@hotmail.com |
22/04/1976 |
443 325-4545 |
| Cute |
Alfa |
cafa@gmail.com |
19/05/1972 |
506 272-4566 |
| Kate |
Bladen |
kbladen@usa.net |
01/05/1980 |
326 503-3232 |
In this section of SQL Tutorial we saw that in addition to column name, we may also use column position based on the SQL
query to indicate which column we want to apply the ORDER BY clause. The first
column is 1, second column is 2, and so on. In the above example, we will
achieve the same results by the following command also.
SELECT FirstName,LastName,Email,DOB,Phone
FROM Employees
ORDER BY 1 ASC
Back
Next
|