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:

DatabaseSyntax
MySQL, PostgreSQL, SQLiteSELECT ... FROM ... LIMIT n;
SQL Server, MS AccessSELECT 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

ProductNamePrice
Espresso Beans 1kg18
Basmati Rice 5kg12.5
Olive Oil 1L9.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

CustomerIDCustomerName
4Delta Mart
5Evergreen Grocers
6Fjord Supplies

Tip: Always pair LIMIT with ORDER BY. Without it, "the first 3 rows" can change between runs.