Skip to content
Related Articles

Related Articles

Improve Article

Python MariaDB – Order By Clause using PyMySQL

  • Last Updated : 14 Oct, 2020

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
  
# Create a connection object
# IP address of the MySQL database server
Host = "localhost"  
  
# User name of the database server
User = "user"       
  
# Password for the database user
Password = ""           
  
database = "GFG"
  
conn  = pymysql.connect(host=Host, user=User, password=Password, database)
  
# Create a cursor object
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
  
# Create a connection object
  
conn  = pymysql.connect('localhost', 'user',
                        'password', 'database')
  
# Create a cursor object
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
  
# Create a connection object
conn  = pymysql.connect('localhost', 'user'
                        'password', 'database')
  
# Create a cursor object
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 :

 

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :