Careeroza
LIMIT / TOP
Limiting the Number of Rows
Large tables can hold millions of rows. To return only the first few, each database has its own syntax:
| Database | Syntax |
|---|---|
| MySQL, PostgreSQL, SQLite | SELECT ... FROM ... LIMIT n; |
| SQL Server, MS Access | SELECT TOP n ... FROM ...; |
| Oracle 12c+, PostgreSQL, SQL Server 2012+ | ... OFFSET 0 ROWS FETCH FIRST n ROWS ONLY; |
LIMIT
Example
The three most expensive products:
SELECT ProductName, Price FROM Products
ORDER BY Price DESC
LIMIT 3;Result: 3 rows
| ProductName | Price |
|---|---|
| Espresso Beans 1kg | 18 |
| Basmati Rice 5kg | 12.5 |
| Olive Oil 1L | 9.99 |
TOP and FETCH FIRST
-- SQL Server
SELECT TOP 3 ProductName, Price FROM Products ORDER BY Price DESC;
-- SQL Server: top 50 percent of rows
SELECT TOP 50 PERCENT * FROM Products;
-- Oracle / standard SQL
SELECT ProductName, Price FROM Products
ORDER BY Price DESC
FETCH FIRST 3 ROWS ONLY;Pagination with OFFSET
OFFSET skips rows. Page n of size k is LIMIT k OFFSET (n-1)*k.
Example
Page 2 of customers, 3 per page:
SELECT CustomerID, CustomerName FROM Customers
ORDER BY CustomerID
LIMIT 3 OFFSET 3;Result: 3 rows
| CustomerID | CustomerName |
|---|---|
| 4 | Delta Mart |
| 5 | Evergreen Grocers |
| 6 | Fjord Supplies |
Tip: Always pair LIMIT with ORDER BY. Without it, "the first 3 rows" can change between runs.