Skip to content

fix(unparser): empty projection fallback and preserve global aggregates - #27333

Open
dreverri wants to merge 2 commits into
apache:mainfrom
dreverri:unparser-empty-projection
Open

dreverri wants to merge 2 commits into
apache:mainfrom
dreverri:unparser-empty-projection

Conversation

@dreverri

@dreverri dreverri commented Nov 11, 2026 •

Copy link
Copy Markdown

Which issue does this PR close?

Rationale for this change

Unparsing the optimized plan of select count(*) from t where id > 10 produces SELECT count(1) AS "count(*)" FROM (SELECT FROM t WHERE (t.id > 10)), even for dialects whose supports_empty_select_list() is false. Engines that don't accept an empty select list, such as BigQuery ("SELECT list must not be empty"), reject the generated SQL.

optimize_projections prunes the filter column above the Filter, which leaves a Projection with no expressions. #19221 added the SELECT 1 fallback for empty projections, but only the TableScan path uses it.

What changes are included in this PR?

  • reconstruct_select_statement uses empty_projection_fallback() when the Projection has no expressions, as the TableScan path does. Dialects without empty select list support get SELECT 1 FROM ...; PostgreSQL output is unchanged.
  • When a Projection references no columns (empty or constant-only) and would absorb a global Aggregate, the aggregate is kept in a derived table. Otherwise the SQL loses the aggregate and returns one row per input row instead of one.

Are these changes tested?

Yes.

  • datafusion/core/tests/sql/unparser.rs: optimized_count_over_filter_empty_projection (default and BigQuery dialects) and unparse_projection_without_columns_over_global_aggregate (runs the SQL on 3-row and empty tables).
  • datafusion/sql/tests/cases/plan_to_sql.rs: snapshots for an empty Projection over a Filter (default, PostgreSQL, BigQuery), over a global aggregate (default, PostgreSQL), a constant projection over a global aggregate, and an empty projection over a grouped aggregate.

Are there any user-facing changes?

Generated SQL changes in two ways: an empty Projection unparses as SELECT 1 FROM ... for dialects without empty select list support, and a Projection without column references over a global aggregate now wraps the aggregate in a derived table. There are no public API changes.

🤖 Generated with Claude Code

A `Projection` with no expressions (as `optimize_projections` leaves
under `count(*)` when a filter column is not otherwise needed) was
unparsed as `SELECT FROM ...` regardless of
`Dialect::supports_empty_select_list`. Only the `TableScan` path
consulted the dialect, so e.g. BigQuery received

    SELECT COUNT(1) FROM (SELECT FROM `t` WHERE ...)

and rejected it with "SELECT list must not be empty".

`reconstruct_select_statement` now uses `empty_projection_fallback`
for an empty projection, the same as the table scan path: `SELECT 1`
for dialects without empty select lists, unchanged for PostgreSQL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added sql SQL Planner core Core DataFusion crate labels Nov 11, 2026

@vinycalves vinycalves left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One logic question; no code suggestions.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does SELECT 1 preserve the meaning of a zero-column projection outside count(*), such as EXISTS or a UNION with zero columns?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The optimize_projections step should only produce an empty Projection when it can prove that the parent node needs only the row count of its input, not any column values. In the PR's example, select count(*) from t where id > 10, the aggregate count(Int64(1)) reads no columns. The filter below it still needs id, so the optimizer keeps id for the filter and inserts an empty Projection above it:

Projection: count(Int64(1)) AS count(*)
  Aggregate: groupBy=[[]], aggr=[[count(Int64(1))]]
    Projection:                          <-- empty
      Filter: t.id > Int32(10)
        TableScan: t projection=[id]

Because the parent was planned against a zero-column input, nothing above the empty Projection can reference a column, including the 1 the unparser adds. SELECT 1 FROM ... returns the same rows as SELECT FROM ..., so the result is unchanged.

To check the cases you mentioned, I ran zero-column queries in DataFusion and PostgreSQL 17, and ran the default-dialect unparser output for the same plans, which is the same query with SELECT FROM replaced by SELECT 1, back through DataFusion. t has id values 1, 5, 11, 12, 20.

