SQL: Structured Query LanguageSQL FundamentalsRow Limiting and Query Results

How do you return only a limited number of rows?

Question 21 of 30 · Updated

On this page

Use the LIMIT clause to restrict a SELECT query to at most a specified number of rows. In PostgreSQL, MySQL and SQLite, SELECT ... LIMIT 5 returns no more than five rows. If the query has only two matching rows, it returns two, not five. To control which rows are returned, combine LIMIT with ORDER BY. Other SQL dialects use alternatives such as FETCH FIRST or TOP.

1. Basic SQL LIMIT syntax#

SQL
SELECT column_name FROM table_name ORDER BY column_name LIMIT 5;

LIMIT belongs to the result-producing SELECT statement. It is normally written near the end, after ORDER BY when sorting is specified. It changes the maximum size of the returned result, not the number of rows stored in the table. It does not impose an exact minimum size, create a uniqueness rule or delete records.

Without ORDER BY, LIMIT can still return at most the requested number, but SQL does not promise which matching rows will appear. For repeatable application behavior, specify an ordering that identifies the desired subset. If the ordering values are not unique, include an appropriate tie-breaker.

2. Reproducible product dataset#

The following examples use a common table expression (CTE) named products containing six synthetic rows. VALUES lets us demonstrate actual PostgreSQL query behavior without creating or changing a permanent table. Each runnable example includes the complete dataset.

product_idproduct_namepricein_stock
4Lamp800TRUE
1Pen20TRUE
5Desk2500FALSE
3Notebook100TRUE
2Marker100TRUE
6Chair1500TRUE

The product ID is unique in this example. Prices are whole-number illustrative currency amounts; the column is used for ordering rather than financial rounding. The rows are deliberately supplied out of ID order so the example distinguishes the logical order of the result from input order.

3. Return the first three rows in a defined order#

SQL
WITH products(product_id,product_name,price,in_stock) AS ( VALUES (4,'Lamp',800,TRUE), (1,'Pen',20,TRUE), (5,'Desk',2500,FALSE), (3,'Notebook',100,TRUE), (2,'Marker',100,TRUE), (6,'Chair',1500,TRUE) ) SELECT product_id,product_name FROM products ORDER BY product_id LIMIT 3;

Result:

product_idproduct_name
1Pen
2Marker
3Notebook

ORDER BY product_id requests increasing ID order (ASC is the default). LIMIT 3 retains the first three rows in that result. The six-row input relation is unchanged. In an actual catalog table, this is useful for a small preview or debugging query. A low product ID does not necessarily mean earliest creation time; use the column that represents the business meaning of first.

4. Find the top three products by price#

To return the three most expensive products, sort price in descending order before applying the limit.

SQL
WITH products(product_id,product_name,price,in_stock) AS ( VALUES (4,'Lamp',800,TRUE), (1,'Pen',20,TRUE), (5,'Desk',2500,FALSE), (3,'Notebook',100,TRUE), (2,'Marker',100,TRUE), (6,'Chair',1500,TRUE) ) SELECT product_id,product_name,price FROM products ORDER BY price DESC,product_id ASC LIMIT 3;
product_idproduct_nameprice
5Desk2500
6Chair1500
4Lamp800

This query does not return all products costing above a fixed threshold. It returns up to three products ranked by price. Notice that Desk appears even though it is out of stock: the query has no stock filter. The sort direction and WHERE condition should match the business requirement, not be added merely to make a query look more complete.

5. Limit rows after filtering#

Suppose the storefront needs the three cheapest products that are available. Combine WHERE, ORDER BY and LIMIT.

SQL
WITH products(product_id,product_name,price,in_stock) AS ( VALUES (4,'Lamp',800,TRUE), (1,'Pen',20,TRUE), (5,'Desk',2500,FALSE), (3,'Notebook',100,TRUE), (2,'Marker',100,TRUE), (6,'Chair',1500,TRUE) ) SELECT product_id,product_name,price FROM products WHERE in_stock ORDER BY price ASC,product_id ASC LIMIT 3;
product_idproduct_nameprice
1Pen20
2Marker100
3Notebook100
Loading diagram…

The diagram shows the logical result: five available products are eligible, those rows are ordered by price and then ID, and the first three are returned. The engine may implement this more efficiently than materializing and sorting every intermediate row. Do not interpret the diagram as a fixed physical query execution plan.

WHERE and LIMIT answer different questions. WHERE defines eligibility based on values in a row; LIMIT defines how many eligible result rows are returned at most. Using LIMIT 3 without WHERE does not guarantee three available products. Using WHERE without LIMIT returns every matching result row unless another operation restricts it.

6. Handle ties and deterministic selection#

Marker and Notebook both cost 100. If a query orders only by price and limits the result to two rows, Pen will be first, but either Marker or Notebook may occupy the second position. The database does not promise an order between rows that compare equal on every sort key. Add a unique secondary key when an exact-size, repeatable subset matters:

