This SQL tutorial explains how to use the SQL SELECT TOP statement with syntax and examples.
The SQL SELECT TOP assertion is used to retrieve data from one or more tables in a database and limit the range of data lower back primarily based on a fixed price or percentage.
The syntax for the SELECT TOP assertion in SQL is:
SELECT TOP (top_value) [ PERCENT ] expressions FROM tables [WHERE conditions] [ORDER BY expression [ ASC | DESC ]];
Parameters or Arguments
TOP (top_value) It will return the top number of rows in the end result set based totally on top_value. For example, TOP(10) would return the top 10 rows from the full result set. PERCENT Optional. If PERCENT is specified, then the pinnacle rows are primarily based on a proportion of the total end result set (as specfied by using the top_value). For example, TOP(10) PERCENT would return the pinnacle 10% of the full result set. expressions The columns or calculations that you wish to retrieve. tables The tables that you want to retrieve files from. There have to be at least one desk listed in the FROM clause. WHERE conditions Optional. The prerequisites that have to be met for the information to be selected. ORDER BY expression Optional. It is used in the SELECT TOP statement so that you can order the results and goal these files that you desire to return. ASC is ascending order and DESC is descending order.
Example – Using TOP keyword
Let’s seem at a SQL example, the place we use the TOP key-word in the SELECT statement.
SELECT TOP(5) contact_id, last_name, first_name FROM contacts WHERE last_name = 'Anderson' ORDER BY contact_id;
This SQL SELECT TOP example would select the first 5 records from the contacts desk the place the last_name is ‘Anderson’. If there are other archives in the contacts desk that have a last_name of ‘Anderson’, they will now not be returned via the SELECT statement.
Example – Using TOP PERCENT keyword
Let’s appear at a SQL example, the place we use the TOP PERCENT key-word in the SELECT statement.
SELECT TOP(10) PERCENT contact_id, last_name, first_name FROM contacts WHERE last_name = 'Anderson' ORDER BY contact_id;
This SQL SELECT TOP instance would choose the first 10% of the records from the full end result set. So in this example, the SELECT declaration would return the top 10% of records from the contacts desk the place the last_name is ‘Anderson’. The other 90% of the end result set would no longer be returned by way of the SELECT statement.