|
| 1 | +# PostgreSQL Planner Optimization: Automatic COUNT(*) Conversion |
| 2 | + |
| 3 | +## Introduction |
| 4 | + |
| 5 | +In October 2025, PostgreSQL committer David Rowley proposed a significant query planner optimization that automatically converts `COUNT(1)` and `COUNT(not_null_col)` expressions to `COUNT(*)`. This optimization addresses a common performance anti-pattern where developers write `COUNT(1)` thinking it's equivalent to `COUNT(*)`, when in fact `COUNT(*)` is more efficient. The patch was committed in November 2025 and introduces new infrastructure for aggregate function simplification. |
| 6 | + |
| 7 | +## Why This Matters |
| 8 | + |
| 9 | +The performance difference between `COUNT(*)` and `COUNT(column)` can be substantial, especially for large tables. When counting a specific column, PostgreSQL must: |
| 10 | + |
| 11 | +1. **Deform the tuple** to extract the column value |
| 12 | +2. **Check for NULL values** (even for NOT NULL columns, the check still occurs) |
| 13 | +3. **Process the column data** through the aggregate function |
| 14 | + |
| 15 | +In contrast, `COUNT(*)` can count rows without accessing individual column values, resulting in significantly better performance. David Rowley's benchmarks showed approximately **37% performance improvement** when using `COUNT(*)` instead of `COUNT(not_null_col)` on a table with 1 million rows. |
| 16 | + |
| 17 | +## Technical Analysis |
| 18 | + |
| 19 | +### The Infrastructure: SupportRequestSimplifyAggref |
| 20 | + |
| 21 | +The patch introduces a new infrastructure called `SupportRequestSimplifyAggref`, which is similar to the existing `SupportRequestSimplify` used for regular function expressions (`FuncExpr`). Since aggregates use `Aggref` nodes, a separate mechanism was needed. |
| 22 | + |
| 23 | +The key components include: |
| 24 | + |
| 25 | +1. **New support node type**: `SupportRequestSimplifyAggref` in `supportnodes.h` |
| 26 | +2. **Simplification function**: `simplify_aggref()` in `clauses.c` that calls the aggregate's support function during constant folding |
| 27 | +3. **Enhanced nullability checking**: Extended `expr_is_nonnullable()` to handle `Const` nodes, not just `Var` nodes |
| 28 | + |
| 29 | +### Implementation Details |
| 30 | + |
| 31 | +The optimization is performed during the constant folding phase of query planning, specifically in `eval_const_expressions_mutator()`. When an `Aggref` node is encountered, the planner: |
| 32 | + |
| 33 | +1. Checks if the aggregate function has a support function registered via `pg_proc.prosupport` |
| 34 | +2. Calls the support function with a `SupportRequestSimplifyAggref` request |
| 35 | +3. If the support function returns a simplified node, replaces the original `Aggref` |
| 36 | + |
| 37 | +For the `COUNT` aggregate specifically, the support function (`int8_agg_support_simplify()`) checks: |
| 38 | + |
| 39 | +- Whether the argument is non-nullable (using `expr_is_nonnullable()`) |
| 40 | +- Whether there are no `ORDER BY` or `DISTINCT` clauses in the aggregate |
| 41 | +- If both conditions are met, converts `COUNT(ANY)` to `COUNT(*)` |
| 42 | + |
| 43 | +### Code Example |
| 44 | + |
| 45 | +The core simplification logic in `int8.c`: |
| 46 | + |
| 47 | +```c |
| 48 | +static Node * |
| 49 | +int8_agg_support_simplify(SupportRequestSimplifyAggref *req) |
| 50 | +{ |
| 51 | + Aggref *aggref = req->aggref; |
| 52 | + |
| 53 | + /* Only handle COUNT */ |
| 54 | + if (aggref->aggfnoid != INT8_AGG_COUNT_OID) |
| 55 | + return NULL; |
| 56 | + |
| 57 | + /* Must have exactly one argument */ |
| 58 | + if (list_length(aggref->args) != 1) |
| 59 | + return NULL; |
| 60 | + |
| 61 | + /* No ORDER BY or DISTINCT */ |
| 62 | + if (aggref->aggorder != NIL || aggref->aggdistinct != NIL) |
| 63 | + return NULL; |
| 64 | + |
| 65 | + /* Check if argument is non-nullable */ |
| 66 | + if (!expr_is_nonnullable(req->root, |
| 67 | + (Expr *) linitial(aggref->args), |
| 68 | + true)) |
| 69 | + return NULL; |
| 70 | + |
| 71 | + /* Convert to COUNT(*) */ |
| 72 | + return make_count_star_aggref(aggref); |
| 73 | +} |
| 74 | +``` |
| 75 | +
|
| 76 | +## Patch Evolution |
| 77 | +
|
| 78 | +The patch went through four iterations, each refining the implementation: |
| 79 | +
|
| 80 | +### Version 1 (Initial Proposal) |
| 81 | +- Introduced the basic infrastructure |
| 82 | +- Used `SysCache` to fetch `pg_proc` tuples |
| 83 | +
|
| 84 | +### Version 2 (Code Cleanup) |
| 85 | +- Replaced `SysCache` lookup with `get_func_support()` function |
| 86 | +- Cleaner and more efficient approach |
| 87 | +
|
| 88 | +### Version 3 (Removed Experimental Code) |
| 89 | +- Removed `#ifdef NOT_USED` block that handled `COUNT(NULL)` optimization |
| 90 | +- Cleaned up unused includes |
| 91 | +- Improved comments |
| 92 | +
|
| 93 | +### Version 4 (Final Version) |
| 94 | +- Rebased after commit `b140c8d7a` |
| 95 | +- Fixed assumption that support function always returns an `Aggref` |
| 96 | +- Allows support functions to return other node types (e.g., constants) for more aggressive optimizations |
| 97 | +- This flexibility enables future optimizations like converting `COUNT(NULL)` to `'0'::bigint` |
| 98 | +
|
| 99 | +## Community Insights |
| 100 | +
|
| 101 | +### Reviewer Feedback |
| 102 | +
|
| 103 | +**Corey Huinker** provided positive feedback: |
| 104 | +- +1 for the automatic query improvement |
| 105 | +- Noted that we can't educate everyone that `COUNT(1)` is an anti-pattern, so making it not an anti-pattern is the right approach |
| 106 | +- Confirmed the patch applies cleanly and tests pass |
| 107 | +
|
| 108 | +**Matheus Alcantara** also reviewed and tested: |
| 109 | +- Confirmed ~30% performance improvement in benchmarks |
| 110 | +- Validated that the code placement is consistent with existing `SupportRequestSimplify` infrastructure |
| 111 | +- +1 for the idea |
| 112 | +
|
| 113 | +### Design Decisions |
| 114 | +
|
| 115 | +**Timing of Optimization**: The optimization happens during constant folding, which is early in the planning process. David considered whether it should happen later (after `add_base_clause_to_rel()`) to catch cases like: |
| 116 | +
|
| 117 | +```sql |
| 118 | +SELECT count(nullable_col) FROM t WHERE nullable_col IS NOT NULL; |
| 119 | +``` |
| 120 | + |
| 121 | +However, it must happen before `preprocess_aggref()`, which groups aggregates with the same transition function. The current placement is consistent with `SupportRequestSimplify` for regular functions. |
| 122 | + |
| 123 | +**Support Function Return Type**: The infrastructure allows support functions to return nodes other than `Aggref`. This design decision enables future optimizations, such as: |
| 124 | +- Converting `COUNT(NULL)` to `'0'::bigint` |
| 125 | +- More aggressive constant folding for aggregates |
| 126 | + |
| 127 | +## Performance Considerations |
| 128 | + |
| 129 | +The optimization provides significant performance benefits: |
| 130 | + |
| 131 | +1. **Reduced tuple deformation**: `COUNT(*)` doesn't need to extract column values from tuples |
| 132 | +2. **Fewer NULL checks**: No need to check individual column values |
| 133 | +3. **Better cache utilization**: Less data movement means better CPU cache usage |
| 134 | + |
| 135 | +For tables with many columns, the performance gain can be even more substantial, as `COUNT(column)` might require deforming many columns to reach the target column. |
| 136 | + |
| 137 | +## Edge Cases and Limitations |
| 138 | + |
| 139 | +The optimization only applies when: |
| 140 | + |
| 141 | +1. The column is provably non-nullable (NOT NULL constraint or constant) |
| 142 | +2. There are no `ORDER BY` clauses in the aggregate |
| 143 | +3. There are no `DISTINCT` clauses in the aggregate |
| 144 | + |
| 145 | +Cases that are **not** optimized (yet): |
| 146 | + |
| 147 | +- `COUNT(nullable_col)` where the column might be NULL (even if filtered by `WHERE nullable_col IS NOT NULL` in the same query) |
| 148 | +- `COUNT(col ORDER BY col)` - the ORDER BY prevents optimization |
| 149 | +- `COUNT(DISTINCT col)` - DISTINCT prevents optimization |
| 150 | + |
| 151 | +The limitation with `WHERE` clauses is due to the timing of the optimization (during constant folding, before relation information is fully available). |
| 152 | + |
| 153 | +## Current Status |
| 154 | + |
| 155 | +The patch was **committed** by David Rowley on November 26, 2025. It's available in PostgreSQL master branch and will be included in PostgreSQL 18. |
| 156 | + |
| 157 | +## Conclusion |
| 158 | + |
| 159 | +This optimization represents a significant improvement to PostgreSQL's query planner, automatically fixing a common performance anti-pattern without requiring application changes. The new `SupportRequestSimplifyAggref` infrastructure also opens the door for future aggregate optimizations. |
| 160 | + |
| 161 | +For developers and DBAs: |
| 162 | +- **No action required**: The optimization happens automatically |
| 163 | +- **Performance benefit**: Existing queries using `COUNT(1)` or `COUNT(not_null_col)` will automatically get faster |
| 164 | +- **Best practice**: While the planner now optimizes these cases, `COUNT(*)` remains the clearest and most idiomatic way to count rows |
| 165 | + |
| 166 | +This change demonstrates PostgreSQL's commitment to improving query performance automatically, reducing the burden on developers to know every optimization detail while still allowing experts to write optimal queries when needed. |
| 167 | + |
| 168 | +## References |
| 169 | + |
| 170 | +- [Discussion Thread](https://www.postgresql.org/message-id/CAApHDvqGcPTagXpKfH=CrmHBqALpziThJEDs_MrPqjKVeDF9wA@mail.gmail.com) |
| 171 | +- Related: `SupportRequestSimplify` for regular function expressions |
0 commit comments