How to ORDER BY a MySQL Query in Python

0 min read 171 words

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)
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts