性能调优基础篇之select count(*) 与select count(1)

本文通过实验对比了在不同数量级的数据集上使用count(*)和count(1)查询性能的区别,发现两者在大部分情况下性能相当,但在千万数量级数据集时,count(1)查询性能有所下降。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很多时候count(*) 与count(1)容易造成人误解

实验环境: pg数据库 ,  


10万数量级

=> explain analyze select count(*) from city;
                                                  QUERY PLAN                                                   
---------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=5488.88..5488.89 rows=1 width=0) (actual time=13.690..13.690 rows=1 loops=1)
   ->  Seq Scan on city  (cost=0.00..5307.90 rows=72390 width=0) (actual time=0.004..8.382 rows=72390 loops=1)
 Total runtime: 13.726 ms
(3 rows)

Time: 23.646 ms
=> explain analyze select count(1) from city;
                                                  QUERY PLAN                                                   
---------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=5488.88..5488.89 rows=1 width=0) (actual time=16.912..16.912 rows=1 loops=1)
   ->  Seq Scan on city  (cost=0.00..5307.90 rows=72390 width=0) (actual time=0.005..9.382 rows=72390 loops=1)
 Total runtime: 16.952 ms
(3 rows)

Time: 20.035 ms                                                             


千万数量级

explain analyze select count(1) from xx;

                                                             QUERY PLAN                                                              
-------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=2144923.85..2144923.86 rows=1 width=0) (actual time=48684.707..48684.707 rows=1 loops=1)
   ->  Seq Scan on xx (cost=0.00..2102132.08 rows=17116708 width=0) (actual time=0.026..47239.822 rows=17154212 loops=1)
 Total runtime: 48691.623 ms
(3 rows)

Time: 48705.884 ms
hotel=>
 explain analyze select count(*) from xx;
^[[A                                                             QUERY PLAN                                                              
-------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=2144923.85..2144923.86 rows=1 width=0) (actual time=65436.442..65436.442 rows=1 loops=1)
   ->  Seq Scan on xx  (cost=0.00..2102132.08 rows=17116708 width=0) (actual time=0.006..64207.656 rows=17154225 loops=1)
 Total runtime: 65445.016 ms
(3 rows)

Time: 65446.541 ms



结论:count(*)并不比count(1)性能差


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值