TOP in SQL

Learn via video course
FREE
View all courses
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
Topics Covered

The SQL SELECT TOP command retrieves records from one or more tables in a database and allows us to limit the query result set based on the number of rows or the percentage of rows. This clause is used when the database tables contain thousands of records. In most cases, the TOP and ORDER BY constructions are used in conjunction. Otherwise, the TOP clause will return the first N rows in an arbitrary order. As a result, it is best practice to utilize the TOP clause in conjunction with an ORDER BY to produce a specific sorted result.

Consider the following example for a better understanding of TOP in SQL:

If a Student table contains a large quantity of data about students, the select TOP statement decides how much students' data will be fetched from the provided database. In this tutorial, we will learn how to use SQL SELECT TOP queries and strengthen our understanding with examples.

NOTE:
The TOP clause is not supported by all databases. For example, Oracle employs the ROWNUM command to fetch a limited amount of entries, while MySQL allows the LIMIT clause to fetch a limited number of records.

How Does TOP Work In SQL?

TOP in SQL (MySql LIMIT, Oracle ROWNUM) is a very useful command for selecting and filtering rows in large tables with thousands of records. This TOP keyword comes in use when we do not want to retrieve all of the rows that meet the requirement, as if there are millions of entries and you execute only the SELECT command, the query will take a long time and close your Query window. This keyword is also used to retrieve the top (n-highest) and lowest (n-lowest) data from a table.

When you use TOP in conjunction with INSERT, UPDATE, MERGE, or DELETE, the referenced rows are not sorted in any particular order. Also, you cannot explicitly define the ORDER BY clause in these statements. If you need to use TOP to insert, delete, or alter rows in relevant chronological order. In that case, it is recommended to use TOP with an ORDER BY clause specified in a subselect statement.

Syntax

KeywordDescription
expressionThe TOP keyword is followed by an expression that specifies the number of rows to be returned. If PERCENT is used, the expression is evaluated to a float value; otherwise, it is transformed to a BIGINT value.
PERCENTThe PERCENT keyword specifies that the query returns the first N percentage of rows, where N is the expression result. For example, if you use TOP \* 50 PERCENT, then it will return the top half of the table.
WITH TIESWITH TIES enables you to produce more rows with values matching the last row in the limited result set. It is important to note that WITH TIES may result in more rows being returned than you specified in the expression. For example, if you wish to return the most expensive products, use TOP 1. However, there is a possibility that two or more products will have the same price as the most costly product, and then the other most costly products in the result set might get missed. You can avoid this by using TOP 1 WITH TIES. It will cover not just the first and most costly products but also the second and subsequent ones, and so on.

Examples For TOP In SQL

The five SQL examples below will show you how to use the TOP in SQL command with PERCENT and WITH TIES keyword in the SQL :

Using the TOP keyword

Example - 1 : In this example, we have three columns in a Cars table, namely Car_Name, Car_Color, and Car_Cost :

Car_NameCar_ColorCar_Cost
Hyundai CretaWhite10,85,000
Hyundai VernaBlack9,50,000
Toyota FortunerBlack46,50,000
Swift DezireSilver9,80,000
Kia SeltosBlue8,00,000
Mahindra XUV 500White20,00,000

Assume you wish to display the first three-car names and colours from the table above. To accomplish this, enter the following TOP in the SQL query:

In the SQL output, this query displays the following table on the screen :

Car_NameCar_Color
Hyundai CretaWhite
Hyundai VernaBlack
Toyota FortunerBlack

Example - 2 : In this example, we have three columns in a Student table, namely Student_ID, Student_Name, and Student_Marks :

Student_IDStudent_NameStudent_Marks
9589Anand87
9592Ankit67
9594Dushyant45
9597Vishal70
9600Smita90

Assume you want to display the details of the first four students from the above table. To accomplish this, enter the following TOP in the SQL query :

In the SQL output, this query displays the following table on the screen :

Student_IDStudent_NameStudent_Marks
9589Anand87
9592Ankit67
9594Dushyant45
9597Vishal70

Example - 3: In this example, we have five columns in a Customer table, namely ID, NAME, AGE, ADDRESS, and SALARY :

IDNAMEAGEADDRESSSALARY
1Hardik32Ahmedabad20,000.00
2Komal23Delhi15,000.00
3Nishi27Delhi65,000.00
4Aman22Bhopal85,000.00
5Jai24Indore1,00,000.00

Assume you want to display the details of the first three customers from the above table. To accomplish this, enter the following TOP in the SQL query :

In the SQL output, this query displays the following table on the screen :

IDNAMEAGEADDRESSSALARY
1Hardik32Ahmedabad20,000.00
2Komal23Delhi15,000.00
3Nishi27Delhi65,000.00

Using the TOP PERCENT keyword

Example - 4: In this example, we have three columns in a Bikes table, namely Bike_Name, Bike_Color, and Bike_Cost :

Bike_NameBike_ColorBike_Cost
Kawasaki NinjaGreen5,00,000
Triumph Trident 660Orange7,58,000
Ducati MonsterBlack11,42,000
Harley-Davidson Iron 883Black10,14,000
KTM 390 DukeOrange2,87,000
BMW TigerBlueNULL

Assume you want to display 50 percent data from the above table. To accomplish this, enter the following TOP in the SQL query :

In the SQL output, this query displays the following table on the screen :

Bike_NameBike_ColorBike_Cost
Kawasaki NinjaGreen5,00,000
Triumph Trident 660Orange7,58,000
Ducati MonsterBlack11,42,000

Using the TOP WITH TIES keyword

Example - 5 : In this example, we have four columns in a Beverages table, namely Product_Name, Product_Volume, Product_Price, and Product_Quantity :

Product_NameProduct_VolumeProduct_PriceProduct_Quantity
Red Bull250 ml100.001
Ocean250 ml71.002
Fanta250 ml29.003
Pepsi250 ml29.002
Mirinda250 ml29.002
Coca Cola250 ml29.002

In the SQL output, this query returns the top three most expensive products :

Product_NameProduct_Price
Red Bull100.00
Ocean71.00
Fanta29.00
Pepsi29.00
Mirinda29.00
Coca Cola29.00

The third most costly product has a list price of 29.0029.00. Since the TOP in SQL command is used WITH TIES, it returned three more products with the same list price as the third.

Learn more

Conclusion

  • The TOP in SQL is used to get records from one or more tables in a database and limit the number of records returned based on a set value or percentage. This command comes in handy when working with huge databases.
  • The TOP in SQL Server statement restricts the number of rows returned in a query result set to a specified number or percentage of rows.
  • When you use the TOP in SQL with the ORDER BY clause, the result set is limited to the first N sorted rows. Otherwise, TOP returns the first N rows in an unspecified order.