SQL
WITH products(product_id,product_name,price,in_stock) AS ( VALUES (4,'Lamp',800,TRUE), (1,'Pen',20,TRUE), (5,'Desk',2500,FALSE), (3,'Notebook',100,TRUE), (2,'Marker',100,TRUE), (6,'Chair',1500,TRUE) ) SELECT product_id,product_name,price FROM products ORDER BY price ASC,product_id ASC LIMIT 2;
product_idproduct_nameprice
1Pen20
2Marker100

The ID is a tie-breaker, not a second independent sorting operation. First compare price; when prices are equal, compare product ID. Repeated execution against the same visible dataset yields the same ordered subset under these keys. Concurrent changes can still change the visible dataset between queries. A requirement to include every tied record at a boundary is different from a strict maximum of two rows; PostgreSQL also supports FETCH FIRST ... WITH TIES, which can return more than the requested number. That alternative is not needed for this example.

7. FETCH FIRST and SQL dialect differences#

PostgreSQL also supports the standard-style FETCH FIRST syntax. The following tested query returns the same three products as the basic LIMIT example:

SQL
WITH products(product_id,product_name,price,in_stock) AS ( VALUES (4,'Lamp',800,TRUE), (1,'Pen',20,TRUE), (5,'Desk',2500,FALSE), (3,'Notebook',100,TRUE), (2,'Marker',100,TRUE), (6,'Chair',1500,TRUE) ) SELECT product_id,product_name FROM products ORDER BY product_id FETCH FIRST 3 ROWS ONLY;

Result: Pen (ID 1), Marker (ID 2), Notebook (ID 3).

DatabaseCommon row-limiting syntax
PostgreSQLLIMIT 3 or FETCH FIRST 3 ROWS ONLY
MySQLLIMIT 3
SQLiteLIMIT 3
SQL ServerSELECT TOP (3) ...
Oracle 12c and laterFETCH FIRST 3 ROWS ONLY

Illustrative SQL Server syntax:

SQL
SELECT TOP (3) product_id, product_name FROM products ORDER BY product_id;

These dialect examples show the equivalent intention, not a claim that every statement is supported by every product. The SQL Server example and the Oracle/MySQL/SQLite variants were not run on those engines. SQL dialect and standards mastery, including detailed differences among LIMIT, TOP and FETCH, is reserved for a later curriculum question. Verify the syntax for the deployed database version.

8. Edge cases: zero, fewer rows and missing matches#

LIMIT 0 is valid in PostgreSQL and returns no result rows. This is useful for inspecting the expected result columns through a client, but it does not mean the query is immune to parse errors, permissions checks or all execution costs.

SQL
WITH products(product_id,product_name,price,in_stock) AS ( VALUES (4,'Lamp',800,TRUE), (1,'Pen',20,TRUE), (5,'Desk',2500,FALSE), (3,'Notebook',100,TRUE), (2,'Marker',100,TRUE), (6,'Chair',1500,TRUE) ) SELECT product_id FROM products ORDER BY product_id LIMIT 0;

Result: zero rows.

Requesting ten rows does not invent data if only one matches:

SQL
WITH products(product_id,product_name,price,in_stock) AS ( VALUES (4,'Lamp',800,TRUE), (1,'Pen',20,TRUE), (5,'Desk',2500,FALSE), (3,'Notebook',100,TRUE), (2,'Marker',100,TRUE), (6,'Chair',1500,TRUE) ) SELECT product_id FROM products WHERE NOT in_stock ORDER BY product_id LIMIT 10;

Result: one row, product_id 5. If no rows match, an ordinary query returns an empty result. In PostgreSQL a negative LIMIT is invalid; other engines may differ, so do not depend on negative sentinel values. PostgreSQL treats LIMIT ALL and LIMIT NULL as no limit. Applications that accept a page size should validate a positive integer against a maximum and supply it as a bound parameter supported by their driver. Do not let a missing or invalid size unintentionally turn a bounded endpoint into an unbounded query.

9. LIMIT and OFFSET: a brief preview#

LIMIT controls how many rows are returned. OFFSET controls how many rows are skipped before returning them. For example, skip the first two products in ID order, then return at most two more:

SQL
WITH products(product_id,product_name,price,in_stock) AS ( VALUES (4,'Lamp',800,TRUE), (1,'Pen',20,TRUE), (5,'Desk',2500,FALSE), (3,'Notebook',100,TRUE), (2,'Marker',100,TRUE), (6,'Chair',1500,TRUE) ) SELECT product_id,product_name FROM products ORDER BY product_id LIMIT 2 OFFSET 2;
product_idproduct_name
3Notebook
4Lamp

