This tutorial shows you how to use PostgreSQL LIMIT clause to get a subset of rows generated by a query.
Introduction to PostgreSQL LIMIT clause
PostgreSQL LIMIT is used in the SELECT statement to get a subset of rows returned by the query. The following is the common syntax of the LIMIT clause:
1 2 3 4 5 | SELECT * FROM TABLE LIMIT n; |
PostgreSQL returns n
number of rows generated by the query. If n
is zero or NULL
, it produces the result that is same as omitting the LIMIT
clause.
In case you want to skip a number of rows before returning n
rows, you use OFFSET
clause followed by the LIMIT
clause as follows:
1 2 3 4 5 | SELECT * FROM table LIMIT n OFFSET m; |
PostgreSQL first skips m
rows before returning n rows generated by the query. If m is zero, PostgreSQL will behave like without the OFFSET
clause.
Because the order of the rows in the database table is unknown and unpredictable, when you use the LIMIT
clause, you should always use the ORDER BY
clause to control the order of rows. If you don’t do so, you will get an unpredictable result.
PostgreSQL LIMIT examples
We will give you a few examples of using PostgreSQL LIMIT clause.
To get the first 5 films ordered by film_id, you use the following query:
1 2 3 4 5 6 7 8 9 | SELECT film_id, title, release_year FROM film ORDER BY film_id LIMIT 5; |
To retrieve 4 films starting from the third one ordered by film_id, you use both LIMIT
and OFFSET
clauses as follows:
1 2 3 4 5 6 7 8 9 | SELECT film_id, title, release_year FROM film ORDER BY film_id LIMIT 4 OFFSET 3; |
We often use the LIMIT
clause to get the number of highest or lowest items in a table. For example, to get top 10 most expensive films, we can use the LIMIT
clause to get 10 films order by the rental rate in descending order.
1 2 3 4 5 6 7 8 9 | SELECT film_id, title, rental_rate FROM film ORDER BY rental_rate DESC LIMIT 10; |
The result of the query is as follows:
In this tutorial, we have shown you how to use the PostgreSQL LIMIT
clause to retrieve a subset of rows returned by a query.