Open In App
Related Articles

Top Clause in Microsoft SQL Server

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

THE SELECT TOP clause is used to fetch a limited number of rows from a database. This clause is very useful while dealing with large databases. The top Clause will be useful for fetching the data records in larger datasets as it will drastically reduce the complexity.

Syntax

SELECT TOP value column1,column2 FROM table_name;

value: number of rows to return from top

column1 , column2 fields in the table

table_name: name of table

Syntax Using Percent

SELECT TOP value PERCENT column1,column2 FROM table_name;

value: percentage of number of rows to return from top

column1 , column2: fields in the table

table_name: name of table

Parameter Explanation

  1. TOP: Clause is used for fetching the top records from a huge dataset.

Lets us see examples for Top Clause in  Microsoft SQL Server, for this we create a database. 

Query:

CREATE TABLE Customer(
    CustomerID INT PRIMARY KEY,
    CustomerName VARCHAR(50),
    LastName VARCHAR(50),
    Country VARCHAR(50),
    Age int(2),
    Phone int(10)
);

-- Insert some sample data into the Customers table
INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age, Phone)
VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),
       (2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),
       (3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),
       (4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),
       (5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain','22','xxxxxxxxxx');

Output:

output1

 

Query:

To fetch the first two data sets from the Customer table.

SELECT TOP 2 * FROM Customer;

Output

output2

 

Add WHERE Clause in SQL Server

We can fetch data records by using a where clause with some condition was well.

Query:

SELECT TOP 1 * FROM Customers
WHERE Country='Spain';

Output:

output4

 

Note:

To get the same functionality on MySQL and Oracle databases there is a bit of difference in the basic syntax;

  • For MySQL databases:
SELECT column1,column2 FROM table_name LIMIT value;
column1 , column2: fields int the table
table_name: name of table
value: number of rows to return from top
  • For Oracle databases:
SELECT column1,column2 FROM table_name WHERE ROWNUM <= value;
column1 , column2: fields int the table
table_name: name of table
value: number of rows to return from top


Last Updated : 13 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads