Easy Tutorial
❮ Postgresql Privileges Postgresql And Or Clauses ❯

PostgreSQL LIMIT Clause

The LIMIT clause in PostgreSQL is used to restrict the number of rows returned 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 syntax when using the LIMIT clause with an OFFSET clause is:

SELECT column1, column2, columnN 
FROM table_name
LIMIT [no of rows] OFFSET [row num]

Example

Create a COMPANY table (download COMPANY SQL file), with the following data:

tutorialprodb# 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 number of rows, specifically 4 rows:

tutorialprodb=# SELECT * FROM COMPANY LIMIT 4;

This results in:

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.

Here is an example, extracting 3 records starting from the third position:

tutorialprodb=# SELECT * FROM COMPANY LIMIT 3 OFFSET 2;

This results in:

id | name  | age | address   | salary
----+-------+-----+-----------+--------
  3 | Teddy |  23 | Norway    |  20000
  4 | Mark  |  25 | Rich-Mond |  65000
  5 | David |  27 | Texas     |  85000
(3 rows)
❮ Postgresql Privileges Postgresql And Or Clauses ❯