Use ORDER BY to sort data and display

In the previous article, we discussed how to use the LIKE operator and regular expression functions for fuzzy search of text data. When you run the examples in the previous articles, the results obtained may not be exactly the same as those in the article, mainly because the display order of the data may be different. This is because SQL does not guarantee the order of returned results when querying.

If you want the results of the query to be sorted according to a certain rule, such as sorting according to salary from high to low, you can use the ORDER BY clause in SQL.

Single column sort

Sorting according to the value of a single field or expression is called single-column sorting . The syntax for single-column sorting is as follows:

SELECT col1, col2, ...
  FROM t
 ORDER BY col1 [ASC | DESC];

Among them, ORDER BY is used to specify the sorting field; ASC means ascending sort (Ascending), DESC means descending sort (Descending), and the default value is ascending sort. The following is a schematic diagram of the sorting operation:

avatar

The following example queries the employee information of the R&D department (dept_id = 4), and displays it in order of monthly salary from high to low:

SELECT emp_name, salary, hire_date
  FROM employee
 WHERE dept_id = 4
 ORDER BY salary DESC;

The WHERE filter condition is used in the query, and the ORDER BY clause is after WHERE. The result of this statement is as follows:

Guess you like

Origin blog.csdn.net/horses/article/details/108729113