LIMIT / TOP
Restricting Result Size
Learn how to control how many rows your SQL queries return using dialect-specific keywords like LIMIT, TOP, and FETCH FIRST.
What Does Restricting Results Mean?
When you run a SELECT query, the database may return thousands or even millions of rows. Often, you only need a small subset: the first 10 products, the top 5 scorers, or just a quick preview of the data.
Restricting result size means telling the database: "give me only \( n \) rows from the full result set." This is essential for performance, pagination, and readability.
Why Limit Your Results?
The Big Picture: Query Flow
Core Syntax: LIMIT
Used in MySQL, PostgreSQL, SQLite, and MariaDB. The LIMIT clause goes at the very end of your query.
Core Syntax: TOP
Used in Microsoft SQL Server and MS Access. The TOP keyword goes immediately after SELECT, not at the end.
Core Syntax: FETCH FIRST
The ANSI SQL:2008 standard introduced FETCH FIRST. This is used in Oracle 12c+, DB2, and PostgreSQL (which supports both LIMIT and FETCH).
LIMIT vs. TOP vs. FETCH
| Feature | LIMIT | TOP | FETCH FIRST |
|---|---|---|---|
| Databases | MySQL, PostgreSQL, SQLite | SQL Server, MS Access | Oracle 12c+, DB2, PostgreSQL |
| Position | End of query | After SELECT | End of query |
| OFFSET support | LIMIT \(n\) OFFSET \(m\) | No built-in offset | OFFSET \(m\) ROWS |
| ANSI standard | No | No | Yes |
OFFSET: Skipping Rows
OFFSET lets you skip a specified number of rows before returning results. Combined with LIMIT, this enables pagination.
How to Apply LIMIT/TOP
Example 1: Simple LIMIT
Get the 5 most expensive products from a products table.
Example 2: TOP with PERCENT
SQL Server's TOP has a unique feature: you can select a percentage of rows instead of a fixed count.
Example 3: Pagination in Action
Display page 3 of a product listing, with 10 items per page, across three dialects:
ORDER BY id
LIMIT 10 OFFSET 20;
ORDER BY id
OFFSET 20 ROWS
FETCH FIRST 10 ROWS ONLY;
Why ORDER BY Matters
Without ORDER BY, the database returns rows in an arbitrary order. Using LIMIT without ORDER BY means you get random, unpredictable rows that may change between executions.
Common Mistakes
Summary Cheat Sheet
| Goal | MySQL / PostgreSQL | SQL Server | Oracle 12c+ |
|---|---|---|---|
| First 10 rows | LIMIT 10 | SELECT TOP 10 | FETCH FIRST 10 ROWS ONLY |
| Skip 20, take 10 | LIMIT 10 OFFSET 20 | Use OFFSET...FETCH* | OFFSET 20 ROWS FETCH FIRST 10 ROWS ONLY |
| Top 10% | Not supported | SELECT TOP 10 PERCENT | FETCH FIRST 10 PERCENT ROWS ONLY |
Question 1 of 5
In MySQL, which clause correctly returns only the first 15 rows?
Question 2 of 5
Where does the TOP keyword appear in a SQL Server query?
Question 3 of 5
You want page 4 of results with 20 items per page using MySQL. What should the OFFSET value be?
Question 4 of 5
What is the main risk of using LIMIT without an ORDER BY clause?
Question 5 of 5
Which row-limiting syntax follows the ANSI SQL standard and works in Oracle 12c+?