In MySQL, the LIMIT function is used to restrict the number of rows returned by a query. Here's how you can use it with an example:
Let's say you have a table called employees with columns employee_id, first_name, and last_name, and you want to retrieve the first 5 employees ordered by employee_id:
SELECT *
FROM employees
ORDER BY employee_id
LIMIT 5;
In this query:
- SELECT * selects all columns from the employees table.
- FROM employees specifies the table from which to retrieve the data.
- ORDER BY employee_id ensures that the results are sorted by the employee_id column.
- LIMIT 5 restricts the result set to only include the first 5 rows.
This query will return the first 5 rows from the employees table, sorted by employee_id.
You can also specify an optional offset to skip a certain number of rows before returning the result set. For example, to skip the first 10 rows and retrieve the next 5:
SELECT *
FROM employees
ORDER BY employee_id
LIMIT 5 OFFSET 10;
This query will skip the first 10 rows and return the next 5 rows from the employees table, sorted by employee_id.
Using LIMIT with OFFSET allows you to paginate through large result sets efficiently.
No comments:
Post a Comment