Top Keyword in SQL

What is Top Keyword?

  • Top Keyword in SQL is used to retrieve the data from the top of the table.
  • It retrieves only the first few set of rows from the top of the desired table.
When to use Top Keyword?
  • When you want to retrieve a number of records from the top.
  • When you want to retrieve a specific percentage of rows from the top.
Syntax:

SELECT [TOP n [PERCENT] [WITH TIES] ] columnNames
FROM TableName
WHERE SearchCondition
[ORDER BY columnNames]
where,
  • TOP is a keyword used to retrieve rows from top of the table.
  • n is the number of rows to be retrieved.
  • PERCENT keyword can be used with n if we want to retrieve "n" percent of rows.
  • WITH TIES specifies the result can contain matching rows too.
  • ORDER BY clause specifies the order in which the rows should be returned.
Example:
  1. Select TOP 10 * From Students;  
This query retrieves the Top 10 rows from the Students table.
  1. Select TOP 10 PERCENT * From Students;  
This query retrieves the Top 10% rows of the Students table.
  1. Select TOP 5 * From Students  
  2. Where Marks>80;  
This query retrieves the Top 5 records from the Students table where the Marks are greater than 80.
  1. Select Top 10 WITH TIES StudentID, StudentName, Marks, City From Students  
  2. Where Marks>80  
  3. ORDER BY StudentID;  
This query retrieves the Top 10 records from the Students table along with ties where Marks are greater than 80 and will sort the result in ascending order of StudentID.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now