ORDER BY Clause in SQL

ORDER BY Clause in SQL

The ORDER BY clause in SQL is used to sort the result set of a query in ascending or descending order based on one or more columns. By default, it sorts in ascending order unless specified otherwise.


Key Points

  1. Sorts Query Results:
    The ORDER BY clause organizes the returned rows based on the specified column(s) and order (ascending or descending).

  2. Supports Multiple Columns:
    You can sort by more than one column, with each column having its own sorting order.


Syntax

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

  • DESC: Sorts in descending order.


Example

Sorting in Ascending Order (Default)

SELECT first_name, last_name, salary
FROM employees
ORDER BY salary;
  • Sorts the employees by their salary in ascending order.

Sorting in Descending Order

SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC;
  • Sorts the employees by their salary in descending order.

Sorting by Multiple Columns

SELECT first_name, last_name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;
  • First sorts the employees by department in ascending order, and within each department, it sorts them by salary in descending order.

Sorting by a Non-Displayed Column

SELECT first_name, last_name
FROM employees
ORDER BY hire_date ASC;
  • Sorts the employees by their hire_date in ascending order, even though the hire_date column is not displayed in the result.

When to Use the ORDER BY Clause

  • To organize data for better readability.

  • To rank records based on specific criteria, such as sorting salaries or dates.

  • To ensure consistent ordering for reporting or pagination in applications.

Note: The ORDER BY clause is always applied after other clauses like WHERE and GROUP BY but before LIMIT or OFFSET.