The ORDER BY clause in SQL sorts the rows in the result set to display the data in a specific order. It sorts one or more columns in ascending or descending order, and supports advanced usage such as multi-column sorting, null value handling, and more.
The role of ORDER BY in SQL
In SQL, the ORDER BY clause is used to compare the results in the result set. Rows are sorted. It allows you to sort your data in ascending or descending order based on one or more columns.
Main functions:
Syntax:
<code>SELECT ... FROM ... WHERE ... ORDER BY column_name1 [ASC | DESC], column_name2 [ASC | DESC], ...;</code>
Example:
Let us consider a table containing people information:
<code>CREATE TABLE persons ( id INT PRIMARY KEY, name VARCHAR(255), age INT );</code>
To sort the people in the table in ascending order by name, We can use the following query:
<code>SELECT * FROM persons ORDER BY name ASC;</code>
This will return rows sorted by name from A to Z.
Advanced usage:
The ORDER BY clause also supports some advanced usage:
By using the ORDER BY clause, you can organize and arrange your data efficiently, simplifying query and report generation.
The above is the detailed content of The role of order by in sql. For more information, please follow other related articles on the PHP Chinese website!