SQL Select Top

HTML
CSS
C#
SQL

SQL Select Top

The SELECT TOP statement in SQL shows the limited number of records or rows from the database table. The TOP clause in the statement specifies how many rows are returned. It shows the top N number of rows from the tables in the output. This clause is used when there are thousands of records stored in the database tables.

Let’s take a simple example: If a Student table has a large amount of data about students, the select TOP statement determines how much student data will be retrieved from the given table.

Example:

SELECT TOP number | percent column_Name1, column_Name2, ….., column_NameN  FROM table_name WHERE [Condition] ;

In this syntax, the pattern is a sequence of characters that have to be searched in that column which is just specified after the WHERE clause.

Let’s take the following Employee table which helps you to analyze the LIKE operator with % sign:

table called Cars

Suppose, you want to show the first three Names and Color of Car from the above table. To do this, you have to type the following query in SQL:

SELECT TOP 3 Car_Name, Car_Color FROM Cars; 

 This query shows the following table:

We have a table called Student with three columns:

table called Student

Suppose, you want to show the details of the first four students in the result from the above table. To do this, you have to type the following query in SQL:

SELECT TOP 4 * FROM Student; 

This query shows the following table:

query shows

We have a table called Employee with four columns:

table called Employee

Suppose, you want to show the details of those first four employees whose city is Goa from the above table. To do this, you have to type the following query in SQL:

SELECT TOP 4 * FROM Employee WHERE Emp_City = Goa ; 

This query shows the following table:

 

query shows

Course Video

NOTE: Practice below practice questions on MSSQL SERVER, it will not execute on site editor.

1.Write a SQL query to select top 5 rows from Person.Address table.

(person.address)-(5 row count)

2. Write SQL Query to  get top 7 rows and get columns BusinessID, Name, AccountNumber, ActiveFlag from Purchasing.vendor table.  

(Purchasing.vendor)-(row count 7)

3. Write a SQL query to get 2 percent rows from   person table.

(person.person)-(400 row count)

4. Make a SQL Query to find top 11 rows and only want Name and ModifiedDate from  Sales.Currency table

(Sales.Currency) (11 rows count)

5. Write a SQL Query to get all the columns from HumanResources.Employee table with top 9 values.

(HumanResources.Employee)-(9 row count)