WikiGalaxy

Personalize

SQL SELECT TOP

Introduction:

The SQL SELECT TOP clause is used to specify the number of records to return. It is useful for limiting the results in large datasets.

Syntax:

The basic syntax of the SELECT TOP clause is:


SELECT TOP(number) column_name(s)
FROM table_name;
      

Example 1:

Retrieve the top 5 employees from the Employees table:


SELECT TOP(5) * FROM Employees;
      

Example 2:

Retrieve the top 10 products ordered by price:


SELECT TOP(10) * FROM Products ORDER BY Price DESC;
      

Example 3:

Retrieve 20% of the top students based on their scores:


SELECT TOP 20 PERCENT * FROM Students ORDER BY Score DESC;
      

Important Note:

The SELECT TOP clause is not supported by all SQL dialects. For example, MySQL uses LIMIT, while Oracle uses ROWNUM.

Console Output Example:

[Sample Output]

Advanced Usage of SELECT TOP

Combining with WHERE Clause:

You can combine the SELECT TOP clause with a WHERE clause to filter results further.


SELECT TOP(3) * FROM Orders WHERE Status = 'Pending';
      

Using with JOIN:

The SELECT TOP clause can be used in queries involving JOIN operations.


SELECT TOP(5) Customers.Name, Orders.OrderID
FROM Customers
JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
      

With Aggregation Functions:

Use the SELECT TOP clause along with aggregation functions like COUNT, SUM, etc.


SELECT TOP(1) Department, COUNT(EmployeeID) AS NumberOfEmployees
FROM Employees
GROUP BY Department
ORDER BY NumberOfEmployees DESC;
      

Caution:

Always ensure that your query returns the desired results, especially when using ORDER BY with SELECT TOP.

Console Output Example:

[Sample Output]

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025