SQL ORDER BY clause

The ORDER BY clause in SQL is used to sort the result set of a query in ascending or descending order. By default, the result set is ordered in ascending order, but you can specify descending order by using the DESC keyword. The ORDER BY clause is typically used in combination with the SELECT statement to retrieve data from a table and sort it based on one or more columns.

Syntax for ORDER BY clause

1SELECT column1, column2, ... 2FROM table_name 3ORDER BY column_name [ASC|DESC];

For example, consider a table named employees with the following columns: id, first_name, last_name, salary. If you want to retrieve all employees and sort the result set by their last name in ascending order, you could use the following query:

1SELECT * 2FROM employees 3ORDER BY last_name;

If you wanted to sort the result set by last name in descending order, you could use the following query:

1SELECT * 2FROM employees 3ORDER BY last_name DESC;

It is also possible to sort the result set based on multiple columns. For example, if you want to sort the result set first by salary in descending order and then by last name in ascending order, you could use the following query:

1SELECT * 2FROM employees 3ORDER BY salary DESC, last_name;