SQL ORDER BY Keyword
The ORDER BY keyword is
used to sort the result-set.
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 SELECT statement:
Output:
We use the following SELECT statement:
Output:
The ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set by a specified column. The ORDER BY keyword sort the records in ascending order by default. If you want to sort the records in a descending order, you can use the DESC keyword.SQL ORDER BY Syntax
SELECT
column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
|
ORDER BY Example
“Persons” TABLE:
P_Id
|
LastName
|
FirstName
|
Address
|
City
|
1
|
Suhail
|
Osmani
|
Maharaj
Nagar
|
Sitapur
|
2
|
Maxwel
|
Tom
|
Biswan
|
Sitapur
|
3
|
Rahi
|
Ayon
|
Okhla
|
Delhi
|
4
|
Nyla
|
Tom
|
Rohini
|
Delhi
|
We use the following SELECT statement:
SELECT
* FROM Persons ORDER BY LastName
|
P_Id
|
LastName
|
FirstName
|
Address
|
City
|
2
|
Maxwel
|
Tom
|
Biswan
|
Sitapur
|
4
|
Nyla
|
Tom
|
Rohini
|
Delhi
|
3
|
Rahi
|
Ayon
|
Okhla
|
Delhi
|
1
|
Suhail
|
Osmani
|
Maharaj
Nagar
|
Sitapur
|
11.ORDER BY DESC Example
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 SELECT statement:
SELECT
* FROM Persons ORDER BY LastName DESC
|
P_Id
|
LastName
|
FirstName
|
Address
|
City
|
1
|
Suhail
|
Osmani
|
Maharaj
Nagar
|
Sitapur
|
3
|
Rahi
|
Ayon
|
Okhla
|
Delhi
|
4
|
Nyla
|
Tom
|
Rohini
|
Delhi
|
2
|
Maxwel
|
Tom
|
Biswan
|
Sitapur
|
SQL ORDER BY Keyword
Reviewed by Admin
on
04:05:00
Rating:
No comments: