The SQL ORDER BY clause is used to sort the results of a SELECT, UPDATE, or DELETE statement in ascending or descending order based on one or more columns. The basic syntax for the ORDER BY clause is as follows:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
By default, the ORDER BY clause sorts the results in ascending order. If you want to sort the results in descending order, you can use the DESC keyword after the column name.
For example, the following SQL query selects all employees from the employees table and sorts the results by last name in ascending order:
SELECT first_name, last_name, salary
FROM employees
ORDER BY last_name;
And the following query sorts the results by salary in descending order:
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC;
You can also sort the results based on multiple columns by specifying multiple column names in the ORDER BY clause, separated by commas. For example, the following query sorts the results first by department_id in ascending order, and then by salary in descending order:
SELECT first_name, last_name, department_id, salary
FROM employees
ORDER BY department_id, salary DESC;
It’s important to note that the ORDER BY clause should be the last clause in a SELECT statement, after all other clauses such as WHERE, JOIN, and GROUP BY.