SQL SELECT TOP β Limit Rows in SQL Server Queries
Introduction β Why Use SELECT TOP?
The SELECT TOP clause is used in SQL to limit the number of rows returned in a result set. This is especially useful when:
- You only want the top N results (e.g., highest scores, latest records)
- Improving query performance on large tables
- Debugging and sampling datasets
π Note:
SELECT TOPis specific to SQL Server and MS Access. UseLIMITin MySQL/PostgreSQL andFETCH FIRSTin Oracle/standard SQL.
In this guide, youβll learn how to:
- Retrieve the first N rows using
TOP - Use
TOPwithORDER BY - Combine
TOPwithPERCENT - Understand syntax differences across databases
1. Basic SELECT TOP Syntax
SELECT TOP 5 *
FROM employees;
Returns the first 5 rows from the employees table.
2. SELECT TOP with ORDER BY
SELECT TOP 3 name, salary
FROM employees
ORDER BY salary DESC;
Retrieves the top 3 highest-paid employees.
3. SELECT TOP PERCENT
SELECT TOP 10 PERCENT *
FROM products
ORDER BY rating DESC;
Returns the top 10% of rows based on rating.
4. Equivalent Syntax in Other SQL Dialects
| SQL Server | MySQL / PostgreSQL | Oracle / ANSI SQL |
|---|---|---|
SELECT TOP 5 ... | SELECT ... LIMIT 5 | FETCH FIRST 5 ROWS ONLY |
5. TOP Without ORDER BY
SELECT TOP 5 * FROM students;
May return any 5 rows, not necessarily the top 5 by value β always use ORDER BY for consistency.
Best Practices
| Do This | Avoid This |
|---|---|
Use ORDER BY with TOP | Using TOP without sorting logic |
Combine TOP with business logic | Assuming TOP always returns same rows |
Use TOP PERCENT for proportions | Forgetting SQL Server specificity |
Summary β Recap & Next Steps
SELECT TOP is a quick and efficient way to limit the output of your queries in SQL Server. It becomes especially useful in sorted queries, dashboards, and analytics.
Key Takeaways:
TOPlimits the number of rows returned- Works best when used with
ORDER BY - Use
TOP PERCENTfor percentage-based sampling - Alternative: Use
LIMITorFETCH FIRSTin other RDBMS
Real-World Relevance:
Used in leaderboards, performance reports, previews, and pagination queries.
Next: Learn about LIMIT and OFFSET for row pagination across SQL dialects.
FAQ β SQL SELECT TOP
What does SELECT TOP do?
It restricts the number of rows returned by a query in SQL Server.
Whatβs the difference between TOP and LIMIT?
TOP is used in SQL Server. LIMIT is for MySQL/PostgreSQL. FETCH FIRST is for Oracle/standard SQL.
Can I use TOP with ORDER BY?
Yes. It’s the recommended way to return the top N sorted values.
Can I return the top 10% of rows?
Yes, use SELECT TOP 10 PERCENT ... with ORDER BY.
Is SELECT TOP ANSI SQL compliant?
No. Itβs specific to SQL Server and Access.
Share Now :
