LIMIT, FETCH & TOP (Pagination) πΒΆ
Prerequisites: ORDER BY Clause
Mentor's Note: Imagine searching for something on Google. You don't see 1 billion results at once; you see 10 at a time. This is "Pagination". In SQL, we use different commands depending on the database to achieve this. π‘
π The Scenario: The Hall of Fame πΒΆ
Imagine you have 1,000 players in a game.
- The Goal: You only want to show the "Top 3" players on the leaderboard.
- The Process: First, sort them by score (ORDER BY), then tell the computer to "Stop after 3 rows". β
π» 1. Multi-Dialect SyntaxΒΆ
A. MySQL & PostgreSQL (LIMIT)ΒΆ
The most common and easiest syntax.
B. Oracle (FETCH FIRST)ΒΆ
The modern ISO-standard way.
C. SQL Server (TOP)ΒΆ
π» 2. Offset (Page 2, Page 3...) πͺΒΆ
To see the next set of results (e.g., rows 4 to 6), we use an OFFSET.
π¨ Visual Logic: The Sliding WindowΒΆ
β οΈ Important RuleΒΆ
Always use ORDER BY with LIMIT! Without a sort order, the database might give you a different set of "Top 3" every time you run the query.