SQL ORDER BY
The ORDER BY clause lets you sort the rows returned by a query β either in ascending or descending order. πΉ Basic Usage πΉ Use with Aliases & Expressions π§ Quick Recap Syntax Meaning ORDER BY column Sort by column (ascending by default) ORDER BY column DESC Sort in descending order ORDER BY col1, col2 […]
The ORDER BY clause lets you sort the rows returned by a query β either in ascending or descending order.
πΉ Basic Usage
-- Sort by one column (default is ASC)
SELECT name, salary FROM employees
ORDER BY salary;
-- Sort in descending order
SELECT name, salary FROM employees
ORDER BY salary DESC;
-- Sort by multiple columns
SELECT name, department, salary FROM employees
ORDER BY department ASC, salary DESC;πΉ Use with Aliases & Expressions
-- Use column alias in ORDER BY
SELECT name, salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;
-- Order by column number (not recommended, but valid)
SELECT name, salary FROM employees
ORDER BY 2 DESC; -- refers to 'salary'π§ Quick Recap
| Syntax | Meaning |
|---|---|
ORDER BY column | Sort by column (ascending by default) |
ORDER BY column DESC | Sort in descending order |
ORDER BY col1, col2 DESC | Sort by multiple columns |
ORDER BY alias / expression | Sort by calculated or renamed field |
β
ORDER BY helps organize results meaningfully
Was this helpful?
Thanks for your feedback!