Skip to content

SQL ORDER BY Clause

Syntax

The ORDER BY clause in SQL is used to sort the result set by one or more columns in ascending (ASC) or descending (DESC) order. By default, sorting is in ascending order.

-- Sort by one column in ascending order
SELECT column1, column2
FROM table_name
ORDER BY column1;
-- Sort by one column in descending order
SELECT column1, column2
FROM table_name
ORDER BY column1 DESC;
-- Sort by multiple columns
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC, column2 DESC;

Example

-- Sort by one column in ascending order
SELECT name, age
FROM employees
ORDER BY age;
/* Output:
| name | age |
|-------------|-----|
| Jane Smith | 25 |
| John Doe | 30 |
| Alice Brown | 40 |
*/
-- Sort by one column in descending order
SELECT name, age
FROM employees
ORDER BY age DESC;
/* Output:
| name | age |
|-------------|-----|
| Alice Brown | 40 |
| John Doe | 30 |
| Jane Smith | 25 |
*/
-- Sort by multiple columns
SELECT name, age, department
FROM employees
ORDER BY department ASC, age DESC;
/* Output:
| name | age | department |
|-------------|-----|------------|
| Alice Brown | 40 | HR |
| Jane Smith | 25 | Marketing |
| John Doe | 30 | Sales |
*/