Skip to content

Fix planning for CASE-filtered SUM with ELSE 0.#19063

Open
gianm wants to merge 1 commit intoapache:masterfrom
gianm:sql-fix-sum-case
Open

Fix planning for CASE-filtered SUM with ELSE 0.#19063
gianm wants to merge 1 commit intoapache:masterfrom
gianm:sql-fix-sum-case

Conversation

@gianm
Copy link
Contributor

@gianm gianm commented Feb 27, 2026

Fixes #17768.

Previously, when extendedFilteredSumRewrite: true (the default), the aggregator SUM(CASE WHEN COND THEN COL1 ELSE 0 END) would be planned into SUM(COL1) FILTER(WHERE COND). This creates a discrepancy in the situation where the underlying relation is nonempty but COND does not match any rows: SQL standard behavior is for the aggregator to return zero, but we returned NULL.

This patch fixes it by wrapping such aggregators in COALESCE(_, CASE WHEN COUNT(*) > 0 THEN 0 END).

Fixes apache#17768.

Previously, when "extendedFilteredSumRewrite: true" (the default), the
aggregator SUM(CASE WHEN COND THEN COL1 ELSE 0 END) would be planned
into SUM(COL1) FILTER(WHERE COND). This creates a discrepancy in the
situation where the underlying relation is nonempty but COND does not
match any rows: SQL standard behavior is for the aggregator to return
zero, but we returned NULL.

This patch fixes it by wrapping such aggregators in
COALESCE(_, CASE WHEN COUNT(*) > 0 THEN 0 END).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Null query result when using SQL CASE expression

1 participant