4

Sort by a column

  • The data filtered by SELECT will be displayed directly in the order in which it appears in the underlying table (the order in which the data is received, the order in which data is added, deleted, and updated, etc.)
  • SQL is made up of clauses, some clauses are required and some things are optional.
  • Data retrieved by SELECT can be sorted using the ORDER BY clause, which takes one or more column names and sorts the output accordingly.

for example:

 SELECT p_name FROM products ORDER BY p_name;

In this way, MySQL will sort the data according to the alphabetical order of p_name and output

Sort by multiple columns

When you need to sort by more than one field (such as sorting by price first, sorting by sales when the price is the same, etc.), you only need to separate the specified column names with commas in order after ORDER BY.
for example:

 SELECT p_name FROM products ORDER BY p_name, p_price;

Specify ascending or descending order

ORDER BY defaults to ascending order, or you can use the DESC keyword for descending order

 SELECT p_name FROM products ORDER BY p_name DREC;

Reference: Forta B. MySQL crash course[M]. Pearson Education India, 2006.

LiberHome
409 声望1.1k 粉丝

有问题 欢迎发邮件 📩 liberhome@163.com