PostgreSQL LIMIT Clause
The LIMIT limit clause in PostgreSQL is used to limit the amount of data queried by a SELECT statement.
Syntax
The basic syntax of a SELECT statement with a LIMIT clause is as follows:
SELECT column1, column2, columnN
FROM table_name
LIMIT [no of rows]
The following is the syntax when the LIMIT clause is used together with the OFFSET clause:
SELECT column1, column2, columnN
FROM table_name
LIMIT [no of rows] OFFSET [row num]
Example
Create the COMPANY table (Download the COMPANY SQL file ), with the following data:
runoobdb# select * from COMPANY;
id | name | age | address | salary
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
The following example will find a limited number of records, that is, read 4 records:
runoobdb=# SELECT * FROM COMPANY LIMIT 4;
The following result is obtained:
id | name | age | address | salary
----+-------+-----+-------------+--------
1 | Paul | 32 | California | 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
(4 rows)
However, in some cases, you may need to start retrieving records from a specific offset.
The following is an example that retrieves 3 records starting from the third position:
runoobdb=# SELECT * FROM COMPANY LIMIT 3 OFFSET 2;
The following result is obtained:
id | name | age | address | salary
----+-------+-----+-----------+--------
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
(3 rows)