MySQL Tutorial
MySQL Installation and Configuration
MySQL Database Operations
Database Design
MySQL Data Types
MySQL Storage Engines
MySQL Basic Operations of Tables
MySQL Constraints
MySQL Operators
MySQL Function
MySQL Manipulate Table Data
MySQL View
MySQL Indexes
MySQL Stored Procedure
MySQL Trigger
MySQL Transactions
MySQL Character Set
MySQL User Management
MySQL Database Backup and Recovery
MySQL Log
MySQL Performance Optimization
The LIMIT
clause in MySQL is used to constrain the number of rows returned by the SELECT
statement. It's useful when you need to retrieve a specific portion of your data, especially when dealing with large databases.
Basic Usage
For example, if you have a table named employees
and you want to retrieve only the first 5 records, you would do this:
SELECT * FROM employees LIMIT 5;
This will return the first 5 rows from the employees
table.
OFFSET
The LIMIT
clause can also be used with an OFFSET
. The OFFSET
keyword skips a specified number of rows before starting to return the rows.
For instance, if you wanted to skip the first 5 records and get the next 5, you would do this:
SELECT * FROM employees LIMIT 5 OFFSET 5;
This will skip the first 5 rows and then return the next 5 rows.
An alternative syntax for the above statement uses a comma instead of the OFFSET
keyword:
SELECT * FROM employees LIMIT 5, 5;
This statement will do the exact same thing as the previous one - skip the first 5 rows and return the next 5.
Important Notes
The rows skipped by an OFFSET
clause still have to be computed internally by MySQL; so if you have a large number of rows to skip, it might be quite slow.
In MySQL, the first row retrieved is row 0, not row 1.
When using LIMIT
with OFFSET
, it's a good practice to use an ORDER BY
clause to make sure the retrieved rows are in a predictable order, especially when dealing with queries that could return more than one possible set of rows.
For instance:
SELECT * FROM employees ORDER BY hire_date DESC LIMIT 5, 5;
This will return the second set of 5 employees who were hired most recently.
MySQL LIMIT Clause Example:
SELECT * FROM table_name LIMIT 10;
How to Use LIMIT in MySQL:
SELECT column1, column2, ... FROM table_name LIMIT 5;
Limiting Query Results in MySQL:
SELECT * FROM customers ORDER BY registration_date DESC LIMIT 20;
Pagination with LIMIT in MySQL:
SELECT * FROM products LIMIT 10 OFFSET 20;
Combining LIMIT and OFFSET in MySQL:
SELECT * FROM orders LIMIT 5 OFFSET 10;
Dynamic LIMIT Values in MySQL:
SET @limit_value = 10; SELECT * FROM employees LIMIT @limit_value;
MySQL LIMIT vs FETCH in Queries:
SELECT * FROM tasks LIMIT 5;
Optimizing Queries with MySQL LIMIT:
SELECT * FROM large_table WHERE category = 'important' LIMIT 100;
Examples of Using LIMIT in MySQL Queries:
SELECT * FROM products WHERE price > 50 ORDER BY price DESC LIMIT 3;