Sắp xếp theo ORDER BY trong MySQL

Sắp xếp kết quả

Sử dụng câu lệnh ORDER BY để sắp xếp kết quả theo thứ tự tăng dần hoặc giảm dần.

Từ khóa ORDER BY mặc định sắp xếp kết quả theo thứ tự tăng dần. Để sắp xếp kết quả theo thứ tự giảm dần, hãy sử dụng từ khóa DESC.

Mẫu

Sắp xếp tên theo thứ tự chữ cái, kết quả:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers" ORDER BY name"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
  print(x)

Chạy mẫu

Sắp xếp giảm dần

Sử dụng từ khóa DESC để sắp xếp kết quả theo thứ tự giảm dần.

Mẫu

Sắp xếp kết quả theo thứ tự chữ cái ngược lại của tên:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers ORDER BY name" DESC"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
  print(x)

Chạy mẫu