Fast Counting with PostgreSQL and Haskell
jezenthomas.com
jezenthomas.com
I have nothing but respect for the author, but if this is needed, maybe Postgres needs to invest some work?
Tldr: They estimate counts by parsing it out of the query plan but get an exact count if the estimate is under a threshold.
Clever! But it makes me nervous. I was expecting it to involve HLL or CountMinSketch or something.
They’re obviously better than nothing when making planning decisions—correctly estimating A > B is useful enough even if both are off by large factors—and maybe for this application it’s effective enough.
For the DBMS I work on, an alternative solution would involve bitmap indexes for each possible filter field. These are compact and can be logically combined and counted at rates of billions/second via SIMD, even without HLL or other estimators.
Why?
1. DBs typically store data in some flavor of b-tree. Determining the number of elements in a sub-range of a b-tree (or any "standard" search tree) is O(N).
2. You can improve that to O(log N) if each b-tree node stores the size of its subtree. But this also increases the cost of add/remove operations.
3. And things get more complicated for DBs that support concurrent transactions, since the count is different for each transaction, depending on when it began running. You'd need something more complicated than just a size-of-subtree integer per node.
It's all doable, but isn't trivial and increases the cost of all add/remove operations.
There have been times where I really wished it existed, though... :-)