LIMIT or TOP keyword in SQL
In SQL, the TOP or Limit keyword is used to limit the number of rows returned in a result set. It is commonly used when we want to retrieve only a specified number of records, for example, the top 10 highest salaries or the top 5 latest orders.
SQL Server Syntax
SELECT TOP (n) [ PERCENT ] column1, column2, ... FROM table_name [WHERE conditions] [ORDER BY column_name [ ASC | DESC ]];
MySQL Syntax
SELECT column1, column2, ... FROM table_name ORDER BY column_name DESC LIMIT n;
Example: Let's say we have a table named Employees with the following data:
Table: Employees
EmployeeID | FirstName | LastName | Age |
---|---|---|---|
1 | Ashish | Goel | 25 |
2 | Kirshan | Gupta | 30 |
3 | Anjali | Sharma | 25 |
4 | Manju | Saini | 15 |
5 | Katrina | Kaif | 18 |
6 | Esha | Dixit | 20 |
7 | Ankita | Verma | 19 |
8 | Meenakshi | Chikkara | 35 |
9 | Alia | Bhatt | 16 |
Query to get the top 3 highest Ages:
SQL
SELECT EmployeeID, FirstName, Age FROM Employees ORDER BY Age DESC Limit 3;
The result of the above query is shown below:
EmployeeID | FirstName | Age |
---|---|---|
8 | Meenakshi | 35 |
2 | Kirshan | 30 |
1 | Ashish | 25 |
This query returns the top 3 employees with the highest ages by ordering the data in descending order of the Age column.