bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Python/Databases in Python
Python•Databases in Python

Python MySQL Order By

Sort the Result

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

The ORDER BY keyword sorts the result ascending by default. To sort the result in descending order, use the DESC keyword.

Example

Sort the result alphabetically by name: result:

import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="
yourusername
",
password="
yourpassword
",
database="mydatabase"
)
mycursor =
mydb.cursor()
sql = "SELECT * FROM customers ORDER BY name"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
 print(x)

Order By Desc

Use the DESC keyword to sort the result in a descending order.

Example

Sort the result reverse alphabetically by name:

import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="
yourusername
",
password="
yourpassword
",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers ORDER BY
name DESC"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
 print(x)

Previous

Python MongoDB Query

Next

Python MongoDB Sort

This chapter

Overview
23

Lessons

49m

Read time

1. Python MySQL2. Python MongoDB3. Python MySQL Create Database4. Python MongoDB Create Database5. Python MySQL Create Table6. Python MongoDB Create Collection7. Python MySQL Insert Into Table8. Python MongoDB Insert Document9. Python MySQL Select From10. Python MongoDB Find11. Python MySQL Where12. Python MongoDB Query13. Python MySQL Order By14. Python MongoDB Sort15. Python MySQL Delete From By16. Python MongoDB Delete Document17. Python MySQL Drop Table18. Python MongoDB Drop Collection19. Python MySQL Update Table20. Python MongoDB Update21. Python MySQL Limit22. Python MongoDB Limit23. Python MySQL Join

On this page

Sort the ResultOrder By Desc