Order By
ORDER BY sorts the result set by one or more columns.
The ORDER BY keyword sorts the records in ascending order by default or you can use the ASC keyword.
To sort records in descending order use the DESC keyword.
SQL ORDER BY Syntax:
SELECT
Column1,
Column2,
Column3
FROM Table_Name
ORDER BY Column1, Column2 ASC|DESC
Example:
Lets use the “Products” table to select all of the products and order them by price in descending order.
ProductID | ProductName | Description | Price | SupplierName | SupplierID |
---|---|---|---|---|---|
1 | Super Printer | 9000 series printer | 300 | TechOne | 1 |
2 | Laptop 5 | 4000 Laptop 5th generation | 700 | TechTwo | 2 |
3 | 3D Printer | 3D Print Pro | 900 | TechOne | 1 |
4 | Labtop 7 | 100 Labtop 7 processor | 1200 | TechTwo | 2 |
5 | Camera 400 | Camera Ultra 400 | 400 | TechThree | 3 |
SELECT
ProductID,
ProductName,
Description,
Price,
SupplierName,
SupplierID
FROM Products
ORDER BY Price DESC
Results:
ProductID | ProductName | Description | Price | SupplierName | SupplierID |
---|---|---|---|---|---|
4 | Labtop 7 | 100 Labtop 7 processor | 1200 | TechTwo | 2 |
3 | 3D Printer | 3D Print Pro | 900 | TechOne | 1 |
2 | Laptop 5 | 4000 Laptop 5th generation | 700 | TechTwo | 2 |
5 | Camera 400 | Camera Ultra 400 | 400 | TechThree | 3 |
1 | Super Printer | 9000 series printer | 300 | TechOne | 1 |
SQL Tutorial