Simplify `CASE WHEN true <xx> ...`
Is your feature request related to a problem or challenge?
While reviewing https://github.com/apache/datafusion/pull/17357 I noticed that expressions like
CASE WHEN true THEN 1 ELSE x END
Could be simplified to
1
but were not
Here is a complete example:
> create table foo(x int) as values (1), (2), (3);
0 row(s) fetched.
Elapsed 0.004 seconds.
> explain format indent select CASE WHEN true THEN 1 ELSE x END from foo;
+---------------+----------------------------------------------------------------------------------------------------------------------------------+
| plan_type | plan |
+---------------+----------------------------------------------------------------------------------------------------------------------------------+
| logical_plan | Projection: CASE WHEN Boolean(true) THEN Int64(1) ELSE CAST(foo.x AS Int64) END |
| | TableScan: foo projection=[x] |
| physical_plan | ProjectionExec: expr=[CASE WHEN true THEN 1 ELSE CAST(x@0 AS Int64) END as CASE WHEN Boolean(true) THEN Int64(1) ELSE foo.x END] |
| | DataSourceExec: partitions=1, partition_sizes=[1] |
| | |
+---------------+----------------------------------------------------------------------------------------------------------------------------------+
2 row(s) fetched.
Elapsed 0.001 seconds.
I expect to see the case expression simplified
It does get the correct answer
> select CASE WHEN true THEN 1 ELSE x END from foo;
+------------------------------------------------------+
| CASE WHEN Boolean(true) THEN Int64(1) ELSE foo.x END |
+------------------------------------------------------+
| 1 |
| 1 |
| 1 |
+------------------------------------------------------+
3 row(s) fetched.
Elapsed 0.001 seconds.
Describe the solution you'd like
I would like expressions that can be simplified to
CASE
WHEN true THEN <expr>
...
Can be simplified to
<expr>
Describe alternatives you've considered
I think we can just extend the existing rules for CASE simplification here:
https://github.com/apache/datafusion/blob/ec4413e7d7b41c381c98eda909e5ab650be4c5e5/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs#L1398-L1400
Additional context
No response
take
Can the symmetric case:
CASE WHEN false THEN x ELSE 1 END
be similarly simplified to just 1?
Also, does this simplification change the returned type? How about:
CASE WHEN true THEN NULL ELSE 1 END
?
EDIT: type coercion happens before simplify_expressions, so the above gets correctly simplified to Projection: Int64(NULL)
Can the symmetric case:
Yes, that is a great call @geoffreyclaude -- I filed a ticket to track:
- https://github.com/apache/datafusion/issues/17590