Python PostgreSQL - Order By
Last Updated :
23 Sep, 2021
In this article, we will discuss how to use order by clause in PostgreSQL using python.
The Order By clause is used to sort the records of a table returned by the SELECT clause in ascending order by default, yet asc keyword can be used. If we want to sort the records in descending order then we have to write desc word.
Syntax :
SELECT
column1, column2, ....
FROM
table_name
ORDER BY
column1, colum2,.... [ASC | DESC]
Data in use:
To start, first, import all the required libraries into the working space and then establish the connection to the database. Now initialize a cursor and pass the SQL statement to be executed. Print the result set generated and close the connection.
Example 1: Python code to display state name in descending order
Python3
# importing psycopg2 module
import psycopg2
# establishing the connection
conn = psycopg2.connect(
database="postgres",
user='postgres',
password='password',
host='localhost',
port='5432'
)
# creating cursor object
cursor = conn.cursor()
# creating table
sql = '''CREATE TABLE Geeks(
id SERIAL NOT NULL,
name varchar(20) not null,
state varchar(20) not null
)'''
cursor.execute(sql)
# inserting values in the table
cursor.execute('''INSERT INTO Geeks(name , state) VALUES ('Babita','Bihar')''')
cursor.execute(
'''INSERT INTO Geeks(name , state) VALUES ('Anushka','Hyderabad')''')
cursor.execute(
'''INSERT INTO Geeks(name , state) VALUES ('Anamika','Banglore')''')
cursor.execute('''INSERT INTO Geeks(name , state) VALUES ('Sanaya','Pune')''')
cursor.execute(
'''INSERT INTO Geeks(name , state) VALUES ('Radha','Chandigarh')''')
# query to sort table by descending order of state
sql2 = 'select * from Geeks order by state desc;'
# executing query
cursor.execute(sql2)
# fetching records
print(cursor.fetchall())
# Commit your changes in the database
conn.commit()
# Closing the connection
conn.close()
Output:
[(4, 'Sanaya', 'Pune'), (2, 'Anushka', 'Hyderabad'), (5, 'Radha', 'Chandigarh'), (1, 'Babita', 'Bihar'), (3, 'Anamika', 'Banglore')]
Example 2: Python code for displaying records of Geeks in ascending order of name
Python3
# importing psycopg2 module
import psycopg2
# establishing the connection
conn = psycopg2.connect(
database="postgres",
user='postgres',
password='password',
host='localhost',
port='5432'
)
# creating cursor object
cursor = conn.cursor()
# creating table
sql = '''CREATE TABLE Geeks(
id SERIAL NOT NULL,
name varchar(20) not null,
state varchar(20) not null
)'''
cursor.execute(sql)
# inserting values in the table
cursor.execute('''INSERT INTO Geeks(name , state) VALUES ('Babita','Bihar')''')
cursor.execute(
'''INSERT INTO Geeks(name , state) VALUES ('Anushka','Hyderabad')''')
cursor.execute(
'''INSERT INTO Geeks(name , state) VALUES ('Anamika','Banglore')''')
cursor.execute('''INSERT INTO Geeks(name , state) VALUES ('Sanaya','Pune')''')
cursor.execute(
'''INSERT INTO Geeks(name , state) VALUES ('Radha','Chandigarh')''')
# query to sort table by name
sql2 = 'select * from Geeks order by name;'
# executing query
cursor.execute(sql2)
# fetching records
print(cursor.fetchall())
# Commit your changes in the database
conn.commit()
# Closing the connection
conn.close()
Output:
[(3, 'Anamika', 'Banglore'), (2, 'Anushka', 'Hyderabad'), (1, 'Babita', 'Bihar'), (5, 'Radha', 'Chandigarh'), (4, 'Sanaya', 'Pune')]
Similar Reads
PostgreSQL - ORDER BY clause The PostgreSQL ORDER BY clause is used to sort the result query set returned by the SELECT statement. As the query set returned by the SELECT statement has no specific order, one can use the ORDER BY clause in the SELECT statement to sort the results in the desired manner. Syntax: SELECT column_1, c
2 min read
Python PostgreSQL - Select Data In this article, we are going to see how to use select data using Python in PostgreSQL and psycopg2. Installation Open the command prompt and write the command given below. pip install psycopg2 SELECT statement is used to retrieve the required details of an existing table in PostgreSQL. The data tha
3 min read
Python PostgreSQL - Where Clause In this article, we are going to see how to use the Where clause in PostgreSQL using Psycopg2 in Python. Where Clauses help us to easily deal with the databases. As we know we have a huge amount of data stored in our database, so extracting only useful and required information clauses is helpful. Th
2 min read
Python PostgreSQL - Limit Clause In this article, we are going to see how to use the limit clause in PostgreSQL using pyscopg2 module in Python. In PostgreSQL LIMIT constraints the number of rows returned by the query. By default, It is used to display some specific number of rows from the top. If we want to skip a number of rows b
2 min read
PostgreSQL Python - Querying Data Psycopg2 acts as a bridge between Python applications and PostgreSQL databases. Widely employed in diverse Python systems, from web applications to data analysis tools and other software projects, Psycopg2 enables developers to execute queries and manipulate data stored in PostgreSQL databases. In t
5 min read
Python | Database management in PostgreSQL PostgreSQL is an open source object-relational database management system. It is well known for its reliability, robustness, and performance. PostgreSQL has a variety of libraries of API (Application programmable interface) that are available for a variety of popular programming languages such as Py
6 min read
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
2 min read
Python MySQL - Order By Clause A connector is employed when we have to use MySQL with other programming languages. The work of MySQL-connector 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 OrderBy is used to arra
2 min read
Python SQLite - ORDER BY Clause In this article, we will discuss ORDER BY clause in SQLite using Python. The ORDER BY statement is a SQL statement that is used to sort the data in either ascending or descending according to one or more columns. By default, ORDER BY sorts the data in ascending order. DESC is used to sort the data i
3 min read
SQLite ORDER BY Clause SQLite is the most popular database engine which is written in C programming language. It is a serverless, easy-to-use relational database system and it is open source and self-contained. In this article, you will gain knowledge on the SQLite ORDER BY clause. By the end of this article, you will get
8 min read