PostgreSQL – LIMIT Clause
The LIMIT
clause is used in a SELECT
statement to restrict the number of rows returned in the result set. It’s particularly useful when you want to retrieve only a specific number of rows from a query result.
The basic syntax of using the LIMIT
clause is as follows:
SELECT column1, column2, ... FROM table_name WHERE condition LIMIT row_count;
Here’s a breakdown of the different parts of the LIMIT
clause:
column1, column2, ...
: The columns you want to retrieve data from.table_name
: The name of the table from which you want to retrieve data.condition
: The optional condition that specifies filtering criteria for the rows you want to retrieve.row_count
: The maximum number of rows you want to retrieve in the result set.
For example, let’s say you have a table named products
with columns product_id
, product_name
, price
, and category
. You might write a SELECT
statement with a LIMIT
clause to retrieve the top 10 cheapest products:
SELECT product_name, price FROM products ORDER BY price LIMIT 10;
In this query, we’re retrieving the product name and price of the top 10 products ordered by price in ascending order.
The LIMIT
clause is especially useful when combined with ordering and sorting to retrieve a specific range of rows, such as getting the highest-paid employees, retrieving recent posts, or showing paginated results in a web application.