Now, when we know how to count the rows in the results set, let's see how we can fetch first N rows only. Here we have two options:
We can use database-specific features in the SQL query itself.
We can process the result set ourselves and stop after the required number of rows has been fetched.
If you have been working mainly with MySQL, then you will be familiar with the LIMIT x,y
clause. For example, if we want to fetch the first five authors sorted by last name, the following query could be issued:
SELECT * FROM authors ORDER BY lastName LIMIT 0, 5;
The same thing could be done with the following query:
SELECT * FROM authors ORDER BY lastName LIMIT 5 OFFSET 0;
The first query will work for MySQL and SQLite, while the second will work for PostgreSQL as well. However, databases like Oracle or MS SQL Server don't use such syntax, so these queries will fail for them.