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;
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
Syntax with using OFFSET: SELECT select_list FROM table_name LIMIT no_of_rows OFFSET rows_to_skip;
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.
Example 1: Using a limit clause in Postgres using Python
Example 2: Using limit and offset clause in Postgres using Python