Member-only story
In SQL, the ORDER BY
clause is used to sort the result set of a query based on one or more columns. It is commonly used with the SELECT
statement, but it can also be used with other SQL statements such as UPDATE
, DELETE
, and MERGE
when ordering is relevant.
The basic syntax of the ORDER BY
clause is as follows:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
column1, column2, ...
: The columns you want to retrieve in the result set.table_name
: The name of the table from which to retrieve data.ORDER BY
: Specifies the sorting order.column1 [ASC|DESC], column2 [ASC|DESC], ...
: The columns by which you want to sort the result set.ASC
stands for ascending order (default), andDESC
stands for descending order.
1. Sorting in Ascending Order:
SELECT first_name, last_name
FROM employees
ORDER BY last_name, first_name;
This query retrieves the first and last names from the employees
table and sorts the result set first by last_name
in ascending order and then by first_name
in ascending order.