PostgreSQL LIMIT Clause

In PostgreSQLlimitthe clause is used to limit the number of data queried in 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]

Examples

Create the COMPANY table (Download COMPANY SQL file), the data content is as follows:

exampledb# 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 retrieve a limited amount of data, i.e., read 4 records:

exampledb=# 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 extract records starting from a specific offset.

The following is an example that extracts 3 records starting from the third position:

exampledb=# 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)
Other extensions