Home > Database > Mysql Tutorial > How to Implement the Equivalent of MySQL's LIMIT Clause in SQL Server?

How to Implement the Equivalent of MySQL's LIMIT Clause in SQL Server?

DDD
Release: 2025-01-14 11:30:43
Original
257 people have browsed it

How to Implement the Equivalent of MySQL's LIMIT Clause in SQL Server?

Replicating MySQL's LIMIT in SQL Server

MySQL's LIMIT clause restricts the number of rows returned. SQL Server achieves this using the TOP clause. Here's how to get the same functionality:

SQL Server 2005 and Later

For SQL Server 2005 and subsequent versions, a common approach involves using ROW_NUMBER():

<code class="language-sql">SELECT *
FROM (
    SELECT *, ROW_NUMBER() OVER (ORDER BY Id) as RowNum
    FROM OrderedOrders
) as RankedOrders
WHERE RowNum BETWEEN 10 AND 20;</code>
Copy after login

This assigns a unique rank to each row and then filters based on that rank.

SQL Server 2000 and Earlier

In older versions (SQL Server 2000 and below), a nested SELECT statement is necessary:

<code class="language-sql">SELECT TOP 10 * 
FROM (SELECT TOP 20 * FROM Table ORDER BY Id) as SubQuery
ORDER BY Id DESC;</code>
Copy after login

This first selects the top 20 rows, then from that subset, selects the top 10. Note the importance of the secondary ORDER BY clause for consistent results. The ordering in both queries is crucial for obtaining the desired rows.

The above is the detailed content of How to Implement the Equivalent of MySQL's LIMIT Clause in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template