Skip to content

Commit

Permalink
fix: Use of HAVING outside of GROUP BY should raise a suitable SQ…
Browse files Browse the repository at this point in the history
…LSyntaxError
  • Loading branch information
alexander-beedie committed Oct 19, 2024
1 parent 46edcd8 commit 228c7cf
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
5 changes: 5 additions & 0 deletions crates/polars-sql/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -709,6 +709,11 @@ impl SQLContext {
};

lf = if group_by_keys.is_empty() {
// The 'having' clause is only valid inside 'group by'
if select_stmt.having.is_some() {
polars_bail!(SQLSyntax: "HAVING clause not valid outside of GROUP BY; found:\n{:?}", select_stmt.having);
};

// Final/selected cols, accounting for 'SELECT *' modifiers
let mut retained_cols = Vec::with_capacity(projections.len());
let have_order_by = query.order_by.is_some();
Expand Down
6 changes: 6 additions & 0 deletions py-polars/tests/unit/sql/test_group_by.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,3 +238,9 @@ def test_group_by_errors() -> None:
match=r"'a' should participate in the GROUP BY clause or an aggregate function",
):
df.sql("SELECT a, SUM(b) FROM self GROUP BY b")

with pytest.raises(
SQLSyntaxError,
match=r"HAVING clause not valid outside of GROUP BY",
):
df.sql("SELECT a, COUNT(a) AS n FROM self HAVING n > 1")

0 comments on commit 228c7cf

Please sign in to comment.