Loading...

Python PostgreSQL

Python PostgreSQL Limit

Limit the Result

You can limit the number of records returned from the query, by using the "LIMIT" statement:

FILE: limit.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 limit 5")
rows = cur.fetchall()
for row in rows:
     print(row)

conn.close()

RUN:

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

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

Start From Another Position

If you want to return five records, starting from the third record, you can use the "OFFSET" keyword:

 FILE: offset.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 limit 5 offset 2")
rows = cur.fetchall()
for row in rows:
     print(row)

conn.close()

RUN:

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

Opened database successfully
('naruto', 'japan', 3)
('morning star', 'LA', 4)
('Amy', 'apple', 5)
('Betty', 'Green Grass 1', 6)
('Richard', 'Sky st 331', 7)