SQL ORDER BY
In SQL, the ORDER BY
keyword is used to sort the result set of a query in ascending or descending order based on one or more columns. It is commonly used with the SELECT
statement but can also be used with other SQL statements that return a result set, such as SELECT
, UPDATE
, and DELETE
.
Here’s the basic syntax for using ORDER BY
:
1 2 3 |
SELECT column1, column2, ... FROM table_name ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...; |
column1
,column2
, etc.: These are the columns you want to select in your query.table_name
: The name of the table from which you want to retrieve data.ORDER BY
: This keyword specifies that you want to sort the result set.column1
,column2
, etc. (again): These are the columns by which you want to order the result set. You can specify one or more columns, and the result set will be sorted in the order you specify.
The optional ASC
(ascending) or DESC
(descending) keywords can be used to control the sorting order. If you omit these keywords, the default sorting order is ascending.
Here are some examples:
Sorting in ascending order by a single column:
1 2 3 |
SELECT first_name, last_name FROM employees ORDER BY last_name; |
Sorting in descending order by a single column:
1 2 3 |
SELECT product_name, price FROM products ORDER BY price DESC; |
Sorting by multiple columns:
1 2 |
SELECT product_name, category, price FROM products ORDER BY category, price DESC; |
In the third example, the result set is first sorted by the category
column in ascending order and then by the price
column in descending order within each category.
Keep in mind that you can use ORDER BY
with various types of data, including numbers, strings, and dates, to customize the sorting of your query results to meet your specific needs.
Sorting by Multiple Columns with Different Orders:
1 2 3 |
SELECT first_name, last_name, hire_date FROM employees ORDER BY hire_date DESC, last_name ASC, first_name ASC; |