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: Use of HAVING outside of GROUP BY should raise a suitable SQLSyntaxError #19320

Merged
merged 1 commit into from
Oct 20, 2024
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
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")