SELECT TOP is a proprietary, non-standard extension used mainly in Microsoft SQL Server and Sybase ASE to restrict the number (or percentage) of rows returned by a SELECT statement. When placed immediately after SELECT, TOP evaluates before ORDER BY, so you almost always combine it with ORDER BY to get deterministic results. The clause can also be paired with PERCENT to return a percentage of the result set and WITH TIES to include additional rows that match the last row in the ordering, ensuring no data is omitted when duplicates exist.Because TOP is parsed before ORDER BY, scalar expressions and variables in TOP cannot reference aliases defined later in the SELECT list. Unlike LIMIT or FETCH FIRST, TOP does not support an OFFSET component; for paging you combine TOP with an anti-join or use OFFSET FETCH in modern SQL Server versions. TOP applies only to the final result set after all joins, filters, GROUP BY, and HAVING clauses are processed.
- quantity
(int or bigint) - The exact number of rows to return.- @var
(int or bigint variable) - T-SQL variable supplying the row count.- PERCENT
(keyword) - Interprets quantity as a percentage of the result set instead of an absolute count.- WITH TIES
(keyword) - Includes additional rows that match the ordering value of the last selected row; requires ORDER BY.- select_list
- Columns or expressions to retrieve.- table_name
- Target table or joined tables.- conditions
- Optional filter predicate.- column_list
- Columns that define sort order (strongly recommended).ORDER BY, LIMIT, FETCH FIRST, OFFSET FETCH, ROW_NUMBER, TOP WITH TIES
Microsoft SQL Server 7.0
LIMIT is used in MySQL and PostgreSQL and appears after ORDER BY. SELECT TOP is placed right after SELECT and lacks built-in OFFSET support.
Without ORDER BY, SQL Server chooses arbitrary rows, which can change between executions. ORDER BY guarantees deterministic, predictable results.
Yes. Enclose the variable in parentheses: `SELECT TOP (@rows) * FROM MyTable;` The variable must be an integer data type.
Use OFFSET FETCH: `ORDER BY id OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;` or wrap the query with ROW_NUMBER() and filter by row number range.