How to ORDER by a MySQL Query in Python


First, you will need the mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python .

How to Sort the Result of a MySQL Query in Python

import mysql.connector

mydb = mysql.connector.connect(
  host = "localhost",
  user = "username",
  password = "YoUrPaSsWoRd",
  database = "your_database"
)

mycursor = mydb.cursor()
sql = "SELECT * FROM customers ORDER BY name"
mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

How to Change Direction of MySQL Order in Python

You can change the order of the sort by simply setting the order direction.

By default, it is set to ORDER BY <column_name> ASC, which sets the response in ascending order.

If you want to change it, you simply replace the ASC with DESC as follows:

import mysql.connector

mydb = mysql.connector.connect(
  host = "localhost",
  user = "username",
  password = "YoUrPaSsWoRd",
  database = "your_database"
)

mycursor = mydb.cursor()
sql = "SELECT * FROM customers ORDER BY name DESC"
mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)