SELECT <column> FROM <table> ORDER BY <column>
Select the product names from the Products table and sort them (9)
-- Oracle / MySQL / SQL Server SELECT prod_name FROM Products ORDER BY prod_name;
| prod_name |
| 12 inch teddy bear |
| 18 inch teddy bear |
| 8 inch teddy bear |
| Bird bean bag toy |
| Fish bean bag toy |
| King doll |
| Queen doll |
| Rabbit bean bag toy |
| Raggedy Ann |
SELECT <column1>, <column2>, <column3> FROM <table> ORDER BY <column1>, <column2>;
Select the product ID, price and name from Products, and sort by price and name
-- Oracle / MySQL / SQL Server SELECT prod_id, prod_price, prod_name FROM Products ORDER BY prod_price, prod_name;
| prod_id | prod_price | prod_name |
| BNBG02 | 3.49 | Bird bean bag toy |
| BNBG01 | 3.49 | Fish bean bag toy |
| BNBG03 | 3.49 | Rabbit bean bag toy |
| RGAN01 | 4.99 | Raggedy Ann |
| BR01 | 5.99 | 8 inch teddy bear |
| BR02 | 8.99 | 12 inch teddy bear |
| RYL01 | 9.49 | King doll |
| RYL02 | 9.49 | Queen doll |
| BR03 | 11.99 | 18 inch teddy bear |
The rows are sorted by price first, then by name. If every price is unique, sorting by name has no effect.
SELECT <column1>, <column2>, <column3> FROM <table> ORDER BY 1, 3;
Select the product ID, price and name from Products, and sort by column positions 2 and 3
-- Oracle / MySQL / SQL Server SELECT prod_id, prod_price, prod_name FROM Products ORDER BY 2,3;
| prod_id | prod_price | prod_name |
| BNBG02 | 3.49 | Bird bean bag toy |
| BNBG01 | 3.49 | Fish bean bag toy |
| BNBG03 | 3.49 | Rabbit bean bag toy |
| RGAN01 | 4.99 | Raggedy Ann |
| BR01 | 5.99 | 8 inch teddy bear |
| BR02 | 8.99 | 12 inch teddy bear |
| RYL01 | 9.49 | King doll |
| RYL02 | 9.49 | Queen doll |
| BR03 | 11.99 | 18 inch teddy bear |
Be careful when changing the order of columns in the SELECT statement
SELECT <column1>, <column2>, <column3> FROM <table> ORDER BY <column1> DESC, <column2>;
Select the product ID, price and name from Products, and sort by price and name in descending order
-- Oracle / MySQL / SQL Server SELECT prod_id, prod_price, prod_name FROM Products ORDER BY prod_price DESC, prod_name DESC;
| prod_id | prod_price | prod_name |
| BR03 | 11.99 | 18 inch teddy bear |
| RYL02 | 9.49 | Queen doll |
| RYL01 | 9.49 | King doll |
| BR02 | 8.99 | 12 inch teddy bear |
| BR01 | 5.99 | 8 inch teddy bear |
| RGAN01 | 4.99 | Raggedy Ann |
| BNBG03 | 3.49 | Rabbit bean bag toy |
| BNBG01 | 3.49 | Fish bean bag toy |
| BNBG02 | 3.49 | Bird bean bag toy |
If both price and name should be descending, specify DESC twice
Whether A and a are treated as equal when sorting depends on the database and its DBMS
| Question | SQL |
|---|---|
| 1 - What do I want to see? | SELECT |
| 2 - Where do I get it from? | FROM |
| 3 - What do I want to sort by? | ORDER BY |