T-SQL Tutorial T-SQL Advanced Database Management T-SQL References

T-SQL - TOP Keyword



The T-SQL (Transact-SQL) TOP keyword 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.

Syntax

The syntax for using TOP keyword in T-SQL (Transact-SQL) is given below:

SELECT TOP number|percent column1, column2, ...
FROM table_name
WHERE condition(s);

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 query is:

    SELECT TOP 3 * FROM Employee;
    

    This will produce the result as shown below:

    EmpIDNameCityAgeSalary
    1JohnLondon253000
    2MarryNew York242750
    3JoParis272800
  • The above result can also be achieved by using PERCENT keyword in the query.

    SELECT TOP 50 PERCENT * FROM Employee;
    

    This result of the following code will be:

    EmpIDNameCityAgeSalary
    1JohnLondon253000
    2MarryNew York242750
    3JoParis272800
  • To fetch top 3 records where the Age of the employee is greater than 25, the query will be:

    SELECT TOP 3 * FROM Employee 
    WHERE Age > 25;
    

    This will produce the result as shown below:

    EmpIDNameCityAgeSalary
    3JoParis272800
    4KimAmsterdam303100
    5RameshNew Delhi283000

❮ T-SQL Keywords