35.6 Order By

By | October 6, 2021

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)

Output:
C:\Users\My Name>python demo_mysql_orderby.py
(3, ‘Amy’, ‘Apple st 652’)
(11, ‘Ben’, ‘Park Lane 38’)
(7, ‘Betty’, ‘Green Grass 1’)
(13, ‘Chuck’, ‘Main Road 989’)
(4, ‘Hannah’, ‘Mountain 21’)
(1, ‘John’, ‘Highway 21’)
(5, ‘Michael’, ‘Valley 345’)
(15, ‘Michelle’, ‘Blue Village’) (2, ‘Peter’, ‘Lowstreet 27’)
(8, ‘Richard’, ‘Sky st 331’)
(6, ‘Sandy’, ‘Ocean blvd 2’)
(9, ‘Susan’, ‘One way 98’)
(10, ‘Vicky’, ‘Yellow Garden 2’)
(14, ‘Viola’, ‘Sideway 1633’)
(12, ‘William’, ‘Central st 954’)

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)

Output:
C:\Users\My Name>python demo_mysql_orderby_desc.py
(12, ‘William’, ‘Central st 954’) (14, ‘Viola’, ‘Sideway 1633’)
(10, ‘Vicky’, ‘Yellow Garden 2’)
(9, ‘Susan’, ‘One way 98’)
(6, ‘Sandy’, ‘Ocean blvd 2’)
(8, ‘Richard’, ‘Sky st 331’)
(2, ‘Peter’, ‘Lowstreet 27’)
(15, ‘Michelle’, ‘Blue Village’) (5, ‘Michael’, ‘Valley 345’)
(1, ‘John’, ‘Highway 21’)
(4, ‘Hannah’, ‘Mountain 21’)
(13, ‘Chuck’, ‘Main Road 989’)
(7, ‘Betty’, ‘Green Grass 1’)
(11, ‘Ben’, ‘Park Lane 38’)
(3, ‘Amy’, ‘Apple st 652’)

Leave a Reply

Your email address will not be published. Required fields are marked *