Curriculum
In this tutorial, you’ll learn how to use the SELECT TOP statement inside a T-SQL statement in SQL Server, along with its syntax, examples, and use cases.
The SELECT TOP statement in SQL Server allows the SQL developers to limit the number of records or percentage of records that are returned when the query is executed.
SELECT TOP (topvalue) [ PERCENT ] [ WITH TIES ] expressions FROM tables [WHERE conditions] [ORDER BY expression [ ASC | DESC ]];
Let’s look at the Person.Person table in the Adventure Works database and try out the SELECT TOP Query.
Below is a sample query that returns the TOP 10 Person records ordered by their FirstName.
SELECT TOP 10 FirstName FROM [Person].[Person] ORDER BY FirstName
In the below query, we have included the WITH TIES clause along with the SELECT TOP.
SELECT TOP 10 WITH TIES FirstName FROM [Person].[Person] ORDER BY FirstName
Although we have only 10 records in the SELECT TOP, the WITH TIES will also return all the Names with the same value that is found in TOP 10 records. As a result, you will see more records being returned that what is specified in the SELECT TOP 10.
Let’s have a look at an SQL query that uses PERCENT to specify the percentage of results returned when the query is run. The table contains 19972 records, and the below query returns the first 10% of the records from those 19972 records.
SELECT TOP(10) PERCENT * FROM [Person].[Person]
The other 90% of the result set will not be returned when the above query is run.