SQL ORDER BY Keyword

📘 SQL ORDER BY Keyword

The ORDER BY keyword in SQL is used to sort query results by one or more columns—either in ascending or descending order.

It is typically placed at the end of a SELECT query.


1. Basic Syntax

SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];
  • ASC = ascending (default)

  • DESC = descending


2. Example: Sort by One Column

Sort employees by salary (lowest → highest):

SELECT name, salary
FROM employees
ORDER BY salary ASC;

Sort employees by salary (highest → lowest):

SELECT name, salary
FROM employees
ORDER BY salary DESC;

3. Sorting by Multiple Columns

If the first column has ties, SQL will sort by the next column.

SELECT name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;

Here:

  1. Sort by department alphabetically

  2. Within each department, sort by salary descending


4. ORDER BY with Expressions

You can sort using expressions or functions.

Example:

SELECT name, (salary * 12) AS annual_salary
FROM employees
ORDER BY annual_salary DESC;

5. ORDER BY with Aliases

Aliases defined in SELECT can be used in ORDER BY.

SELECT name, salary AS sal
FROM employees
ORDER BY sal DESC;

6. ORDER BY for Text, Numbers, and Dates

SQL sorts based on column data type:

  • Text → alphabetical

  • Numbers → numeric

  • Dates → chronological

Example:

SELECT name, hire_date
FROM employees
ORDER BY hire_date DESC;

7. ORDER BY with NULL Values

Different databases sort NULLs differently:

DBMS ASC DESC
PostgreSQL NULLs first NULLs last
MySQL NULLs first NULLs last
Oracle NULLs last NULLs first

To control placement:

ORDER BY salary DESC NULLS LAST;

(Works in PostgreSQL, Oracle)


8. ORDER BY with LIMIT (Pagination)

Common in APIs and dashboards:

SELECT *
FROM employees
ORDER BY salary DESC
LIMIT 10;

9. Real-World Example

Return the 5 highest-paid employees in IT:

SELECT name, salary
FROM employees
WHERE department = 'IT'
ORDER BY salary DESC
LIMIT 5;

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *