In this example we will show how to sort the result in descending order using the DESC keyword in Python MySQL.
Source Code
import mysql.connector
# connect to server
mydb = mysql.connector.connect(
host="localhost",
port=3306,
user="yourusername",
password="yourpassword",
db="mydatabase"
)
# get a cursor
mycursor = mydb.cursor()
sql = "SELECT * FROM us_state ORDER BY Total_area DESC"
# execute a query
mycursor.execute(sql)
results = mycursor.fetchall()
for row in results:
print(row)
# close the connection
mydb.close()
Output:
(1, 'Alaska', 'AK', 'Juneau', 665384)
(4, 'California', 'CA', 'Sacramento', 163695)
(2, 'Arizona', 'AZ', 'Phoenix', 113990)
(5, 'Colorado', 'CO', 'Denver', 104094)
(3, 'Arkansas', 'AR', 'Little Rock', 53179)
(0, 'Alabama', 'AL', 'Montgomery', 52420)
(6, 'Connecticut', 'CT', 'Hartford', 5543)
(7, 'Delaware', 'DE', 'Dover', 2489)