SQL Tutorial
The TOP
clause in SQL Server is used to specify the number of records to return from a select query. The TOP
clause can be very useful on large tables with thousands of records, where returning a large number of records can impact performance.
Syntax:
SELECT TOP number|percent column_name(s) FROM table_name WHERE condition;
The number|percent
indicates that you can either specify a specific number of records to return, or a percentage of records to return.
Example 1: Return only the first 5 records.
SELECT TOP 5 * FROM Employees;
Example 2: Return the top 10 percent of records.
SELECT TOP 10 PERCENT * FROM Employees;
You can also use the TOP
clause with the ORDER BY
clause to return the top records based on a sort.
Example 3: Return the 3 employees with the highest salaries.
SELECT TOP 3 * FROM Employees ORDER BY Salary DESC;
Note: In other SQL systems, such as MySQL and PostgreSQL, the LIMIT
clause provides similar functionality to the TOP
clause.
Please note that the usage of TOP
without an ORDER BY
clause might not give you consistent results, as there's no guaranteed order of rows in a SQL table without an ORDER BY
clause. If you want a consistent result, always use TOP
with an ORDER BY
clause.
As always, the exact syntax and capabilities of the TOP
clause can vary between different SQL dialects, so it's important to consult the documentation for the SQL variant you're using.
How to Use TOP in SQL to Restrict Results:
TOP
keyword is used in SQL Server to limit the number of rows returned in a result set.SELECT TOP 5 column1, column2 FROM example_table;
SQL SELECT TOP N Rows:
TOP
clause can be used with a numerical value (N
) to specify the maximum number of rows to be returned.SELECT TOP 10 column1, column2 FROM example_table;
Examples of Limiting Rows in SQL Using TOP:
SELECT TOP 5 * FROM example_table;
SELECT TOP 3 column1, column2 FROM example_table WHERE condition;
Using TOP to Fetch a Specific Number of Rows in SQL:
TOP
keyword.SELECT TOP 8 column1, column2 FROM example_table ORDER BY column1;
MySQL LIMIT vs SQL Server TOP:
LIMIT
keyword is used to restrict the number of rows, while SQL Server uses TOP
.SELECT column1, column2 FROM example_table LIMIT 5;
PostgreSQL Equivalent of SQL Server TOP:
LIMIT
keyword is used similar to MySQL to restrict the number of rows.SELECT column1, column2 FROM example_table LIMIT 7;
Fetching Top Records in Oracle SQL:
ROWNUM
or FETCH FIRST
clause to limit rows.SELECT column1, column2 FROM example_table WHERE ROWNUM <= 6;
SELECT column1, column2 FROM example_table ORDER BY column1 FETCH FIRST 4 ROWS ONLY;