@@ -31,7 +31,7 @@ use datafusion_common::config::ConfigOptions;
3131use datafusion_common:: tree_node:: { Transformed , TreeNode , TreeNodeRewriter } ;
3232use datafusion_common:: {
3333 Column , DFSchema , DFSchemaRef , DataFusionError , Result , ScalarValue , TableReference ,
34- exec_err, internal_datafusion_err , internal_err, not_impl_err, plan_datafusion_err,
34+ exec_err, internal_err, not_impl_err, plan_datafusion_err,
3535 plan_err,
3636} ;
3737use datafusion_expr:: expr:: {
@@ -662,31 +662,40 @@ impl TreeNodeRewriter for TypeCoercionRewriter<'_> {
662662 high,
663663 } ) => {
664664 let expr_type = expr. get_type ( self . schema ) ?;
665- // Cast string literal bounds to the expression's numeric type
665+ let low_type = low. get_type ( self . schema ) ?;
666+ // Try casting string literals to the other side's numeric
667+ // type in both directions, mirroring BinaryExpr behavior.
668+ // This handles both `int_col BETWEEN '1' AND '10'` and
669+ // `'5' BETWEEN 1 AND 10`.
666670 let low = try_cast_string_literal_to_type ( & low, & expr_type) ?
667671 . map ( Box :: new)
668672 . unwrap_or ( low) ;
669673 let high = try_cast_string_literal_to_type ( & high, & expr_type) ?
670674 . map ( Box :: new)
671675 . unwrap_or ( high) ;
676+ let expr =
677+ try_cast_string_literal_to_type ( & expr, & low_type) ?
678+ . map ( Box :: new)
679+ . unwrap_or ( expr) ;
680+ let expr_type = expr. get_type ( self . schema ) ?;
672681 let low_type = low. get_type ( self . schema ) ?;
673682 let low_coerced_type = comparison_coercion ( & expr_type, & low_type)
674683 . ok_or_else ( || {
675- internal_datafusion_err ! (
684+ plan_datafusion_err ! (
676685 "Failed to coerce types {expr_type} and {low_type} in BETWEEN expression"
677686 )
678687 } ) ?;
679688 let high_type = high. get_type ( self . schema ) ?;
680689 let high_coerced_type = comparison_coercion ( & expr_type, & high_type)
681690 . ok_or_else ( || {
682- internal_datafusion_err ! (
691+ plan_datafusion_err ! (
683692 "Failed to coerce types {expr_type} and {high_type} in BETWEEN expression"
684693 )
685694 } ) ?;
686695 let coercion_type =
687696 comparison_coercion ( & low_coerced_type, & high_coerced_type)
688697 . ok_or_else ( || {
689- internal_datafusion_err ! (
698+ plan_datafusion_err ! (
690699 "Failed to coerce types {expr_type} and {high_type} in BETWEEN expression"
691700 )
692701 } ) ?;
0 commit comments