Need a row count after SELECT statement: what's the optimal SQL approach?

后端 未结 10 1076
悲哀的现实
悲哀的现实 2020-12-05 02:19

I\'m trying to select a column from a single table (no joins) and I need the count of the number of rows, ideally before I begin retrieving the rows. I have come to two app

10条回答
  •  再見小時候
    2020-12-05 02:33

    There are only two ways to be 100% certain that the COUNT(*) and the actual query will give consistent results:

    • Combined the COUNT(*) with the query, as in your Approach 2. I recommend the form you show in your example, not the correlated subquery form shown in the comment from kogus.
    • Use two queries, as in your Approach 1, after starting a transaction in SNAPSHOT or SERIALIZABLE isolation level.

    Using one of those isolation levels is important because any other isolation level allows new rows created by other clients to become visible in your current transaction. Read the MSDN documentation on SET TRANSACTION ISOLATION for more details.

提交回复
热议问题