SQL Order By
The ORDER BY clause in SQL is used to sort the result set of a query based on one or more columns. It allows you to specify the order in which the rows should be returned. 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], ...
Here’s an explanation of the different parts:
SELECT column1, column2, ...: Specifies the columns you want to retrieve in the result set.
FROM table_name: Specifies the table from which you want to retrieve data.
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...: Specifies the columns by which you want to sort the result set. You can specify one or more columns separated by commas. Optionally, you can specify the sort order using ASC (ascending, the default) or DESC (descending).
Here are a few examples to illustrate how the ORDER BY clause works:
- Sorting by a single column in ascending order:
SELECT * FROM employees ORDER BY last_name;
- Sorting by a single column in descending order:
SELECT * FROM products ORDER BY price DESC;
- Sorting by multiple columns:
SELECT * FROM orders ORDER BY order_date DESC, customer_name ASC;
In the third example, the result set will be sorted first by the order_date column in descending order, and then by the customer_name column in ascending order.
It’s important to note that the ORDER BY clause is typically the last clause in a SQL query, after the SELECT, FROM, WHERE, GROUP BY, and HAVING clauses (if present).