Google News
logo
Python Program to Sort the result of a table alphabetically
To sort the result of a table alphabetically in Python, you can use the `ORDER BY` clause in your SQL query. Here's an example :
Program :
import mysql.connector

# Establish a connection to the database
db = mysql.connector.connect(
    host="localhost",
    user="yourusername",
    password="yourpassword",
    database="yourdatabase"
)

# Create a cursor object to execute queries
cursor = db.cursor()

# Define the SQL query with the ORDER BY clause
query = "SELECT * FROM tablename ORDER BY columnname ASC"

# Execute the query
cursor.execute(query)

# Fetch all rows returned by the query
rows = cursor.fetchall()

# Display the rows
for row in rows:
    print(row)

# Close the database connection
db.close()
In this program, we are using the `ORDER BY` clause with the `ASC` keyword to sort the rows of the table in ascending order based on the values in the `columnname` column. You can also use the `DESC` keyword to sort the rows in descending order.