Python MariaDB – Order By Clause using PyMySQL
A MySQL client library is employed when we have to use MySQL with other programming languages. The work of PyMySQL is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server.
OrderBy Clause
The OrderBy is used to arrange the result set in either ascending or descending order. By default, it is always in ascending order unless “DESC” is mentioned, which arranges it in descending order. “ASC” can also be used to explicitly arrange it in ascending order. But, it is generally not done this way since default already does that.
Syntax :
SELECT column_list
FROM table_name
ORDER BY column_name ASC|DESC;
The following programs will help you understand this better.
Table in use :
Example 1: Program to arrange the data in ascending order by PRODUCT_TYPE
Python3
import pymysql
Host = "localhost"
User = "user"
Password = ""
database = "GFG"
conn = pymysql.connect(host = Host, user = User, password = Password, database)
cur = conn.cursor()
query = f "SELECT * FROM PRODUCT ORDER BY PRODUCT_TYPE ASC"
cur.execute(query)
rows = cur.fetchall()
for row in rows :
print (row)
conn.close()
|
Output :
Example 2: Arranging the table in descending order by price
Python3
import pymysql
conn = pymysql.connect( 'localhost' , 'user' ,
'password' , 'database' )
cur = conn.cursor()
query = f "SELECT * FROM PRODUCT ORDER BY price DESC"
cur.execute(query)
for row in rows :
print (row)
conn.close()
|
Output :
Example 3: Arranging the table in ascending order by price
Python3
import pymysql
conn = pymysql.connect( 'localhost' , 'user' ,
'password' , 'database' )
cur = conn.cursor()
query = f"SELECT price,PRODUCT_TYPE FROM PRODUCT\
ORDER BY price ASC"
cur.execute(query)
for row in rows :
print (row)
conn.close()
|
Output :
Last Updated :
14 Oct, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...