Python MySQL Order By
- Previous Page MySQL Where
- Next Page MySQL Delete
Result sorting
Please use the ORDER BY statement to sort the results in ascending or descending order.
The ORDER BY keyword sorts the results in ascending order by default. To sort the results in descending order, use the DESC keyword.
Example
Sort names in alphabetical order, results:
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)
Sort in descending order
Please use the DESC keyword to sort the results in descending order.
Example
Sort the results of names in reverse alphabetical order:
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)
- Previous Page MySQL Where
- Next Page MySQL Delete