New Tutorials:   KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL  
See the Tutorial List

Python MySQL - Orderby Clause

In this tutorial, we will learn how to sort the result in any order(ascending or descending) in MySQL.

The ORDER BY in MySQL is mainly used for the sorting purpose. That is with the help of ORDER BY one can sort the result either in Ascending or Descending Order.

  • By default ORDER BY statement will sort the result in the Ascending order, or we can also use the ASC keyword.

  • In order to sort the result in the Descending order, the DESC keyword will be used.

Below we have a basic syntax to sort the result in ascending order which is the default:

SELECT column_names FROM table_name ORDER BY column_name

Python MySQL ORDER BY Example

Below we have an example in which we will sort the result in ascending order. Let us see the code snippet given below:

import mysql.connector as mysql

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

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)

The above code will sort the names in ascending order and the output will be as follows:

('Amy', 'CE', 'New Delhi', 3) ('Michael', 'CSE', 'London', 4) ('Peter', 'ME', 'Noida', 2) ('Ramesh', 'CSE', '149 Indirapuram', 1)

Here is the snapshot of the actual output:

Python mysql order by example

Python MySQL ORDER BY DESC

The syntax ORDER BY COLUMN_NAME DESC statement is used to sort the resultset based on the specified column in descending order.

The syntax to use this statement is given below:

SELECT column_names FROM table_name ORDER BY column_name DESC 

Now Let us sort the data in descending order by name column using the DESC keyword with the ORDER BY clause. Let's see the code which is given below:

import mysql.connector as mysql

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

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)

The output of the above code will be:

('Ramesh', 'CSE', '149 Indirapuram', 1) ('Peter', 'ME', 'Noida', 2) ('Michael', 'CSE', 'London', 4) ('Amy', 'CE', 'New Delhi', 3)

Here is the snapshot of the actual output:

python mysql order by clause in query