Sắp xếp với ORDER BY
The rows come back in no particular order. Add ORDER BY to sort them by a column:
SELECT name, score FROM student ORDER BY score DESC;
ASCsorts ascending (smallest first) — this is the default.DESCsorts descending (largest first).
Sort text columns alphabetically:
SELECT name FROM student ORDER BY name;
You can sort by several columns: ORDER BY form ASC, score DESC sorts by form first, then by score within each form. ORDER BY always comes last in the query.
Question. List each student's form, name and score, grouped by form (A to Z), with the highest score first inside each form. If two students in a form tie, list them alphabetically.
Answer. Each extra column in ORDER BY only breaks ties left by the ones before it:
SELECT form, name, score FROM student
ORDER BY form, score DESC, name;
form | name | score
11A | Sara | 95
11A | Lin | 88
11A | Mei | 88
11B | Jamal | 72
11B | Tom | 64
Lin and Mei both scored 88, so the third key, name, puts Lin first.
DESCbelongs to one column. InORDER BY form, score DESConlyscoreis descending;formis still ascending.WHEREcomes beforeORDER BY.SELECT name FROM student ORDER BY score WHERE form = '11A'is a syntax error.- Without
ORDER BY, never rely on the order the rows come back in.
ORDER BY sắp xếp các hàng
ORDER BY đặt các hàng kết quả theo thứ tự, giống như một phép sắp xếp.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Hiển thị name và score của mọi học sinh, điểm cao nhất lên đầu. Hai học sinh bị hòa ở 88: liệt kê sự hòa theo thứ tự bảng chữ cái của name (một cột sắp xếp thứ hai).
Nhấn Chạy để xem kết quả ở đây.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Hiển thị name của mọi học sinh, sắp xếp theo bảng chữ cái (A đến Z).
Nhấn Chạy để xem kết quả ở đây.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Hiển thị form, name và score: các lớp theo thứ tự ngược (11B lên đầu), điểm thấp nhất lên đầu bên trong mỗi lớp, và thứ tự bảng chữ cái khi bị hòa.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Hiển thị name và score của các học sinh thuộc lớp 11B duy nhất, điểm cao nhất lên đầu. WHERE đứng trước ORDER BY.
Nhấn Chạy để xem kết quả ở đây.