Sorting using ORDER BY

  • ASC(ascent), ascending order; DESC(descent), descending order. If no sort order is ORDER BYexplicitly , the default is ascending sort , equivalent to ORDER BY xxx ASC.
  • ORDER BYColumn aliases can be used , and column aliases can be used for sorting.
  • SELECT ... FROM ... WHERE ... ORDER BY.... ORDER BYin WHEREthe back . ORDER BYColumn aliases can be used, and WHEREcolumn aliases cannot be used .
  • Multiple columns are sorted , separated by commas . For example, ORDER BY xxx DESC,yyy ASC.

DESC descending, ASC ascending

  1. Sort by salary from high to low.
# 按照salary从高到低排序
SELECT last_name,salary
FROM employees
ORDER BY salary DESC;
  1. Sort by salary from low to high.
# 按照salary从低到高排序
SELECT last_name,salary
FROM employees
ORDER BY salary ASC;

SELECT last_name,salary
FROM employees
ORDER BY salary;

ORDER BY sorts using column aliases

# 按照年薪从高到低进行排序
SELECT last_name,salary,12*salary*(1+IFNULL(commission_pct,0)) annual_salary
FROM employees
ORDER BY annual_salary DESC; 

ORDER BY follows WHERE

# department_id为10或20或30的员工的年收入从高到底排序
SELECT department_id,last_name,salary,12*salary*(1+IFNULL(commission_pct,0)) annual_salary
FROM employees
WHERE department_id IN (10,20,30)
ORDER BY annual_salary DESC;

The execution sequence of the above MySQL statement is,
step 1: FROM.
Step 2: WHERE.
Step 3: SELECT.
Step 4: ORDER BY.

ORDER BY multi-column sorting, separated by commas

  1. Sort in descending order by department_id
# 显示员工信息,按照department_id降序排列
SELECT department_id,last_name,salary
FROM employees
ORDER BY department_id DESC;
  1. Sort in descending order by department_id, and then sort in ascending order by salary (when the department_id is the same, sort in ascending order by salary)
SELECT department_id,last_name,salary
FROM employees
ORDER BY department_id DESC,salary ASC;

Guess you like

Origin blog.csdn.net/qzw752890913/article/details/126037140