Top Clause in SQL



The TOP clause

The TOP clause is used to limit the number of rows returned by the query.
For example, you can either use the TOP keyword to return the first n rows or the first n percent of rows from a result set.

Syntax:
             select top(expression)[PERCENT][WITH TIES]
                      from table_name order by column_name

The select statement can also use other clauses like WHERE, JOIN, GROUP BY and HAVING


expression
The TOP keyword is an expression that specifies the number of rows to be returned.

PERCENT

The PERCENT keyword indicates that the query returns the first N percentage of rows
For example, if we have 10 results in the table and the query is top 1 percent then it returns only 1 result because of 1 percent of 10 is 1.

WITH TIES

This keyword returns the data that matches the values as explained with the example below.

Example:-

1. Top clause use:-
select top(3) firstname,Salary from Employees order by salary desc.




2. Top clause with percentage:-

select top 1 percent FirstName,Salary from employees order by Salary desc



3. Top clause with TIES:-

select top(3) with ties FirstName,Salary from employees order by Salary desc

             





Explanation:-
              


Note:- Top clause is used in conjunction with an order by clause.

Comments :

Post a Comment