ADVERTISEMENT

SQL ORDER BY

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

SyntaxMeaning
ORDER BY columnSort by column (ascending by default)
ORDER BY column DESCSort in descending order
ORDER BY col1, col2 DESCSort by multiple columns
ORDER BY alias / expressionSort by calculated or renamed field

ORDER BY helps organize results meaningfully

ADVERTISEMENT