Skip to content

Commit

Permalink
fix: SQL ELSE clause should be implicitly NULL when omitted (#19714)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-beedie authored Nov 11, 2024
1 parent e596fa7 commit 441c18e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion crates/polars-sql/src/sql_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -919,7 +919,7 @@ impl SQLExprVisitor<'_> {
}
let else_res = match else_result {
Some(else_res) => self.visit_expr(else_res)?,
None => polars_bail!(SQLSyntax: "ELSE expression is required"),
None => lit(Null), // ELSE clause is optional; when omitted, it is implicitly NULL
};
if let Some(operand_expr) = operand {
let first_operand_expr = self.visit_expr(operand_expr)?;
Expand Down
18 changes: 18 additions & 0 deletions py-polars/tests/unit/sql/test_conditional.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,24 @@ def test_case_when() -> None:
}


@pytest.mark.parametrize("else_clause", ["ELSE NULL ", ""])
def test_case_when_optional_else(else_clause: str) -> None:
df = pl.DataFrame(
{
"a": [1, 2, 3, 4, 5, 6, 7],
"b": [7, 6, 5, 4, 3, 2, 1],
"c": [3, 4, 0, 3, 4, 1, 1],
}
)
query = f"""
SELECT
AVG(CASE WHEN a <= b THEN c {else_clause}END) AS conditional_mean
FROM self
"""
res = df.sql(query)
assert res.to_dict(as_series=False) == {"conditional_mean": [2.5]}


def test_control_flow(foods_ipc_path: Path) -> None:
nums = pl.LazyFrame(
{
Expand Down

0 comments on commit 441c18e

Please sign in to comment.