SQL clause is the specific part of a SQL statement which is used to perform various operations. It can be combined to create more complex queries to retrieve and manipulate data.
TOP clause is used to fetch specified number or percentage of rows from a table.
It is often used with other clauses such as 'SELECT' and 'FROM' etc. to retrieve, specify table and manipulate data.
SELECT TOP n column_name(s) FROM table_name;
OR
SELECT TOP n PERCENT column_name(s) FROM table_name;
• Specify the column(s) name after the 'SELECT' keyword.
• Specify Asterisk (*) symbol to selects all columns from the table after the 'SELECT' keyword.
• Specify the table name after the 'FROM' keyword.
• Specify number or percentage of rows that you want to retrieve after the 'TOP' keyword.
1. Let's assume we have a table named "[Employees]".
Let's assume you want to retrieve only specific number of rows from [Employees] table.
Run below SQL statement :
SELECT TOP 3 * FROM [Employees];
Above statement will select only top 3 rows from the [Employees] table.
That's it! You have successfully retrieved top 3 rows from [Employees] table.
Let's assume you want to retrieve only specific percentage of rows from [Employees] table.
Run below SQL statement :
SELECT TOP 40 PERCENT * FROM [Employees];
Above statement will select only top 2 rows, considering that [Employees] table contained total 5 rows. 40 percent of 5 rows is equates to 2 rows.
That's it! You have successfully retrieved top 40 percent of rows from [Employees] table.
The TOP clause in SQL specifies the number of rows to return from a query result.
The TOP n clause in SQL Server limits the result set to the specified number of rows.
An alternative to the TOP clause in other database systems like MySQL is the LIMIT clause.
To select the top 5 records in SQL, you can use the "SELECT TOP 5" statement in SQL Server.