PostgreSQL

Limit, Offset, Fetch

Limit

The LIMIT clause limits the amount of retrieved rows based on the specified limit.

Syntax

SELECT <columns> FROM <table-name> LIMIT <limit>; 

Example

SELECT * FROM Companies LIMIT 3; 
First 3 rows of the Companies
Name Type Founded HQ
Walmart Retail 1962 United States
Disney Entertainment 1923 United States
PayPal Finance 1998 United States

Offset

The OFFSET clause offsets the first set of rows given by an ORDER BY clause.

Syntax

SELECT <columns> FROM <table-name>
ORDER BY <attribute-name>
OFFSET <offset>; 

Example

SELECT * FROM Companies
ORDER BY name
OFFSET 2
LIMIT 1; 
1 row from Companies ordered by name offset by 2
Name Type Founded HQ
PayPal Finance 1998 United States

Fetch

The FETCH clause is used with ORDER BY and OFFSET to retrieve rows.

Syntax

SELECT <columns> FROM <table-name>
ORDER BY <attribute-name>
OFFSET <offset>
FETCH <fetch-details>; 

Example

SELECT * FROM Companies
ORDER BY name
OFFSET 2
FETCH FIRST 2 ROW ONLY; 
2 rows fetched from Companies, ordered by name, offset by 2
Name Type Founded HQ
PayPal Finance 1998 United States
Walmart Retail 1962 United States