The ORDER BY
clause in SQL is used to sort the results of a query in either ascending or descending order based on one or more columns. By default, the ORDER BY
clause sorts the data in ascending order if no specific direction is provided.
Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
- ASC: Sorts in ascending order (smallest to largest). This is the default order.
- DESC: Sorts in descending order (largest to smallest).
Example:
SELECT name, age
FROM employees
ORDER BY age DESC, name ASC;
In this example, employees are sorted by age
in descending order, and if multiple employees have the same age, they are further sorted by name
in ascending order.
The ORDER BY
clause is often used with clauses like LIMIT
to retrieve a specific range of sorted data.