How to use SQL TOP Clause



SQL TOP Clause

We have already learned where clause and order by clause in our previous post.
In this post i will explain you what is TOP Clause and How to use TOP Clause in sql.

TOP Clause Definition :
The TOP Clause is used to return a TOP N number  records from a table.
The TOP clause is used to specify the number of record to return.

All database do not supports TOP Clause.
In MYSQL supports LIMIT clause to fetch limited data from a table.
In ORACLE supports ROWNUM clauses to fetch records from a table.

Syntax of TOP Clause:

SELECT TOP (top_value)  col1, col2 FROM Table_Name;

SELECT TOP(top_value) * FROM Table_Name WHERE Condition;

 

Example of TOP Clause:

SELECT * FROM StudentMst

ID Name City Pincode Mobile
1 Meera Bombay 380022 7874555555
2 Rahul Surat 352200 7874444444
3 Jayesh Ahmedabad 352200 7874333333
4 Dhvanish Bombay 380022 7874111111
5 Reena Baroda 352222 7874666666
6 Veera Baroda 352222 7874121212

 

SELECT TOP 3 * FROM StudentMst

ID Name City Pincode Mobile
1 Meera Bombay 380022 7874555555
2 Rahul Surat 352200 7874444444
3 Jayesh Ahmedabad 352200 7874333333

 

SELECT TOP 3 * FROM StudentMst WHERE ORDER BY ID DESC

ID Name City Pincode Mobile
6 Veera Baroda 352222 7874121212
5 Reena Baroda 352222 7874666666
4 Dhvanish Bombay 380022 7874111111

 

SELECT * FROM StudentMst ORDER BY NAME

ID Name City Pincode Mobile
4 Dhvanish Bombay 380022 7874111111
3 Jayesh Ahmedabad 352200 7874333333
1 Meera Bombay 380022 7874555555

Leave a Reply

Your email address will not be published. Required fields are marked *