Chapter 9: Limiting Results with LIMIT/TOP
Imagine a website showing search results or a list of blog posts. You wouldn’t want to load thousands of items on a single page! Not only would it be overwhelming for the user, but it would also be incredibly slow to load. This is where the ability to limit the number of rows returned by your query becomes essential.
The LIMIT
clause (or TOP
for some SQL dialects) allows you to restrict the number of rows returned by a SELECT
statement. This chapter will teach you how to retrieve a specific number of records, and how to implement pagination, a core feature of most dynamic web applications.
The Purpose of LIMIT
/ TOP
LIMIT
: Used primarily in MySQL, PostgreSQL, SQLite, and MariaDB. It allows you to specify a maximum number of rows to return, and optionally, an offset (how many rows to skip from the beginning).TOP
: Used in SQL Server and MS Access. It allows you to specify the number or percentage of rows to return from the top of the result set.
Since this tutorial focuses on MySQL/MariaDB, we will primarily use the LIMIT
clause. However, a brief note on TOP
will be included for awareness.
When to Use LIMIT
- Pagination: Displaying a fixed number of results per page (e.g., “10 posts per page”).
- “Show More” Functionality: Loading additional data as a user scrolls or clicks a button.
- Top N Results: Finding the top 5 most expensive products, or the 3 most recent users.
- Performance Optimization: Preventing large result sets from being retrieved unnecessarily.
SQL Syntax & Examples (MySQL/MariaDB LIMIT
)
The LIMIT
clause is placed at the very end of your SELECT
statement, after ORDER BY
if present.
Syntax 1: LIMIT count
(Get the first ‘count’ rows)
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_to_sort_by
LIMIT count;
count
: The maximum number of rows you want to retrieve.
Example 1: Get the first 3 users
USE scriptbuzz_db;
SELECT user_id, username FROM users
LIMIT 3;
Expected Output (example – order might vary without ORDER BY):
user_id | username |
1 | john_doe |
2 | admin_user |
3 | jane_doe |
What it does: Retrieves the first 3 rows encountered in the users
table. Without an ORDER BY
clause, the “first” rows are not guaranteed to be consistent or meaningful (e.g., by ID).
Example 2: Get the 5 most expensive products
To get the “most expensive,” we need to sort the data first.
SELECT name, price FROM products
ORDER BY price DESC
LIMIT 5;
Expected Output (example):
name | price |
Laptop Pro | 1200.00 |
Gaming Monitor | 350.00 |
Mechanical Keyboard | 99.99 |
Gaming Mouse | 75.00 |
Webcam 1080p | 65.00 |
What it does: Sorts all products by price in descending order, then takes only the first 5 results from that sorted list.
Syntax 2: LIMIT offset, count
(For Pagination)
This syntax is crucial for pagination, allowing you to skip a certain number of rows before starting to retrieve.
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_to_sort_by
LIMIT offset, count;
offset
: The number of rows to skip from the beginning of the result set.offset
is 0-indexed, meaning the first row is at offset 0.count
: The maximum number of rows to return after the offset.
Example 3: Pagination – Page 1 (10 products per page)
Let’s assume we want to display 10 products per page, sorted by name.
SELECT product_id, name, price FROM products
ORDER BY name ASC
LIMIT 0, 10;
What it does: Skips 0 rows and retrieves the next 10 products. This is your “Page 1”.
Example 4: Pagination – Page 2 (10 products per page)
To get the next 10 products, you need to skip the first 10.
SELECT product_id, name, price FROM products
ORDER BY name ASC
LIMIT 10, 10;
What it does: Skips the first 10 rows and retrieves the next 10 products (rows 11-20). This is your “Page 2”.
General Pagination Formula: If you want N
items per page and you are on page_number
(starting from 1): LIMIT (page_number - 1) * N, N;
For instance, for page_number = 3
and N = 10
: LIMIT (3 - 1) * 10, 10;
which simplifies to LIMIT 20, 10;
Syntax 3 (Alternative in MySQL/MariaDB): LIMIT count OFFSET offset
This is another way to write the same thing as LIMIT offset, count
and is often considered more readable.
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_to_sort_by
LIMIT count OFFSET offset;
Example 5: Get 10 products starting from the 11th product (same as Page 2 above)
SELECT product_id, name, price FROM products
ORDER BY name ASC
LIMIT 10 OFFSET 10;
What it does: Identical functionality to LIMIT 10, 10
.
SQL Server TOP
Clause (For Awareness)
If you were working with SQL Server, the syntax for limiting results is different:
SELECT TOP count column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_to_sort_by;
Or, to get a percentage of rows:
SELECT TOP percentage PERCENT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_to_sort_by;
Example (SQL Server):
SELECT TOP 5 name, price FROM products
ORDER BY price DESC;
This is equivalent to LIMIT 5
in MySQL/MariaDB. Remember, for this tutorial, we will continue using LIMIT
.
Tips
- Always use
ORDER BY
withLIMIT
for consistent results. Without anORDER BY
clause, the order of rows returned by the database is not guaranteed. If you ask forLIMIT 10
without anORDER BY
, you might get a different set of 10 rows each time you run the query, even if the underlying data hasn’t changed. - Performance:
LIMIT
combined withORDER BY
can still be slow on very large tables if theORDER BY
column is not indexed. We will cover indexes in a later chapter to address this. - Calculating Total Rows for Pagination: To properly implement pagination in a web application, you usually need two pieces of information:
- The actual data for the current page (obtained with
SELECT ... LIMIT offset, count
). - The total number of rows without the
LIMIT
(obtained withSELECT COUNT(*) FROM table_name WHERE condition;
). This helps determine the total number of pages.
- The actual data for the current page (obtained with
Notes:
- The
LIMIT
clause (MySQL/MariaDB) restricts the number of rows returned by aSELECT
statement. LIMIT count
: Retrieves the firstcount
rows.LIMIT offset, count
: Retrievescount
rows starting afteroffset
rows.LIMIT count OFFSET offset
: An alternative, often more readable, syntax for the same.LIMIT
is fundamental for pagination and displaying “top N” results.- Always use
ORDER BY
withLIMIT
to ensure a consistent and predictable order of results. - Be aware that other database systems (like SQL Server) use
TOP
for similar functionality.
Small Exercise
Using your scriptbuzz_db
:
- Select the 2 most recently created users (hint: use
created_at
andDESC
). - Select the 3 cheapest products that are currently active (
is_active = 1
). - Imagine you want to display blog posts (from your
posts
table, if created) at 5 posts per page. Write the query to get the posts for “Page 3”, sorted bycreated_at
(newest first).
You’ve now learned how to precisely control which rows you retrieve and how many. This brings us closer to building dynamic web interfaces that manage data effectively. Next, we’ll learn how to perform calculations on your data!