Home >>Python Tutorial >Python MySQL Order By

Python MySQL Order By

To Sort the Result

This is the python sql order by module of our entire Python MySQL tutorial. And if you wish to sort the results in a particular ascending or descending order then you can do that by using the “ORDER BY” statement. This statement will help you in sorting out the results in a rather default mysql order by limit. If you wish to sort out the results in a descending order then it is suggested that you should use the DESC keyword. For example, if you wish to sort out the results alphabetically by name then  
import mysql.connector

mydb = mysql.connector.connect (

  host=“localhost” ,

  user=“yourusername” ,

  passwd=“yourpassword” ,

  database=“mydatabase” ,

)

mycursor = mydb.cursor ( )

sql = “SELECT * FROM customer ORDER BY name ”

mycursor.execute ( sql )

myresult = mycursor.fetchall ( )

for x in myresult :

  print ( x )
  You can also sort the results in a mysql order by desc manner.  

The Order by DESC

As we mentioned above, that the DESC keyword can be used to sort all the result items in a descending mysql order by limit. For example, if you wish to sort all the results in a reverse alphabetically manner or the mysql order by desc then
import mysql.connector

mydb = mysql.connector.connect (

  host=“localhost” ,

  user=“yourusername” ,

  passwd=“yourpassword” ,

  database=“mydatabase” ,

)

mycursor = mydb.cursor ( )

sql = “SELECT * FROM customer ORDER BY name DESC ”

mycursor.execute ( sql )

myresult = mycursor.fetchall ( )

for x in myresult :

  print ( x )
With this, we finish the python sql order by part of our Python MySQL tutorial.

No Sidebar ads