SQL TOP Clause

TOP Clause

The TOP clause is used to specify the number of records to be returned.

The TOP clause is very useful for large tables with thousands of records.

Note:Not all database systems support the TOP clause.

SQL Server Syntax:

SELECT TOP number|percent column_name(s)
FROM table_name

SQL SELECT TOP in MySQL and Oracle is equivalent

MySQL Syntax

SELECT column_name(s)
FROM table_name
LIMIT number

Example

SELECT *
FROM Persons
LIMIT 5

Oracle Syntax

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

Example

SELECT *
FROM Persons
WHERE ROWNUM <= 5

Original Table (used in examples):

Persons Table:

Id LastName FirstName Address City
1 Adams John Oxford Street London
2 Bush George Fifth Avenue New York
3 Carter Thomas Changan Street Beijing
4 Obama Barack Pennsylvania Avenue Washington

SQL TOP Example

Now, we want to select the first two records from the 'Persons' table above.

We can use the following SELECT statement:

SELECT TOP 2 * FROM Persons

Result:

Id LastName FirstName Address City
1 Adams John Oxford Street London
2 Bush George Fifth Avenue New York

SQL TOP PERCENT Example

Now, we want to select 50% of the records from the 'Persons' table above.

We can use the following SELECT statement:

SELECT TOP 50 PERCENT * FROM Persons

Result:

Id LastName FirstName Address City
1 Adams John Oxford Street London
2 Bush George Fifth Avenue New York