Day 19: LIMIT and OFFSET
Introduction:
The
LIMITclause is used to specify the number of rows to return in a query. TheOFFSETclause is used to skip a specific number of rows before starting to return the rows.
Key Concepts:
LIMIT Clause: Restrict the number of rows returned.
OFFSET Clause: Skip a specified number of rows before returning the rows.
Pagination: Combine
LIMITandOFFSETto retrieve a subset of rows for paging through results.
SQL Commands and Examples:
Basic LIMIT Clause:
Retrieve a limited number of rows from a table.
-- Select the first 5 students
SELECT * FROM Students
LIMIT 5;
LIMIT with OFFSET:
Skip a number of rows before returning the results.
-- Select 5 students starting from the 3rd student (offset by 2)
SELECT * FROM Students
LIMIT 5 OFFSET 2;
Pagination Example:
Useful for applications that need to display a subset of results at a time.
-- Select 10 courses starting from the 11th course (offset by 10)
SELECT * FROM Courses
LIMIT 10 OFFSET 10;
Practice Exercise:
Use the Students table with columns
StudentID,FirstName,LastName,Age.Write a query to select the first 3 students.
Write a query to select 3 students starting from the 4th student (offset by 3).
Use the Courses table and write a query to select the first 5 courses.
Write a query to select 5 courses starting from the 6th course (offset by 5).
-- Select the first 3 students
SELECT * FROM Students
LIMIT 3;
-- Select 3 students starting from the 4th student
SELECT * FROM Students
LIMIT 3 OFFSET 3;
-- Select the first 5 courses
SELECT * FROM Courses
LIMIT 5;
-- Select 5 courses starting from the 6th course
SELECT * FROM Courses
LIMIT 5 OFFSET 5;
Using the LIMIT and OFFSET clauses effectively allows you to control the number of rows returned by your queries and implement pagination.
0 Comments