SQL SELECT TOP

SQL SELECT TOP, LIMIT, ROWNUM

The SELECT TOP clause is used to specify the number of records to return from the top of the result set.

This clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.

Note: Not all database systems support the SELECT TOP clause. The syntax for fetching a limited number of records varies between different database systems.


Syntax for Different Databases

SQL Server / MS Access Syntax:

SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;

MySQL Syntax:

SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;

Oracle Syntax:

SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;

Demo Database

Below is a selection from the Customers table:

Customers Table:

CustomerID CustomerName Country
1 Alfreds Futterkiste Germany
2 Ana Trujillo Emparedados Mexico
3 Antonio Moreno Taquería Mexico
4 Around the Horn UK
5 Berglunds snabbköp Sweden

Example 1: LIMIT (MySQL)

The following SQL statement shows the LIMIT clause, which is the equivalent for MySQL. It selects the first 3 records from the Customers table.

LIMIT Example

SELECT * FROM Customers
LIMIT 3;

Example 2: TOP with WHERE (SQL Server)

The following SQL statement selects the top 2 records from the Customers table where the country is "Mexico".

TOP with WHERE Example

SELECT TOP 2 * FROM Customers
WHERE Country = 'Mexico';