"SQL Must Know and Know" (3): Sort and retrieve data

Sort and retrieve data

3.1 Sorting data

Clause (clause): Sql statement consists of clauses, some are required, some are necessary, as said at the beginning, a necessary condition for finding data are: 找什么,在哪找. These are the two necessary clauses. A clause usually consists of a keyword plus the provided data.
To sort the found data, you can use the order by clause.

SELECT * from products
order by vend_id
;

Insert picture description here

3.2 Sort by multiple columns

Why do you want to sort by multiple columns? ? Used when there is duplicate data, such as the student table of a certain class, we need to separate men and women, and the names are sorted by the first letter. We have to sort by gender, so that only men and women can be separated, and we also need to sort by name. In this case, men and women can be sorted by name respectively.

SELECT prod_id,prod_price,prod_name from products
order by prod_price,prod_name
;

Insert picture description here

Sort by column position

The above SQL statement is sorted by column name, and position can also be used instead of column name.

SELECT prod_id,prod_price,prod_nameFROM Products
ORDER BY 23;

The effect is the same.
There are advantages and disadvantages, you can understand at a glance. Disadvantages: It is easy to be confused when the order of listing is not clear.
You can also mix position and column name.

3.4 Specify the sort direction

Whether it is ascending or descending.
Add desc|asc after order by …; descending or ascending order.
The default is ascending.

3.5 Summary

I mainly learned order by xxx desc|asc;. There is also the concept of clauses, and there is order by这个子句必须是select子句的最后一个子句, that is, to be placed last.

Guess you like

Origin blog.csdn.net/qq_43600467/article/details/112973999