To retrieve the first N records in SQL, the exact syntax depends slightly on the database system, but the goal is the same โ limit the number of rows returned from a query.
In SQL Server, I typically use the TOP keyword:
SELECT TOP 5 *
FROM Employees;
This returns the first 5 records from the Employees table. I often use this during testing or data preview โ for instance, when verifying data quality after a migration or when I just want to inspect a small portion of a large dataset without loading everything.
In MySQL or PostgreSQL, the equivalent is the LIMIT clause:
SELECT *
FROM Employees
LIMIT 5;
This also returns the first 5 rows. Iโve used this approach frequently in dashboards where users only need to see a few top results โ for example, โTop 10 Customers by Sales.โ
In Oracle, the traditional way was using ROWNUM:
SELECT *
FROM Employees
WHERE ROWNUM <= 5;
However, in newer versions (12c and later), Oracle also supports FETCH FIRST N ROWS ONLY, which aligns with standard SQL:
SELECT *
FROM Employees
FETCH FIRST 5 ROWS ONLY;
A key point here is that SQL tables represent unordered sets โ so unless you specify an ORDER BY clause, โfirst N recordsโ is arbitrary. For example:
SELECT TOP 5 *
FROM Employees
ORDER BY HireDate ASC;
This ensures Iโm getting the earliest hired 5 employees, not just any 5 rows.
A challenge Iโve faced was when working with paginated queries โ for example, fetching rows 11 to 20 instead of just the top 10. In those cases, I use OFFSET with LIMIT:
SELECT *
FROM Employees
ORDER BY EmpID
LIMIT 10 OFFSET 10;
That retrieves records starting from the 11th.
In short:
- SQL Server:
TOP N - MySQL/PostgreSQL:
LIMIT N - Oracle:
FETCH FIRST N ROWS ONLYorROWNUM
And I always pair it with ORDER BY to ensure consistent, predictable results โ especially when the query is used in production reports or dashboards.
