totn PostgreSQL

PostgreSQL: SELECT LIMIT Statement

This PostgreSQL tutorial explains how to use the PostgreSQL SELECT LIMIT statement with syntax and examples.

Description

The PostgreSQL SELECT statement is used to retrieve records from one or more tables in PostgreSQL and limit the number of records returned based on a limit value.

Syntax

The syntax for the SELECT LIMIT statement in PostgreSQL is:

SELECT expressions
FROM tables
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]]
LIMIT row_count;

Parameters or Arguments

expressions
The columns or calculations that you wish to retrieve.
tables
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
WHERE conditions
Optional. The conditions that must be met for the records to be selected.
ORDER BY expression
Optional. It is used in the SELECT LIMIT statement so that you can order the results and target those records that you wish to return.
LIMIT row_count
Specifies a limited number of rows in the result set to be returned based on row_count. For example, LIMIT 10 would return the first 10 rows matching the SELECT criteria. This is where sort order matters so be sure to use an ORDER BY clause appropriately.

Example - Using LIMIT keyword

Let's look at how to use a SELECT statement with a LIMIT clause in PostgreSQL.

For example:

SELECT order_id, quantity, price
FROM order_details
WHERE website = 'TechOnTheNet.com'
ORDER BY order_id DESC
LIMIT 8;

This PostgreSQL SELECT LIMIT example would select the first 8 records from the order_details table where the website is 'TechOnTheNet.com'. Note that the results are sorted by order_id in descending order so this means that the 8 largest order_id values will be returned by the SELECT LIMIT statement.

If there are other records in the order_details table that have a website value of 'TechOnTheNet.com', they will not be returned by the SELECT LIMIT statement in PostgreSQL.

If we wanted to select the 8 smallest order_id values instead of the largest, we could change the sort order as follows:

SELECT order_id, quantity, price
FROM order_details
WHERE website = 'TechOnTheNet.com'
ORDER BY order_id ASC
LIMIT 8;

Now the results would be sorted by order_id in ascending order, so the first 8 smallest order_id records that have a website of 'TechOnTheNet.com' would be returned by this SELECT LIMIT statement. No other records would be returned by this query.