LIMIT keyword
Specify the number and position of records returned by a SELECT statement.
Other implementations of SQL sometimes use clauses such as OFFSET or ROWNUM.
Our implementation uses LIMIT for both the offset from start and limit.
Syntax
SELECT ... LIMIT { numberOfRecords | lowerBound, upperBound };
numberOfRecordsis the number of records to return.upperBoundandlowerBoundis the range of records to return.
Here's the exhaustive list of supported combinations of arguments. m and n
are positive numbers, and negative numbers are explicitly labeled -m and -n.
LIMIT n: take the firstnrecordsLIMIT -n: take the lastnrecordsLIMIT m, n: skip the firstmrecords, then take up to record numbern(inclusive)- result is the range of records
(m, n]number 1 denoting the first record - if
m > n, implicitly swap the arguments - PostgreSQL equivalent:
OFFSET m LIMIT (n-m)
- result is the range of records
LIMIT -m, -n: take the lastmrecords, then drop the lastnrecords from that- result is the range of records
[-m, -n), number -1 denoting the last record - if
m < n, implicitly swap them
- result is the range of records
LIMIT m, -n: drop the firstmand the lastnrecords. This gives you the range(m, -n). These arguments will not be swapped.
These are additional edge-case variants:
LIMIT n, 0=LIMIT 0, n=LIMIT n,=LIMIT , n=LIMIT nLIMIT -n, 0=LIMIT -n,=LIMIT -n
Null bounds
A LIMIT bound can be null. Null bounds come from parameterized queries: a
bind variable used as a bound (LIMIT $1, LIMIT $1, $2, or LIMIT :lo, :hi)
that is bound to null or left unbound. A literal null written in the query
text is rejected with invalid type: NULL.
In an ORDER BY ... LIMIT query:
LIMIT null: return all records (same as omittingLIMIT)LIMIT null, n: take the firstnrecordsLIMIT n, null: return no records (empty result)
Without ORDER BY, a null lower bound combined with a positive upper bound
(LIMIT null, n) is rejected with LIMIT <negative>, <positive> is not allowed. LIMIT null and LIMIT n, null behave the same with or without
ORDER BY.
Examples
Examples use this schema and dataset:
CREATE TABLE orders (id LONG);
INSERT INTO orders VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10);
SELECT * FROM orders LIMIT 5;
id
----
1
2
3
4
5
SELECT * FROM orders LIMIT -5;
id
----
6
7
8
9
10
SELECT * FROM orders LIMIT 2, 5;
id
----
3
4
5
SELECT * FROM orders LIMIT -5, -3;
id
----
6
7
SELECT * FROM orders LIMIT 2, -1;
id
----
3
4
5
6
7
8
9
SELECT * FROM orders LIMIT 5, 2;
id
----
3
4
5
SELECT * FROM orders LIMIT -3, -5;
id
----
6
7