Python Mysql Order BY

The ORDER BY clause is used to order the result, mainly order is used for sort the results either by ascending or descending order.

Mysql Ascending Order

Order the result based on the employee name

Consider the following example.

CopiedCopy Code

import mysql.connector  
myconn = mysql.connector.connect(host = "localhost", user = "root",password = "naveen",database = "PythonDB")  
cur = myconn.cursor()  
try:  
    cur.execute("select name, id, salary from Employee order by name")  
    result = cur.fetchall()   
    print("Name    id    Salary");  
    for row in result:  
        print("--s\t--d\t--d"--(row[0],row[1],row[2]))  
except:  
    myconn.rollback()  
myconn.close()

Mysql descending Order

This orders the result in the decreasing order of a particular column.

CopiedCopy Code

import mysql.connector  
myconn = mysql.connector.connect(host = "localhost", user = "root",password = "naveen",database = "PythonDB")  
cur = myconn.cursor()  
try:  
    cur.execute("select name, id, salary from Employee order by name desc")  
    result = cur.fetchall()  
    print("Name    id    Salary");  
    for row in result:  
        print("--s\t--d\t--d"--(row[0],row[1],row[2]))  
except:  
    myconn.rollback()  
myconn.close()