Sql Top Command
- Sql Select Top Clause returns a specific number of rows from the SELECT statement.
- It is very much like the SET ROWCOUNT function for that reason.
- It is usually used with order by clause
- The Select Top command is used MSSQL and Access database.
- If we add PERCENT Clause after “top clause”,than The specified percentage of records is bring.
Sql Top Command Syntax
Select top n columNames from tableName
Select top n percent columnNames from TableName
Select top n with ties columnNames from TableName order by columnNames
Note:WITH TIES can only be used with an ORDER BY. If you specify you want to return TOP 10 rows, and the 11th row has the same value as the 10th row on those columns that have been defined in the ORDER BY, then the 11th row will also be returned. Same for subsequent rows, until you get to the point that the values differ.
Select Top Command Examples on Library Database
Example 1: List 10 books, that has the highest page count.
Select top 10 * from books order by pageCount desc
Example 2: List the autor, whose name has the most letters
Select top 1 * from autors order by len(name) desc
Example 3: List the author that has the most books.
Select top 1 name,surname,count(*) as Quantity from books join authors on books.bookId = authors.bookId group by name,surname,authorId order by Quantity desc