π» Introduction
When working with large datasets, you often donβt want all rows at once. SQL provides row limiting clauses such as LIMIT
, FETCH FIRST
, and TOP
to control how many rows are returned.
Different databases use different syntax:
- MySQL / PostgreSQL:
LIMIT
- Oracle / DB2 / PostgreSQL (SQL:2008 standard):
FETCH FIRST
- SQL Server:
TOP
1οΈβ£ MySQL & PostgreSQL β LIMIT
Use LIMIT
to restrict the number of rows.
-- Return first 5 employees
SELECT * FROM Employees
LIMIT 5;
LIMIT with OFFSET
-- Skip first 5 rows, return next 5
SELECT * FROM Employees
LIMIT 5 OFFSET 5;
Tip: OFFSET is commonly used in pagination (e.g., displaying 10 records per page).
2οΈβ£ Oracle / PostgreSQL / DB2 β FETCH FIRST
FETCH FIRST
is part of the SQL standard for row limiting.
-- Return first 10 employees
SELECT * FROM Employees
FETCH FIRST 10 ROWS ONLY;
FETCH with OFFSET
-- Skip first 10 rows, return next 5
SELECT * FROM Employees
OFFSET 10 ROWS
FETCH NEXT 5 ROWS ONLY;
3οΈβ£ SQL Server β TOP
SQL Server uses TOP
to limit rows.
-- Return top 5 employees
SELECT TOP 5 * FROM Employees;
TOP with PERCENT
-- Return top 10% of employees
SELECT TOP 10 PERCENT * FROM Employees;
β Key Takeaways
LIMIT
β Used in MySQL & PostgreSQLFETCH FIRST
β SQL standard (Oracle, PostgreSQL, DB2)TOP
β Used in SQL ServerOFFSET
β Skips rows (used for pagination)- Row limiting is essential for performance and pagination
π Continue Learning
π¬ Got a question about SQL Row Limiting (LIMIT / FETCH FIRST)? Drop it in the comments below and letβs discuss!