What does ORDER BY do?
ORDER BY is an operator that sorts a query's results in SQL.
It determines the order rows are returned in after the selection.
Syntax
sql
SELECT *
FROM employees
ORDER BY salary;Sorts rows ascending (ASC is used by default).
Sort variants
- Ascending (ASC), from smaller to larger:
sql
ORDER BY age ASC- Descending (DESC), from larger to smaller:
sql
ORDER BY age DESCExample 1: sorting by a number
sql
SELECT name, salary
FROM employees
ORDER BY salary DESC;Returns employees with the highest salary first.
Example 2: sorting by text
sql
SELECT name, city
FROM employees
ORDER BY city ASC;Sorts alphabetically, from A to Z.
Example 3: sorting by several fields
sql
SELECT name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;Sorts by department first, then within each department, by salary (largest to smallest).
Example 4: sorting by a computed value
sql
SELECT name, (salary * 0.9) AS net_salary
FROM employees
ORDER BY net_salary;You can even sort by the result of an expression.
Summary:
ORDER BY controls the order of rows in the results.
- By default: ascending (
ASC). - For reverse order:
DESC. - You can sort by one or several columns, including computed values.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.