How to Sort Result in Ascending Order in Python MySQL


In this example we will show how to sort the result in ascending order using the ORDER BY 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"

# execute a query
mycursor.execute(sql)

results = mycursor.fetchall()

for row in results:
    print(row)

# close the connection
mydb.close()

Output:

(7, 'Delaware', 'DE', 'Dover', 2489)
(6, 'Connecticut', 'CT', 'Hartford', 5543)
(0, 'Alabama', 'AL', 'Montgomery', 52420)
(3, 'Arkansas', 'AR', 'Little Rock', 53179)
(5, 'Colorado', 'CO', 'Denver', 104094)
(2, 'Arizona', 'AZ', 'Phoenix', 113990)
(4, 'California', 'CA', 'Sacramento', 163695)
(1, 'Alaska', 'AK', 'Juneau', 665384)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments