Careeroza
ORDER BY
The SQL ORDER BY Keyword
ORDER BY sorts the result set in ascending (ASC, the default) or descending (DESC) order.
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;Note: Without ORDER BY, the order of rows is not guaranteed, even if it looks stable today.
Ascending
Example
Sort products by price, cheapest first:
SELECT ProductName, Price FROM Products
ORDER BY Price;Result: 6 rows
| ProductName | Price |
|---|---|
| Dark Chocolate | 3.49 |
| Green Tea 100 bags | 6.75 |
| Almonds 500g | 8.25 |
| Olive Oil 1L | 9.99 |
| Basmati Rice 5kg | 12.5 |
| Espresso Beans 1kg | 18 |
DESC
Example
Sort products by price, most expensive first:
SELECT ProductName, Price FROM Products
ORDER BY Price DESC;Result: 6 rows
| ProductName | Price |
|---|---|
| Espresso Beans 1kg | 18 |
| Basmati Rice 5kg | 12.5 |
| Olive Oil 1L | 9.99 |
| Almonds 500g | 8.25 |
| Green Tea 100 bags | 6.75 |
| Dark Chocolate | 3.49 |
Order Alphabetically
Example
For text columns, ORDER BY sorts alphabetically:
SELECT CustomerName FROM Customers
ORDER BY CustomerName DESC;Result: 8 rows
| CustomerName |
|---|
| Harbor Lights |
| Golden Spoon |
| Fjord Supplies |
| Evergreen Grocers |
| Delta Mart |
| Cedar & Co |
| Blue Harbor Foods |
| Aarav Traders |
ORDER BY Several Columns
Example
Sort by country, and within each country by customer name:
SELECT Country, CustomerName FROM Customers
ORDER BY Country ASC, CustomerName DESC;Result: 8 rows
| Country | CustomerName |
|---|---|
| Canada | Cedar & Co |
| India | Delta Mart |
| India | Aarav Traders |
| Norway | Fjord Supplies |
| Singapore | Golden Spoon |
| UK | Harbor Lights |
| UK | Blue Harbor Foods |
| USA | Evergreen Grocers |
Sorting and NULL
Databases disagree on where NULL goes: MySQL, SQL Server and SQLite put NULL first in ascending order; PostgreSQL and Oracle put it last. PostgreSQL and Oracle let you choose with NULLS FIRST / NULLS LAST.
Example
Golden Spoon (no city) appears first here:
SELECT CustomerName, City FROM Customers
ORDER BY City;Result: 8 rows
| CustomerName | City |
|---|---|
| Golden Spoon | NULL |
| Delta Mart | Bengaluru |
| Blue Harbor Foods | London |
| Harbor Lights | London |
| Aarav Traders | Mumbai |
| Evergreen Grocers | New York |
| Fjord Supplies | Oslo |
| Cedar & Co | Toronto |