By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,665 Members | 1,489 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,665 IT Pros & Developers. It's quick & easy.

Issue with using limit with offset

P: 1
I am using Postgres 9.6.9.

I am facing a strange issue with using limit with offset.

Without any limit and offset conditions, I get 9 records.

If I give conditions like-

OFFSET 1 LIMIT 3

OFFSET 2 LIMIT 3

I get the expected no (3) of records at the desired offset.

However I only get 2 records for the following-

OFFSET 5 LIMIT 3

OFFSET 6 LIMIT 3

I should get 3 , as the total no. of records is 9.

For the following conditions I get 3 records-

OFFSET 5 LIMIT 4

OFFSET 6 LIMIT 4

It seems that under some conditions, the LIMIT is internally being decreased by 1 when used with OFFSET.

This is baffling, thanks in advance for any help.
6 Days Ago #1
Share this Question
Share on Google+
1 Reply


Rabbit
Expert Mod 10K+
P: 12,327
Are you using an order by?

According to the documentation from PostgreSQL:
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 might 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 query plans, 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.
6 Days Ago #2

Post your reply

Sign in to post your reply or Sign up for a free account.