Simplify COALESCE() with one surviving argument.
authorTom Lane <tgl@sss.pgh.pa.us>
Thu, 3 Jul 2025 21:39:53 +0000 (17:39 -0400)
committerTom Lane <tgl@sss.pgh.pa.us>
Thu, 3 Jul 2025 21:39:53 +0000 (17:39 -0400)
commit931766aaec58b2ce09c82203456877e0b05e1271
treed07c8d32603eb4101650b0f3bfcef287d5e49bd3
parentfc896821c4448038c5cc678c1aff7349ee850b23
Simplify COALESCE() with one surviving argument.

If, after removal of useless null-constant arguments, a CoalesceExpr
has exactly one remaining argument, we can just take that argument as
the result, without bothering to wrap a new CoalesceExpr around it.
This isn't likely to produce any great improvement in runtime per se,
but it can lead to better plans since the planner no longer has to
treat the expression as non-strict.

However, there were a few regression test cases that intentionally
wrote COALESCE(x) as a shorthand way of creating a non-strict
subexpression.  To avoid ruining the intent of those tests, write
COALESCE(x,x) instead.  (If anyone ever proposes de-duplicating
COALESCE arguments, we'll need another iteration of this arms race.
But it seems pretty unlikely that such an optimization would be
worthwhile.)

Author: Maksim Milyutin <maksim.milyutin@tantorlabs.ru>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/8e8573c3-1411-448d-877e-53258b7b2be0@tantorlabs.ru
src/backend/optimizer/util/clauses.c
src/test/regress/expected/join.out
src/test/regress/expected/subselect.out
src/test/regress/sql/join.sql
src/test/regress/sql/subselect.sql