OFFSET 2 skips two rows, not two ID values. This is a simple illustration of retrieving a slice of an ordered result. It does not solve the reliability problems of pagination while data is changing, and large offsets can require extra work. The curriculum covers offset pagination, cursor pagination and composite ordering keys separately.

10. LIMIT applies to the final result, not automatically to source rows#

Consider counting all products and limiting the result to one row:

SQL
WITH products(product_id,product_name,price,in_stock) AS ( VALUES (4,'Lamp',800,TRUE), (1,'Pen',20,TRUE), (5,'Desk',2500,FALSE), (3,'Notebook',100,TRUE), (2,'Marker',100,TRUE), (6,'Chair',1500,TRUE) ) SELECT COUNT(*) AS total FROM products LIMIT 1;

| total | |---:| | 6 |

The count is six, not one. COUNT(*) produces one aggregate result row and LIMIT 1 permits that row to be returned. If you intend to count only a limited ordered subset, explicitly construct that subset in a subquery or CTE before counting it. The same distinction matters for grouping and duplicate elimination: LIMIT restricts the result at its own query level, not every operation performed to generate it.

11. Production API usage#

Supabase's JavaScript query documentation provides a limit(rows) modifier that limits the returned result count. An application using the Supabase client could write the following illustrative query against an actual products table:

JAVASCRIPT
const { data, error } = await supabase .from('products') .select('product_id, product_name, price') .eq('in_stock', true) .order('price', { ascending: true }) .order('product_id', { ascending: true }) .limit(3); if (error) throw error;

This API example assumes a configured client, an accessible products table with these columns and appropriate database policies. It was not executed against a live table. The SQL equivalent was tested using synthetic data. Row-level security and database permissions still apply to the actual API request; restricting the result size is not a replacement for authorization. Supabase's range(from, to) modifier also supports a zero-based inclusive slice and respects query order; it is a separate pagination mechanism.

12. Does LIMIT make a query faster?#

A smaller output can reduce network transfer and client memory. PostgreSQL can sometimes use an ordered index or a bounded sort strategy and avoid processing some rows once enough results are available. However, LIMIT is not a guarantee that the database reads only N rows. A selective filter might require examining many candidates, an aggregate might require all relevant input, and a sort or join might perform substantial work before the first rows can be returned.

Choose indexes according to real filter and sort patterns, inspect execution plans with EXPLAIN, and measure representative workloads. EXPLAIN ANALYZE executes the statement, so use suitable workload safeguards. For this article no performance benchmark or index modification was performed. A small limit is useful for bounding response size but does not by itself bound database CPU time, I/O or memory.

13. Common mistakes and decision guide#

MistakeBetter approach
LIMIT 5 without ORDER BY when the business needs top fiveSpecify the ranking expression and direction
Sorting by a nonunique column aloneAdd a stable unique tie-breaker
Expecting LIMIT 5 to return exactly five rowsHandle fewer matches and empty results
Using LIMIT as a substitute for WHEREFilter eligibility, then restrict the result size
Expecting LIMIT to cap aggregate inputLimit an explicit subquery when that is intended
Assuming all SQL dialects accept LIMITUse the database's supported syntax
Treating a result limit as an access-control mechanismEnforce permissions and row-level authorization

14. Interview-ready answer#

Use SELECT ... FROM table_name ORDER BY column_name LIMIT n in PostgreSQL, MySQL or SQLite to return at most n rows. ORDER BY determines which rows are first, and a unique tie-breaker makes the subset deterministic for an unchanged dataset. WHERE filters the eligible rows before limiting the result. If fewer than n rows qualify, only those rows are returned. LIMIT does not delete data or necessarily limit how much data the database processes. PostgreSQL also supports FETCH FIRST n ROWS ONLY, and SQL Server commonly uses TOP (n).

Quick checks: Can LIMIT return fewer than requested? Yes. Does LIMIT guarantee the top N without ORDER BY? No. Does LIMIT 1 on COUNT(*) count one input row? No; it limits the aggregate result. Is OFFSET needed for the first page? No. Can a tied boundary be unstable? Yes, unless the ordering uniquely identifies the desired rows or the query explicitly includes ties.

15. Validation and authoritative references#

Nine read-only PostgreSQL queries using synthetic VALUES data were executed successfully: basic LIMIT, descending top-three, filtered limit, deterministic tie-breaking, FETCH FIRST, LIMIT 0, fewer qualifying rows, LIMIT with OFFSET, and aggregate output limiting. The displayed results match those executions. No educational DDL, DML or production business-data access was performed. The Mermaid diagram was structurally checked and enclosed in an exact triple-backtick mermaid fence. Full Mermaid parser validation and live page rendering were unavailable. Supabase JavaScript limit and range reference material was consulted through the documentation connector. Other official reference destinations were not independently fetched because live web access was unavailable; the offline research exception was used. The API example and alternative database dialects were not independently executed.

Related questions

Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning