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 TOPclause. The syntax for fetching a limited number of records varies between different database systems.
SELECT TOP number|percent column_name(s) FROM table_name WHERE condition;
SELECT column_name(s) FROM table_name WHERE condition LIMIT number;
SELECT column_name(s) FROM table_name WHERE ROWNUM <= number;
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 |
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.
SELECT * FROM Customers LIMIT 3;
TOP with WHERE (SQL Server)The following SQL statement selects the top 2 records from the Customers table where the country is "Mexico".
SELECT TOP 2 * FROM Customers WHERE Country = 'Mexico';