Introduction
We can filter the top N rows or percent of rows from the query result based on an order by.
When we use the Top Option, then Order by is not required. In SQL, the Offset-fetch functionwasn introduced. For more information, see offset–fetch.
- Top (N) [With Ties]. This means the number of rows; N is the constant value or @variable (BIGINT) data type.
- Top (N) [With Ties] – Percent. This means the percentage of rows is based on value.
Example
CREATE TABLE #STUDENT
(
NAME VARCHAR (50),
MARKS INT
)
INSERT INTO #STUDENT (NAME, MARKS) VALUES ('RAKESH', 99)
INSERT INTO #STUDENT (NAME, MARKS) VALUES ('MADHU', 95)
INSERT INTO #STUDENT (NAME, MARKS) VALUES ('NARESH', 88)
INSERT INTO #STUDENT (NAME, MARKS) VALUES ('RAJU', 87)
INSERT INTO #STUDENT (NAME, MARKS) VALUES ('PANKAJ', 95)
INSERT INTO #STUDENT (NAME, MARKS) VALUES ('RAMU', 66)
INSERT INTO #STUDENT (NAME, MARKS) VALUES ('SHEKAR', 90)
INSERT INTO #STUDENT (NAME, MARKS) VALUES ('RAKI', 68)
INSERT INTO #STUDENT (NAME, MARKS) VALUES ('MAHESH', 95)
INSERT INTO #STUDENT (NAME, MARKS) VALUES ('PARVEEN', 94)
SELECT * FROM #STUDENT

Top (N)
Top 2 Students from Student table based on Marks.


The solution to the preceding is given here:
SELECT TOP 2 WITH TIES * FROM #STUDENT
ORDER BY MARKS DESC

Top (N) Percent
Using Top with PERCENT will give the percent of rows.
Example
SELECT TOP 50 PERCENT * FROM #STUDENT
ORDER BY MARKS DESC

We have 10 rows in the Student table. Out of that, we have selected 50 percent of the rows from the Student table. The result of rows will be 5.
Top (N) Percent with Ties
SELECT TOP 50 PERCENT WITH TIES * FROM #STUDENT
ORDER BY MARKS DESC


Sibeesh VenuPosted Jul 20, 2015, 4:50 AM
Nice Share.
Rakesh KalluriPosted Jul 20, 2015, 2:12 AM
Thanks Upendra Pratap Shahi
Rakesh KalluriPosted Jul 20, 2015, 2:12 AM
Thanks Rakesh Chavda
Rakesh KalluriPosted Jul 20, 2015, 2:11 AM
Thanks SanthaKumar
Upendra Pratap ShahiPosted Jul 20, 2015, 12:54 AM
nice one..
RakeshPosted Jul 19, 2015, 7:49 AM
Good one
Santhakumar MunuswamyPosted Jul 19, 2015, 7:46 AM
Good one
Rakesh KalluriPosted Jul 18, 2015, 2:11 PM
Thanks to all
Rakesh KalluriPosted Jul 18, 2015, 2:11 PM
Thanks narisimha reddy
Narasimha Reddy ChennupalliPosted Jul 18, 2015, 1:35 PM
Nice one
Rakesh KalluriPosted Jul 18, 2015, 12:28 PM
Thanks Pankaj
Pankaj Kumar ChoudharyPosted Jul 18, 2015, 11:38 AM
Nice Explain Sir......
Rakesh KalluriPosted Jul 18, 2015, 11:24 AM
Thanks Sharad
SharadPosted Jul 18, 2015, 11:19 AM
good one
Rakesh KalluriPosted Jul 18, 2015, 11:12 AM
Thanks Gopi Chand
Gopi ChandPosted Jul 18, 2015, 11:06 AM
Its nice
Rakesh KalluriPosted Jul 18, 2015, 10:54 AM
Thanks Sibeesh Venu
Rakesh KalluriPosted Jul 18, 2015, 10:53 AM
Thanks Chervine Bhiwoo
Sibeesh VenuPosted Jul 18, 2015, 10:45 AM
Nice Share
Chervine BhiwooPosted Jul 18, 2015, 10:31 AM
Very useful! Thanks!