SQL ORDER BY clause
The ORDER BY statement is used to sort the result set based on a specified column.
The ORDER BY statement sorts records in ascending order by default. If you need to sort records in descending order, use the DESC keyword.
"Orders" table:
Company OrderNumber IBM 3532 HuluMiao 2356 Apple 4698 IBM 6953
Example 1: Display company names in alphabetical order:
SELECT Company, OrderNumber FROM Orders ORDER BY Company
Result:
Company OrderNumber Apple 4698 HuluMiao 2356 IBM 6953 IBM 3532
Example 2: Display the company name (Company) in alphabetical order, and display the sequence number (OrderNumber) in numerical order:
SELECT Company, OrderNumber FROM Orders ORDER BY Company, OrderNumber
Result:
Company OrderNumber Apple 4698 HuluMiao 2356 IBM 3532 IBM 6953
Example 3: Display company names in reverse alphabetical order:
SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC
Result:
Company OrderNumber IBM 6953 IBM 3532 HuluMiao 2356 Apple 4698
Example 4: Display the company name in reverse alphabetical order, and display the sequence number in numerical order:
SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC, OrderNumber ASC
Result:
Company OrderNumber IBM 3532 IBM 6953 HuluMiao 2356 Apple 4698
Tips: In this example When there are the same values in the first column (can be nulls), the second column is sorted in ascending order.
The above is the detailed content of How to use ORDER BY clause in SQL. For more information, please follow other related articles on the PHP Chinese website!