Topics

Order By clause - Python MySQL

Welcome to another tutorial on Python MySQL. Here you will learn about Orderby Clause, and how to sort the result in any order either in ascending or descending order in MySQL.

In MySQL, the ORDERBY is used for sorting purposes. So, by making use of ORDERBY, you can sort results. Below are some features of ORDERBY when using it.

  • The ORDER BY statement by default will sort the result in Ascending order, or the ASC keyword can be used as well.
  • The DESC keyword is used to sort the result in Descending order.

 

Below is the general syntax to sort a certain result in ascending order(i.e. by default):

SELECT column_names FROM table_name ORDER BY column_name

 

Python MySQL ORDER BY Example

Check out the example below, where we will sort the result in ascending order.

import mysql.connector as mysql

db = mysql.connect(
    host = "localhost",
    user = "yourusername",
    passwd = "yourpassword",
    database = "mydatabase1"
)

cursor = db.cursor()
## defining the Query
query = "SELECT * FROM students ORDER BY name"

## getting records from the table
cursor.execute(query)

## fetching all records from the 'cursor' object
records = cursor.fetchall()

## Showing the data
for record in records:
    print(record)

Output:

('Michael', 'Computer Science', 'USA', 3)
('Mike', 'Computer Science', 'London, 1)

 

Python MySQL ORDER BY DESC

In this case, the syntax ORDER BY COLUMN_NAME DESC statement is simply used to sort the result-set based on the specified column in descending order.

Below is the syntax for this statement. 

SELECT column_names FROM table_name ORDER BY column_name DESC 

 

Here, we will be sorting the data in descending order by name column using the DESC keyword with the ORDER BY clause.

import mysql.connector as mysql

db = mysql.connect(
    host = "localhost",
    user = "yourusername",
    passwd = "yourpassword",
    database = "mydatabase1"
)

cursor = db.cursor()
## defining the Query
query = "SELECT * FROM students ORDER BY name Desc"

## getting records from the table
cursor.execute(query)

## fetching all records from the 'cursor' object
records = cursor.fetchall()

## Showing the data
for record in records:
    print(record)

Output:

('Mike', 'Computer Science', 'London, 1)
('Michael', 'Computer Science', 'USA', 3)