How do you use the TOP or LIMIT clause to restrict the number of returned rows?
Posted by DavidLee
Last Updated: July 01, 2024
The TOP and LIMIT clauses are used in SQL to restrict the number of rows that a query returns. However, the specific syntax can differ depending on the database management system (DBMS) you are using. Below are examples for both SQL Server (which uses TOP) and MySQL/SQLite/ PostgreSQL (which use LIMIT).
SQL Server (using TOP)
In SQL Server, you can use the TOP clause to specify the number of rows you want to return from your query. Here’s an example:
SELECT TOP 10 *
FROM Employees
ORDER BY Salary DESC;
In this example, the query returns the top 10 employees with the highest salaries.
MySQL, PostgreSQL, SQLite (using LIMIT)
In MySQL, PostgreSQL, and SQLite, you use the LIMIT clause. Here’s how it looks:
SELECT *
FROM Employees
ORDER BY Salary DESC
LIMIT 10;
This query also returns the top 10 employees with the highest salaries.
Other Considerations
- In PostgreSQL, you can also use the OFFSET clause in conjunction with LIMIT to skip a certain number of rows. For example:
SELECT *
    FROM Employees
    ORDER BY Salary DESC
    LIMIT 10 OFFSET 5;
This would return 10 employees starting from the 6th employee (after skipping the first 5). - In Oracle, a similar approach uses the ROWNUM pseudo-column or the FETCH FIRST clause in combination with ORDER BY:
SELECT *
    FROM Employees
    ORDER BY Salary DESC
    FETCH FIRST 10 ROWS ONLY;
Summary
- Use TOP in SQL Server. - Use LIMIT in MySQL, PostgreSQL, and SQLite. - For Oracle, use FETCH FIRST or ROWNUM. Make sure to check the exact syntax and capabilities of the specific SQL dialect you are working with, as they may have additional features or variations.