Categories: python

Order by Clause – MySQL

In MySQL, sorting is primarily accomplished using the ORDER BY clause. That is, one can sort the results in either ascending or descending order using ORDER BY.

If we use the ASC keyword, the ORDER BY statement will sort the results in ascending order in addition to its default behavior.

The DESC keyword will be used to sort the outcome in descending order.

Syntax:

Following is the syntax of the ORDER BY clause in PostgreSQL.

SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

Example: Program to arrange the data in ascending order by name


import mysql.connector

# Connecting to the Database
mydb = mysql.connector.connect(
host ='localhost',
database ='College',
user ='root',
password = 'root'
)

cs = mydb.cursor()

# Order by clause
statement ="SELECT * FROM Student ORDER BY Name"
cs.execute(statement)

result_set = cs.fetchall()

for x in result_set:
 print(x)
 
# Disconnecting from the database
mydb.close()

Example: Python MySQL ORDER BY DESC

To sort the resultset according to the specified column in descending order, use the syntax ORDER BY COLUMN NAME DESC statement.

The following is the syntax for using this statement:

import mysql.connector

# Connecting to the Database
mydb = mysql.connector.connect(
host ='localhost',
database ='College',
user ='root',
password = 'root'
)

cs = mydb.cursor()

# Order by clause
statement ="SELECT * FROM Student ORDER BY Name Desc"
cs.execute(statement)

result_set = cs.fetchall()

for x in result_set:
 print(x)
 
# Disconnecting from the database
mydb.close()

The output of the above code will be in descending order.

Note: also read about WHERE Clause – MySQL

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago