beginner
ORDER BY Clause
5 min read
The ORDER BY clause sorts the rows returned by a SQL query in ascending (ASC) or descending (DESC) order based on one or more specified columns.
1. Basic Syntax
sql
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC|DESC;
Note: By default, ORDER BY sorts in ascending (ASC) order if no direction is specified.
2. Multi-Column Sorting
When specifying multiple columns, SQL sorts by the first column first, and then sorts rows with identical values in the first column by the second column:
sql
SELECT first_name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;
Result:
Employees are grouped alphabetically by department, and within each department, sorted from highest salary to lowest.
3. Sorting by Column Position or Alias
You can sort by an aliased column name or by its positional index in the SELECT list:
sql
SELECT first_name, salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;