Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: SQL ELSE clause should be implicitly NULL when omitted #19714

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading