How can you sort results in ascending or descending order in SQL?
Posted by LeoRobs
Last Updated: June 12, 2024
In SQL, you can sort the results of a query using the ORDER BY clause. This clause allows you to specify one or more columns by which to sort the results. You can sort in either ascending (default) or descending order.
Syntax for Sorting
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
Parameters:
- column1, column2, ...: The columns by which to sort the results. - ASC: Sorts the results in ascending order (smallest to largest). This is the default behavior, and you can omit the keyword if you want ascending order. - DESC: Sorts the results in descending order (largest to smallest).
Examples
1. Sorting in Ascending Order (Default):
SELECT first_name, last_name
   FROM employees
   ORDER BY last_name;
2. Sorting in Descending Order:
SELECT first_name, last_name
   FROM employees
   ORDER BY last_name DESC;
3. Sorting by Multiple Columns: You can sort by multiple columns. For example, to sort by last_name in ascending order and first_name in descending order:
SELECT first_name, last_name
   FROM employees
   ORDER BY last_name ASC, first_name DESC;
Notes:
- The ORDER BY clause is typically used at the end of a SELECT query. - If you specify multiple columns in the ORDER BY clause, SQL will first sort by the first column, then by the second column within those sorted results, and so on. By using the ORDER BY clause appropriately, you can control the order of the results returned by your SQL queries.