Home > Database > Mysql Tutorial > How to use ORDER BY clause in SQL

How to use ORDER BY clause in SQL

PHPz
Release: 2023-05-28 09:52:12
forward
1440 people have browsed it

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
Copy after login

Example 1: Display company names in alphabetical order:

SELECT Company, OrderNumber FROM Orders ORDER BY Company
Copy after login

Result:

Company    OrderNumber
Apple      4698
HuluMiao   2356
IBM        6953
IBM        3532
Copy after login

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
Copy after login

Result:

Company    OrderNumber
Apple      4698
HuluMiao   2356
IBM        3532
IBM        6953
Copy after login

Example 3: Display company names in reverse alphabetical order:

SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC
Copy after login

Result:

Company    OrderNumber
IBM        6953
IBM        3532
HuluMiao   2356
Apple      4698
Copy after login

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
Copy after login

Result:

Company    OrderNumber
IBM        3532
IBM        6953
HuluMiao   2356
Apple      4698
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template