Test setup with Postgres:
create table data (id integer, some_value integer);
insert into data
select i, i % 10
from generate_series(1,1000000) i;
create index on data (some_value);
analyze data;
So we have a table with 1 million rows and 10 distinct values for some_value
, so a condition like some_value = 9
will select 100000 rows:
explain (analyze,verbose)
select count(*)
from data
where some_value = 9;
Gives us:
Aggregate (cost=7761.13..7761.14 rows=1 width=8) (actual time=16.790..16.791 rows=1 loops=1)
Output: count(*)
-> Bitmap Heap Scan on stuff.data (cost=1854.13..7514.13 rows=98800 width=0) (actual time=4.703..14.001 rows=100000 loops=1)
Output: id, some_value
Recheck Cond: (data.some_value = 9)
Heap Blocks: exact=4425
-> Bitmap Index Scan on data_some_value_idx (cost=0.00..1829.43 rows=98800 width=0) (actual time=4.243..4.243 rows=100000 loops=1)
Index Cond: (data.some_value = 9)
Planning time: 0.101 ms
Execution time: 16.876 ms
And:
explain (analyze,verbose)
select count(*)
from (
select *
from data
where some_value = 9
) x;
Shows this:
Aggregate (cost=7761.13..7761.14 rows=1 width=8) (actual time=16.947..16.947 rows=1 loops=1)
Output: count(*)
-> Bitmap Heap Scan on stuff.data (cost=1854.13..7514.13 rows=98800 width=0) (actual time=4.816..14.173 rows=100000 loops=1)
Output: data.id, data.some_value
Recheck Cond: (data.some_value = 9)
Heap Blocks: exact=4425
-> Bitmap Index Scan on data_some_value_idx (cost=0.00..1829.43 rows=98800 width=0) (actual time=4.332..4.332 rows=100000 loops=1)
Index Cond: (data.some_value = 9)
Planning time: 0.071 ms
Execution time: 17.032 ms
As you can see: identical plans and essentially identical runtimes
If there is no index, we again get the same execution plans:
Aggregate (cost=17180.83..17180.84 rows=1 width=8) (actual time=67.336..67.336 rows=1 loops=1)
Output: count(*)
-> Seq Scan on stuff.data (cost=0.00..16925.00 rows=102333 width=0) (actual time=0.015..63.878 rows=100000 loops=1)
Output: id, some_value
Filter: (data.some_value = 9)
Rows Removed by Filter: 900000
Planning time: 0.046 ms
Execution time: 67.358 ms
Aggregate (cost=17180.83..17180.84 rows=1 width=8) (actual time=68.316..68.316 rows=1 loops=1)
Output: count(*)
-> Seq Scan on stuff.data (cost=0.00..16925.00 rows=102333 width=0) (actual time=0.014..64.848 rows=100000 loops=1)
Output: data.id, data.some_value
Filter: (data.some_value = 9)
Rows Removed by Filter: 900000
Planning time: 0.046 ms
Execution time: 68.336 ms