Query (zero-column form) DataFusion PostgreSQL DataFusion, unparsed (SELECT 1)
SELECT t.id FROM t WHERE EXISTS (SELECT FROM t WHERE t.id > 10) ORDER BY t.id 5 rows 5 rows 5 rows
SELECT t.id FROM t WHERE EXISTS (SELECT FROM t WHERE t.id > 100) ORDER BY t.id 0 rows 0 rows 0 rows
SELECT t.id FROM t WHERE NOT EXISTS (SELECT FROM t WHERE t.id > 10) ORDER BY t.id 0 rows 0 rows 0 rows
SELECT count(1) AS n FROM (SELECT FROM t WHERE t.id > 10 UNION ALL SELECT FROM t WHERE t.id < 6) s n = 5 n = 5 n = 5
SELECT count(1) AS n FROM (SELECT FROM t WHERE t.id > 10 UNION SELECT FROM t WHERE t.id < 6) s n = 1 n = 1 n = 1
SELECT count(1) AS n FROM (SELECT FROM t WHERE t.id > 100 UNION SELECT FROM t WHERE t.id > 100) s n = 0 n = 0 n = 0

The one visible difference is when the empty projection is the root of the plan, e.g. a user explicitly asks for zero columns. Then the SQL returns one constant column instead of zero. That's the same trade-off TableScan has had since #19221, and it only applies to dialects with supports_empty_select_list() == false, where SELECT FROM isn't valid anyway. PostgreSQL still gets SELECT FROM.

This PR also fixes a union case. Before it, an empty TableScan input and an empty Projection input unparsed as SELECT 1 FROM t UNION ALL SELECT FROM t WHERE ..., which fails with UNION queries have different number of columns. Both inputs now use the same fallback.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Following up: a review found that the global aggregate case did change cardinality; that's fixed in 95a69c2.

@dreverri
dreverri requested a review from vinycalves November 16, 2026 22:38

@kosiew kosiew left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dreverri,

Thanks for the fix. Reusing the existing dialect-aware fallback is appropriate, and the regression tests cover the reported issue well.

However, the fallback can turn a pre-existing unparsing defect into executable SQL that silently returns incorrect results. Please address this cardinality issue before merging.

Comment thread datafusion/sql/src/unparser/plan.rs Outdated
// same fallback as an empty table scan projection, so dialects
// that reject `SELECT FROM` receive `SELECT 1 FROM`.
let mut exprs = if p.expr.is_empty() {
self.empty_projection_fallback()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An empty projection above a global aggregate can now produce executable SQL that silently loses the aggregate. Preserve the inner aggregate in a derived query or reject this shape explicitly, with regression coverage for empty and multi-row inputs.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks. Confirmed: Projection: [] over Aggregate: groupBy=[[]], aggr=[[count(1)]] unparsed as SELECT 1 FROM t, which returns one row per input row (3 for a 3-row table, 0 for an empty one) instead of 1. PostgreSQL already had this with SELECT FROM t; the fallback made it executable everywhere.

Fixed in 95a69c2. When none of a Projection's expressions reference a column and the SELECT would absorb a global aggregate, the aggregate now stays in a derived table: SELECT 1 FROM (SELECT count(1) FROM t). The condition also covers constant-only projections like Projection: 1, which hit the same problem. Grouped aggregates are unaffected, since GROUP BY already keeps the cardinality.

Tests: unparse_projection_without_columns_over_global_aggregate runs the unparsed SQL against a 3-row and an empty table, with empty and constant projections, and checks for exactly one row. plan_to_sql.rs has snapshots for the default and PostgreSQL dialects, the constant case, and a grouped-aggregate case to check it doesn't over-apply.

These shapes don't seem reachable from SQL through DataFusion's optimizer, which folds them to EmptyRelation: rows=1, so the tests build the plans directly.

.sql("select count(*) from t where id > 10")
.await?
.into_optimized_plan()?;
let sql = plan_to_sql(&plan)?.to_string();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: Could we also unparse this optimized plan using BigQueryDialect to cover the complete nested query reported in #27332?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 95a69c2: optimized_count_over_filter_empty_projection now also unparses the optimized plan with BigQueryDialect, which gives SELECT count(1) AS `count_40_42_41` FROM (SELECT 1 FROM `t` WHERE (`t`.`id` > 10)). The alias is BigQuery's usual escaping of count(*).

A Projection whose expressions reference no columns, such as the empty
projection the fallback now emits as `SELECT 1`, was absorbed into the
SELECT of a global Aggregate below it. Nothing in that SELECT referenced
the aggregate and there was no GROUP BY, so the SQL returned one row per
input row instead of exactly one. Keep the aggregate in a derived table
in that case.

Also unparse the optimized plan from apache#27332 with BigQueryDialect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@dreverri dreverri changed the title fix(unparser): apply empty projection fallback to Projection nodes fix(unparser): empty projection fallback and preserve global aggregates Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Core DataFusion crate sql SQL Planner

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unparser emits empty SELECT list for empty Projection nodes, ignoring supports_empty_select_list

3 participants