SQL Tutorial SQL Advanced SQL Database SQL References

SQL - TOP, LIMIT or ROWNUM Clause



The SQL TOP Clause is used to fetch specified number or percentage of records from a table. This is useful when the table contains thousands of records and returning a large dataset can impact performance.

Note: TOP clause is not supported in all database. For example MySQL supports the LIMIT clause and Oracle uses ROWNUM keyword to fetch limited number of records.

Syntax

The syntax for using TOP Clause is given below:

/* SQL Server / MS Access Syntax */
SELECT TOP number|percent column1, column2, ...
FROM table_name
WHERE condition(s);

/* MySQL Syntax */
SELECT column1, column2, ...
FROM table_name
WHERE condition(s)
LIMIT number;

/* Oracle Syntax */
SELECT column1, column2, ...
FROM table_name
WHERE condition(s) AND ROWNUM <= number;

Example:

Consider a database containing a table called Employee with the following records:

EmpIDNameCityAgeSalary
1JohnLondon253000
2MarryNew York242750
3JoParis272800
4KimAmsterdam303100
5RameshNew Delhi283000
6HuangBeijing282800

  • To fetch top 3 records from the Employee table, the SQL query is:

    /* SQL Server / MS Access Query */
    SELECT TOP 3 * FROM Employee;
    
    OR
    
    /* SQL Server / MS Access Query */
    SELECT TOP 50 PERCENT * FROM Employee;
    
  • In Oracle, the above result can be achieved using ROWNUM keyword. Consider the example below:

    /* Oracle Query */
    SELECT * FROM Employee WHERE ROWNUM <= 3;
    
  • In MySQL, the above result can be achieved using LIMIT keyword. Consider the example below:

    /* MySQL Query */
    SELECT * FROM Employee LIMIT 3;
    

    This will produce the result as shown below:

    EmpIDNameCityAgeSalary
    1JohnLondon253000
    2MarryNew York242750
    3JoParis272800