Skip to content

Commit

Permalink
Optimize MIN/MAX when relation is empty
Browse files Browse the repository at this point in the history
  • Loading branch information
viirya committed Jan 21, 2024
1 parent f5a97d5 commit 8b2839a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
22 changes: 22 additions & 0 deletions datafusion/core/src/physical_optimizer/aggregate_statistics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,17 @@ fn take_optimizable_min(
}
}
}
} else if *num_rows == 0 {
// MIN/MAX with 0 rows is always null
if let Some(casted_expr) =
agg_expr.as_any().downcast_ref::<expressions::Min>()
{
if let Ok(min_data_type) =
ScalarValue::try_from(casted_expr.field().unwrap().data_type())
{
return Some((min_data_type, casted_expr.name().to_string()));
}
}
}
}
None
Expand Down Expand Up @@ -257,6 +268,17 @@ fn take_optimizable_max(
}
}
}
} else if *num_rows == 0 {
// MIN/MAX with 0 rows is always null
if let Some(casted_expr) =
agg_expr.as_any().downcast_ref::<expressions::Max>()
{
if let Ok(max_data_type) =
ScalarValue::try_from(casted_expr.field().unwrap().data_type())
{
return Some((max_data_type, casted_expr.name().to_string()));
}
}
}
}
None
Expand Down
20 changes: 20 additions & 0 deletions datafusion/sqllogictest/test_files/aggregate.slt
Original file line number Diff line number Diff line change
Expand Up @@ -3276,6 +3276,26 @@ SELECT MAX(col0) FROM empty WHERE col0=1;
----
NULL

query TT
EXPLAIN SELECT MIN(col0) FROM empty;
----
logical_plan
Aggregate: groupBy=[[]], aggr=[[MIN(empty.col0)]]
--TableScan: empty projection=[col0]
physical_plan
ProjectionExec: expr=[NULL as MIN(empty.col0)]
--PlaceholderRowExec

query TT
EXPLAIN SELECT MAX(col0) FROM empty;
----
logical_plan
Aggregate: groupBy=[[]], aggr=[[MAX(empty.col0)]]
--TableScan: empty projection=[col0]
physical_plan
ProjectionExec: expr=[NULL as MAX(empty.col0)]
--PlaceholderRowExec

statement ok
DROP TABLE empty;

Expand Down

0 comments on commit 8b2839a

Please sign in to comment.