Yogesh Chauhan's Blog

LIMIT and OFFSET in Postgres

in Postgres on July 7, 2020

LIMIT and OFFSET allow you to retrieve just a portion of the rows that are generated by the rest of the query:

Syntax: 


SELECT select_list
    FROM table_expression
    [LIMIT { number | ALL }] [OFFSET number]

If a limit count is given, no more than that many rows will be returned (but possibly less, if the query itself yields less rows).

LIMIT ALL is the same as omitting the LIMIT clause.

OFFSET says to skip that many rows before beginning to return rows.

OFFSET 0 is the same as omitting the OFFSET clause. If both OFFSET and LIMIT appear, then OFFSET rows are skipped before starting to count the LIMIT rows that are returned.

You don’t need to use LIMIT and OFFSET together all the time.

For example, without OFFSET, LIMIT syntax would be like this:


SELECT columns FROM table
LIMIT x;

The query above returns x rows.

If LIMIT is zero, the query returns an empty set. If the LIMIT is NULL, the query returns all rows omitting the LIMIT clause.

If we decide to skip some rows, we can use OFFSET. The syntax of LIMIT query with OFFSET will look like following:


SELECT columns FROM table
LIMIT x OFFSET y;

The query above skips y rows before returning x rows. If y is zero then no rows will be skipped.

When using LIMIT, it is important to use an ORDER BY clause that constrains the result rows into a unique order. Otherwise you will get an unpredictable subset of the query’s rows.

You may be asking for the tenth through twentieth rows, but tenth through twentieth in what ordering? The ordering is unknown, unless you specified ORDER BY.

The query optimizer takes LIMIT into account when generating a query plan, so you are very likely to get different plans (yielding different row orders) depending on what you give for LIMIT and OFFSET. Thus, using different LIMIT/OFFSET values to select different subsets of a query result will give inconsistent results unless you enforce a predictable result ordering with ORDER BY.

This is not a bug; it is an inherent consequence of the fact that SQL does not promise to deliver the results of a query in any particular order unless ORDER BY is used to constrain the order.

The rows skipped by an OFFSET clause still have to be computed inside the server; therefore a large OFFSET can be inefficient.

Examples:

I am using the database available on my Github public repo

Without ORDER BY


SELECT customer_id, contact_name FROM customers LIMIT 3;

//Output
customer_id, contact_name
"ALFKI"	"Maria Anders"
"ANATR"	"Ana Trujillo"
"ANTON"	"Antonio Moreno"

With ORDER BY


SELECT customer_id, contact_name FROM customers ORDER BY customer_id LIMIT 3;

//Output
customer_id, contact_name
"ALFKI"    "Maria Anders"
"ANATR"    "Ana Trujillo"
"ANTON"    "Antonio Moreno"

Same results.

It’s because Postgres is sorting the results in ascending order based on the first row if we don’t include ORDER BY clause.

With OFFSET


SELECT customer_id, contact_name FROM customers ORDER BY customer_id LIMIT 3 OFFSET 1;

//Output
customer_id, contact_name
"ANATR"	"Ana Trujillo"
"ANTON"	"Antonio Moreno"
"AROUT"	"Thomas Hardy"

As we can see, the first row was skipped and the second row became the first row in results and so on.

Source: Postgres Docs


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to Use the EXISTS and NOT EXISTS Operator with a Subquery in SQL and MySQL?SQL/MySQLWhat is Object Mutability in JavaScript?JavaScriptCheck If a String Contains a Specific Word in PHPPHPSolution for Xcode 11 Command PhaseScriptExecution failed with a nonzero exit code errorMiscellaneousWordPress: How to set WP_SITEURL?WordPressHow to control file extensions with an .htaccess file?Miscellaneous