Have a question?
Message sent Close
View Categories

SQL ORDER BY Clause

🗃️
SELECT column1, column2, ...

FROM table_name

ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;

ASC → Ascending order (default)

DESC → Descending order

You can sort by one or many columns

Numeric, text, date, and expression columns can all be sorted

🗃️
-- Example: Sort employees by their first name:

SELECT FirstName, LastName, Salary

FROM Employees

ORDER BY FirstName;

-- Because ascending order is default, the result is A → Z.

-- To reverse the order:

SELECT FirstName, LastName, Salary

FROM Employees

ORDER BY FirstName DESC;

🗃️
-- Example:

SELECT FirstName, LastName, City

FROM Employees

ORDER BY City ASC, LastName ASC;

🗃️
-- Another example (common in banking/salary data):

SELECT Department, Salary, FirstName

FROM Employees

ORDER BY Department ASC, Salary DESC;

🗃️
-- Example: Sort employees by annual salary (calculated on the fly):

SELECT 

    FirstName,

    Salary,

    Salary * 12 AS AnnualSalary

-- FROM Employees

ORDER BY Salary * 12 DESC;

-- Or sort by length of employee names:

SELECT FirstName, LastName

FROM Employees

ORDER BY LENGTH(FirstName);

🗃️
SELECT FirstName, LastName, Salary

FROM Employees

ORDER BY 3 DESC;

🗃️
-- Example:

SELECT FirstName, Bonus

FROM Employees

ORDER BY Bonus ASC;

-- To explicitly control placement:

-- NULLS LAST (PostgreSQL, Oracle):

SELECT FirstName, Bonus

FROM Employees

ORDER BY Bonus ASC NULLS LAST;

-- NULLS FIRST (PostgreSQL, Oracle):

ORDER BY Bonus DESC NULLS FIRST;

🗃️
SELECT

    FirstName,

    LastName,

    Salary * 12 AS AnnualSalary

FROM Employees

ORDER BY AnnualSalary DESC;

🗃️
-- MySQL / PostgreSQL:

SELECT *

FROM Employees

ORDER BY Salary DESC

LIMIT 5;

-- SQL Server:

SELECT TOP 5 *

FROM Employees

ORDER BY Salary DESC;

-- Standard SQL:

SELECT *

FROM Employees

ORDER BY Salary DESC

FETCH FIRST 5 ROWS ONLY;

🗃️
-- Sort by latest transactions:

SELECT TxnID, CustomerID, Amount, TxnDate

FROM Transactions

ORDER BY TxnDate DESC;

-- Sort by amount (biggest first), NULL amounts last:

SELECT TxnID, Amount, TxnDate

FROM Transactions

ORDER BY Amount DESC NULLS LAST;

-- Sort by type and then by date:

SELECT TxnID, Type, Amount, TxnDate

FROM Transactions

ORDER BY Type ASC, TxnDate DESC;