📜  SQL ORDER BY(1)

📅  最后修改于: 2023-12-03 15:35:04.588000             🧑  作者: Mango

SQL ORDER BY

When retrieving data from a table, you may want the results to be sorted in a particular way. To accomplish this, SQL provides the ORDER BY clause.

Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...
  • column1, column2, ... are the columns to be selected from the table.
  • table_name is the name of the table to retrieve data from.
  • ORDER BY clause is used to sort the results in either ascending or descending order.
Examples
Sorting in Ascending Order
SELECT first_name, last_name
FROM employees
ORDER BY last_name ASC;
  • This will return the list of employees' first and last names, sorted alphabetically by last name.
Sorting in Descending Order
SELECT product_name, unit_price
FROM products
ORDER BY unit_price DESC;
  • This will return the list of products' names and prices, sorted in descending order by price.
Sorting Multiple Columns
SELECT first_name, last_name, hire_date
FROM employees
ORDER BY hire_date DESC, last_name ASC;
  • This will return the list of employees' names and hire dates, sorted first by hire date in descending order, and then by last name in ascending order.
Conclusion

The ORDER BY clause is a powerful tool for sorting data in a particular way when retrieving from a table. It allows you to sort by one or more columns, in either ascending or descending order.