Sort the result in python using mysql

Use the ORDER BY statement to sort the result in ascending order.


import mysql.connector as mysql

db = mysql.connect(
    host ="localhost",
    username= "root",
    password = "[email protected]",
    database = "realprogrammers"
)

cursor = db.cursor()

# defining the query

query = "SELECT * FROM user ORDER BY user_name"

cursor.execute(query)

result = cursor.fetchall()

for x in result:
  print(x)

Fetch data only column


import mysql.connector as mysql

db = mysql.connect(
    host ="localhost",
    username= "root",
    password = "[email protected]",
    database = "realprogrammers"
)

cursor = db.cursor()

# defining the query

query = "SELECT * FROM user ORDER BY user_name"

cursor.execute(query)

result = cursor.fetchall()

for x in result:
  print(x[0])
Leave a Comment