Skip to main content

MySQL LIMIT

Introduction

When working with databases containing thousands or even millions of records, retrieving all data from a query can be inefficient and unnecessary. MySQL provides the LIMIT clause as a powerful tool to control the number of rows returned by a SELECT statement. This feature is essential for improving query performance, implementing pagination in web applications, and focusing on specific subsets of your data.

In this tutorial, we'll explore how to use the MySQL LIMIT clause effectively with plenty of practical examples.

Basic Syntax of MySQL LIMIT

The basic syntax of the LIMIT clause is straightforward:

sql
SELECT column_name(s)
FROM table_name
[WHERE condition]
[ORDER BY column_name(s)]
LIMIT [offset,] row_count;

Where:

  • row_count specifies the maximum number of rows to return
  • offset (optional) specifies the number of rows to skip before starting to return rows

Simple LIMIT Examples

Example 1: Retrieving a Fixed Number of Records

Let's say we have a products table and want to retrieve just the first 5 products:

sql
SELECT product_id, product_name, price
FROM products
LIMIT 5;

Output:

+------------+------------------+-------+
| product_id | product_name | price |
+------------+------------------+-------+
| 1 | Widget A | 19.99 |
| 2 | Gadget B | 24.95 |
| 3 | Tool C | 15.50 |
| 4 | Device D | 49.99 |
| 5 | Accessory E | 9.99 |
+------------+------------------+-------+

This query returns only the first 5 products, regardless of how many total products exist in the database.

Example 2: Using LIMIT with ORDER BY

Often, you'll want to use LIMIT with ORDER BY to get the top/bottom records based on a specific column:

sql
-- Find the 3 most expensive products
SELECT product_id, product_name, price
FROM products
ORDER BY price DESC
LIMIT 3;

Output:

+------------+------------------+-------+
| product_id | product_name | price |
+------------+------------------+-------+
| 10 | Premium Kit | 199.99|
| 8 | Professional Set | 149.95|
| 12 | Deluxe Package | 89.99 |
+------------+------------------+-------+

In this example, we're retrieving the three most expensive products by ordering all products by price in descending order and limiting the result to just 3 records.

Using LIMIT with OFFSET

The OFFSET parameter allows you to skip a specified number of rows before starting to return records.

Syntax

sql
SELECT column_name(s)
FROM table_name
LIMIT offset, row_count;

Or the more modern syntax:

sql
SELECT column_name(s)
FROM table_name
LIMIT row_count OFFSET offset;

Example 3: Retrieving Records with an Offset

If you want to retrieve records 6-10 from the products table:

sql
SELECT product_id, product_name, price
FROM products
LIMIT 5, 5;

Or using the alternative syntax:

sql
SELECT product_id, product_name, price
FROM products
LIMIT 5 OFFSET 5;

Output:

+------------+------------------+-------+
| product_id | product_name | price |
+------------+------------------+-------+
| 6 | Component F | 34.50 |
| 7 | Item G | 12.75 |
| 8 | Professional Set | 149.95|
| 9 | Basic Kit | 29.99 |
| 10 | Premium Kit | 199.99|
+------------+------------------+-------+

This query skips the first 5 records and returns the next 5.

Practical Applications of LIMIT

Implementing Pagination

One of the most common uses for LIMIT is implementing pagination in web applications. Let's say you want to display 10 records per page:

sql
-- Page 1
SELECT * FROM products LIMIT 0, 10;

-- Page 2
SELECT * FROM products LIMIT 10, 10;

-- Page 3
SELECT * FROM products LIMIT 20, 10;

We can generalize this with a formula:

sql
SELECT * FROM products LIMIT (page_number - 1) * items_per_page, items_per_page;

Example 4: Web Application Pagination

If you're building a product catalog with 20 products per page:

sql
-- For page 1
SELECT product_id, product_name, price
FROM products
ORDER BY product_name
LIMIT 0, 20;

-- For page 2
SELECT product_id, product_name, price
FROM products
ORDER BY product_name
LIMIT 20, 20;

Finding Top or Bottom Values

sql
-- Find the 5 cheapest products
SELECT product_id, product_name, price
FROM products
ORDER BY price ASC
LIMIT 5;

-- Find the 5 newest products
SELECT product_id, product_name, created_date
FROM products
ORDER BY created_date DESC
LIMIT 5;

Performance Considerations

Using LIMIT can significantly improve performance when working with large datasets:

  1. Reduced data transfer: Only returning the needed rows reduces network traffic.
  2. Lower memory usage: Both the database server and your application use less memory when processing fewer rows.
  3. Faster response time: Queries complete faster when they don't have to process all records.

However, it's important to note that MySQL still executes the entire query and then discards the rows that exceed the LIMIT. For optimal performance with large tables, combine LIMIT with properly indexed columns, especially in WHERE and ORDER BY clauses.

Example 5: Improving Performance with LIMIT and Indexing

Consider a table with millions of orders:

sql
-- This query scans all records, sorts them, then returns just 10
-- Could be slow without proper indexing
SELECT order_id, customer_id, order_date, total_amount
FROM orders
WHERE order_date > '2023-01-01'
ORDER BY order_date DESC
LIMIT 10;

For better performance, ensure order_date is indexed:

sql
CREATE INDEX idx_order_date ON orders(order_date);

Common Mistakes and Pitfalls

Mistake 1: Using LIMIT Without ORDER BY

When using LIMIT without an ORDER BY clause, MySQL returns rows in an arbitrary order, which might not be what you expect:

sql
-- Not recommended: order is not guaranteed
SELECT * FROM products LIMIT 5;

-- Better approach: specify the desired order
SELECT * FROM products ORDER BY product_id LIMIT 5;

Mistake 2: Forgetting That OFFSET Starts at 0

Remember that the first row has an offset of 0, not 1:

sql
-- This returns the FIRST row, not the second
SELECT * FROM products LIMIT 0, 1;

-- This returns the SECOND row
SELECT * FROM products LIMIT 1, 1;

Mistake 3: Using Large Offsets on Big Tables

Using large offsets on big tables can be inefficient:

sql
-- Potentially slow on large tables
SELECT * FROM products LIMIT 10000, 10;

For better performance with deep pagination, consider using keyset pagination instead:

sql
-- Assuming the last product_id on the previous page was 10025
SELECT * FROM products
WHERE product_id > 10025
ORDER BY product_id
LIMIT 10;

LIMIT in Different MySQL Versions

The LIMIT clause behavior has remained consistent across most MySQL versions, but there are some syntax differences:

  • MySQL 5.x and later: Both LIMIT offset, count and LIMIT count OFFSET offset are supported.
  • MariaDB (MySQL fork): Same behavior as MySQL.

Summary

The MySQL LIMIT clause is an essential tool for controlling the number of rows returned by your queries. We've covered:

  • Basic syntax and usage of LIMIT
  • Using LIMIT with OFFSET to skip records
  • Practical applications like pagination and finding top/bottom values
  • Performance considerations when using LIMIT
  • Common mistakes to avoid

By mastering the LIMIT clause, you can make your queries more efficient, implement common web application features like pagination, and focus on the specific data you need.

Exercises

To reinforce your understanding, try these exercises:

  1. Create a table called employees with at least 20 records and write a query to fetch the 5 highest-paid employees.
  2. Write a query that shows employees ranked 6-10 in terms of seniority (based on hire date).
  3. Implement a pagination query that shows 7 employees per page, and display the 3rd page of results.
  4. Write a query to find the 3 newest and 3 oldest employees (hint: you'll need two separate queries with LIMIT).
  5. If you have a table with 1 million records, write an efficient query to get records 990,000 to 990,010.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)