大表中的行数

2021-09-10 00:00:00 sql tsql sql-server
SELECT COUNT(*) FROM BigTable_1

如果我有超过 10 亿行,我应该使用哪种方式来获取表中的行数?

Which way I should to use to get number of rows in table if I have more than 1 billion of rows?

更新:例如,如果上面的查询出现超时问题",有什么方法可以优化它吗?如何更快地完成?

UPDATE: For example, if we have 'a timeout problem' with the query above is there any way to optimize it? How to do it quicker?

推荐答案

如果需要精确计数,必须使用COUNT (*)

If you need an exact count, you have to use COUNT (*)

如果您可以进行粗略计数,则可以使用分区中的行总和

If you are OK with a rough count, you can use a sum of rows in the partitions

SELECT SUM (Rows)
FROM sys.partitions
WHERE 1=1
And index_id IN (0, 1)
And OBJECT_ID = OBJECT_ID('Database.schema.Table');

如果你想用你的 COUNT 开玩笑,你可以执行以下操作

If you want to be funny with your COUNT, you can do the following

select COUNT (1/0) from BigTable_1

相关文章