Saturday, October 25, 2025
HomeLanguagesPython PostgreSQL – Limit Clause

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 before returning the rows then we use the OFFSET clause after the  LIMIT clause.

Syntax without using OFFSET: SELECT select_list FROM table_name LIMIT no_of_rows;

Syntax with using OFFSET: SELECT select_list FROM table_name LIMIT no_of_rows OFFSET rows_to_skip;

Table Used:

Here, we are using the product table for demonstration.

Now let’s use the limit in this table, for we will use will psycopg2 module to connect the PostgreSQL and execute the SQL query in the cursor.execute(query) object.

Syntax: cursor.execute(sql_query);

Example 1: Using a limit clause in Postgre using Python

Python3




# importing psycopg2
import psycopg2
 
conn=psycopg2.connect(
    database="neveropen",
    user="postgre",
    password="root",
    host="localhost",
    port="5432"
)
 
# Creating a cursor object using the cursor() method
cursor = conn.cursor()
 
print("\ndisplaying five rows from top");
sql = '''SELECT * from products LIMIT 5 '''
 
# Executing the query
cursor.execute(sql)
 
# Fetching the data
result = cursor.fetchall();
print(result)
 
# Commit changes in the database
conn.commit()
 
# Closing the connection
conn.close()


Output:

Postgre limit clause

Example 2: Using limit and offset clause in Postgre using Python

Python3




# importing psycopg2
import psycopg2
 
conn=psycopg2.connect(
    database="neveropen",
    user="postgre",
    password="root",
    host="localhost",
    port="5432"
)
 
# Creating a cursor object using the cursor() method
cursor = conn.cursor()
print("displaying four rows after a particular offset");
sql1 = '''SELECT * from products LIMIT 4 OFFSET 5 '''
 
# Executing the query
cursor.execute(sql1)
 
# Fetching the data
result1 = cursor.fetchall();
print(result1)
 
 
# Commit changes in the database
conn.commit()
 
# Closing the connection
conn.close()


Output:

Postgre limit clause with offset

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS