7.6. LIMIT
andOFFSET
#
LIMIT
andOFFSET
allow you to retrieve just a portion of the rows that are generated by the rest of the query:
SELECTselect_list
FROMtable_expression
[ ORDER BY ...] [ LIMIT {count
| ALL }] [ OFFSETstart
]
If a limit count is given, no more than that many rows will be returned (but possibly fewer, if the query itself yields fewer rows).LIMIT ALL
is the same as omitting theLIMIT
clause, as isLIMIT
with a NULL argument.
OFFSET
says to skip that many rows before beginning to return rows.OFFSET 0
is the same as omitting theOFFSET
clause, as isOFFSET
with a NULL argument.
If bothOFFSET
andLIMIT
appear, thenOFFSET
rows are skipped before starting to count theLIMIT
rows that are returned.
When usingLIMIT
, it is important to use anORDER 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 specifiedORDER BY
.
The query optimizer takesLIMIT
into account when generating query plans, so you are very likely to get different plans (yielding different row orders) depending on what you give forLIMIT
andOFFSET
. Thus, using differentLIMIT
/OFFSET
values to select different subsets of a query resultwill give inconsistent results unless you enforce a predictable result ordering withORDER 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 unlessORDER BY
is used to constrain the order.
The rows skipped by anOFFSET
clause still have to be computed inside the server; therefore a largeOFFSET
might be inefficient.