TOP n Clause : Top « Query « SQL Server / T-SQL Tutorial






The TOP n clause specifies the first n rows of the query result that are to be retrieved.


5>
6> create table department(
7>    dept_name     char(20)     not null,
8>    emp_cnt       int          not null,
9>    budget        float,
10>    date_month    datetime);
11> GO
1>
2> insert into department values('Research', 5, 50000, '01.01.2002');
3> insert into department values('Research', 10, 70000, '01.02.2002');
4> insert into department values('Research', 5, 65000, '01.07.2002');
5> insert into department values('Accounting', 5, 10000, '01.07.2002');
6> insert into department values('Accounting', 10, 40000, '01.02.2002');
7> insert into department values('Accounting', 6, 30000, '01.01.2002');
8> insert into department values('Accounting', 6, 40000, '01.02.2003');
9> insert into department values('Marketing', 6, 10000, '01.01.2003');
10> insert into department values('Marketing', 10, 40000, '01.02.2003');
11> insert into department values('Marketing', 3, 30000, '01.07.2003');
12> insert into department values('Marketing', 5, 40000, '01.01.2003');
13> GO

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)
1>
2> SELECT TOP 8 dept_name, budget
3> FROM department
4> ORDER BY budget DESC
5> GO
dept_name            budget
-------------------- ------------------------
Research                                70000
Research                                65000
Research                                50000
Accounting                              40000
Marketing                               40000
Accounting                              40000
Marketing                               40000
Accounting                              30000

(8 rows affected)
1>
2> drop table department;
3> GO
1>
2>








1.15.Top
1.15.1.TOP n Clause
1.15.2.TOP n Query with ORDER BY
1.15.3.Top Clause with the UPDATE statement.
1.15.4.Use TOP n clause with the DELETE statement.
1.15.5.A SELECT statement with a TOP clause
1.15.6.A SELECT statement with a TOP clause and the PERCENT keyword
1.15.7.A SELECT statement with a TOP clause and the WITH TIES keyword
1.15.8.A query that uses a derived table to retrieve the top 5 Bankers by average Billing total
1.15.9.Define variable for query top percent
1.15.10.Declare variable and use it in 'TOP PERCENT'