In my query engine, SELECT COUNT(*) FROM table does not scan the table.
That sounds like cheating the first time you hear it. It is not. Parquet files already store how many rows they contain. The count is in the footer metadata, per file and per row group. If the query has no filter, reading every column just to count rows is wasted work. You open the footer, add up the numbers, and return.
SELECT COUNT(*) FROM orders;
-- footer metadata, no column scan
The catch is the filter.
SELECT COUNT(*) FROM orders WHERE status = 'shipped';
Now metadata alone cannot answer it. The footer stores min and max values for columns, so it can sometimes skip a whole row group. If 'shipped' falls outside the stored range for status, that row group has no matches. If it falls inside, you still have to read the column and check row by row. Metadata prunes. It does not count matches for you.
Same with COUNT(column). COUNT(*) counts rows. COUNT(email) counts rows where email is not null. The footer can help there too, because Parquet stores null counts, but only when the writer wrote them and only for the unfiltered case. Once a WHERE clause shows up, you are scanning again.
This is one of the small optimisations that made my engine look better than it is on simple queries. My engine is a C++20 columnar SQL engine over Parquet. It has 208 tests. Against DuckDB on 1M rows it wins 3 of 8 queries single-threaded and 5 of 8 with 4 scan threads. A metadata-only COUNT(*) is not one of the hard wins. DuckDB does the same kind of thing, and any engine that skips it is just leaving free time on the table.
The lesson I took from building it: before optimising the scan, check whether the scan needs to happen at all. A lot of query speed is not faster loops. It is reading less. Column pruning reads fewer columns. Predicate pushdown reads fewer row groups. Metadata counts read no rows at all.
The fastest scan is the one you delete.
Top comments (0)