The SELECT TOP
clause in SQL is used to specify the number of rows to return from the result set. It is often used with large tables where you want to retrieve only a limited number of records. The SELECT TOP
clause is supported by some databases, such as SQL Server, while others may use different syntax (e.g., LIMIT
in MySQL or FETCH FIRST
in Oracle).
The basic syntax of SELECT TOP
is as follows:
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
You can specify either a fixed number of rows or a percentage of rows to return.
Consider the following Customers
table:
CustomerID | CustomerName | City | Country |
---|---|---|---|
1 | MOHD Zaid Khan | New York | USA |
2 | Akef Khan | London | UK |
3 | Khizar Mirza | Berlin | Germany |
4 | Laeeque Deshmukh | Paris | France |
5 | Shaikh Arshiya Naaz | Madrid | Spain |
To return the top 3 customers from the Customers
table, you can use the following SQL query:
SELECT TOP 3 CustomerName, City
FROM Customers;
This query will return the top 3 customers based on the default order of the table (usually the order of insertion).
If you want to return the top 50% of rows, you can modify the query like this:
SELECT TOP 50 PERCENT CustomerName, City
FROM Customers;
This query will return 50% of the rows from the Customers
table.
The result of the query to select the top 3 customers would be:
CustomerName | City |
---|---|
MOHD Zaid Khan | New York |
AKef khan | London |
Khizar Mirza | Berlin |
In this case, the top 3 customers are listed.