Loading...

Python PostgreSQL

Python PostgreSQL Oder By

Sort the Result

Use the ORDER BY statement to sort the result in ascending or descending order.

The ORDER BY keyword sorts the result ascending by default. To sort the result in descending order, use the DESC keyword.

FILE: order_by.py

import psycopg2
conn = psycopg2.connect(database = "kwikl3arn", user = "postgres", password = "post123", host = "localhost", port = "5432")
conn.autocommit = True
print ("Opened database successfully")

cur = conn.cursor()

cur.execute("SELECT * FROM customers order by name ")

rows = cur.fetchall()
for row in rows:
     print(row)

conn.close()

RUN:

C:\Users\Your Name>python order_by.py

Opened database successfully
('Amy', 'apple', 5)
('dilip', 'Highway 21', 2)
('John', 'Highway 21', 1)
('morning star', 'LA', 4)
('naruto', 'japan', 3)

ORDER BY DESC

Use the DESC keyword to sort the result in a descending order.

 

 FILE: order_by_desc.py

import psycopg2
conn = psycopg2.connect(database = "kwikl3arn", user = "postgres", password = "post123", host = "localhost", port = "5432")
conn.autocommit = True
print ("Opened database successfully")

cur = conn.cursor()

cur.execute("SELECT * FROM customers order by name desc ")

rows = cur.fetchall()
for row in rows:
     print(row)

conn.close()

RUN:

C:\Users\Your Name>python order_by_desc.py

Opened database successfully
('naruto', 'japan', 3)
('morning star', 'LA', 4)
('John', 'Highway 21', 1)
('dilip', 'Highway 21', 2)
('Amy', 'apple', 5)