LIMIT and OFFSET

Estimated reading: 2 minutes 14 views

1. What is the purpose of LIMIT and OFFSET in SQL?

  • LIMIT: The LIMIT keyword in SQL is used to specify the number of records to return from the result set. It is commonly used to restrict the number of rows returned by a query.
  • OFFSET: The OFFSET keyword is used to specify the number of rows to skip before starting to return rows from the query. It is often used in conjunction with LIMIT to implement pagination.

Together, LIMIT and OFFSET allow you to control the number of rows returned and the starting point of the query result.


2. Write a query to fetch the first 10 rows from a table.

To retrieve the first 10 rows from a table, you can use the LIMIT keyword.

Example:

				
					SELECT * 
FROM employees
LIMIT 10;

				
			
  • This query will return the first 10 rows from the employees table.

3. How do you implement pagination in SQL queries?

Pagination can be implemented using LIMIT and OFFSET together. You can specify which set of rows to retrieve by skipping a specific number of rows and limiting the result to a specific count.

Example (Pagination for pages of 10 results):
To fetch the second page of results (rows 11 to 20) from a table:

				
					SELECT * 
FROM employees
LIMIT 10 OFFSET 10;

				
			
  • LIMIT 10 ensures that only 10 rows are returned.
  • OFFSET 10 skips the first 10 rows (so rows 11 to 20 are returned).

For the third page (rows 21 to 30):

				
					SELECT * 
FROM employees
LIMIT 10 OFFSET 20;

				
			

Leave a Comment

Share this Doc

LIMIT and OFFSET

Or copy link

CONTENTS