Skip to content

Parser: Cannot parse COUNT(CASE WHEN x NOT NULL THEN 1 END) #1920

Closed

Description

@ryanschneider

I'm not sure if this is generally accepted SQL syntax but duckdb supports it:

> duckdb
DuckDB v1.3.0 (Ossivalis) 71c5c07cdd
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
> WITH t AS (SELECT NULL as x) SELECT COUNT(CASE WHEN x NOT NULL THEN 1 END) AS x FROM t;
┌───────┐
│   x   │
│ int64 │
├───────┤
│   0   │
└───────┘
>

However the parser rejects it:

#[test]
fn test_duckdb_case() {
    let real_sql = r#"WITH t AS (SELECT NULL as x) SELECT COUNT(CASE WHEN x NOT NULL THEN 1 END) AS x FROM t"#;
    assert_eq!(duckdb().verified_stmt(real_sql).to_string(), real_sql);
}

This fails w/ WITH t AS (SELECT NULL as x) SELECT COUNT(CASE WHEN x NOT NULL THEN 1 END) AS x FROM t: ParserError("Expected: ), found: WHEN")

I've tried stepping through myself and got as far as looking at parse_case_expr and it's failing here:

        llet mut conditions = vec![];
        loop {
            let condition = self.parse_expr()?;
            self.expect_keyword_is(Keyword::THEN)?;   <-- fails here
            let result = self.parse_expr()?;
            conditions.push(CaseWhen { condition, result });
            if !self.parse_keyword(Keyword::WHEN) {
                break;
            }
        }

At that point, condition is just the Expr x and conditions is still empty, it still needs to parse NOT NULL before expecting the THEN keyword, but I'm not sure what the fix is.

Activity

  1. ryanschneider commented on Jul 2, 2025

    @ryanschneider
    ContributorAuthor

    Ah, FWIW this passes:

    WITH t AS (SELECT NULL AS x) SELECT COUNT(CASE WHEN x = 1 THEN 1 END) AS x FROM t
    

    So the issue is specifically w/ the NOT NULL not being included in the expression. I'll dig deeper when I have a chance.

  2. ryanschneider commented on Jul 2, 2025

    @ryanschneider
    ContributorAuthor

    I did a bit more stepping through and I think I see the issue, it's in get_next_precedence_default, specifically in the Keyword::NOT arm:

    Token::Word(w) if w.keyword == Keyword::NOT => match parser.peek_nth_token(1).token {
                    // The precedence of NOT varies depending on keyword that
                    // follows it. If it is followed by IN, BETWEEN, or LIKE,
                    // it takes on the precedence of those tokens. Otherwise, it
                    // is not an infix operator, and therefore has zero
                    // precedence.
                    Token::Word(w) if w.keyword == Keyword::IN => Ok(p!(Between)),
                    Token::Word(w) if w.keyword == Keyword::BETWEEN => Ok(p!(Between)),
                    Token::Word(w) if w.keyword == Keyword::LIKE => Ok(p!(Like)),
                    Token::Word(w) if w.keyword == Keyword::ILIKE => Ok(p!(Like)),
                    Token::Word(w) if w.keyword == Keyword::RLIKE => Ok(p!(Like)),
                    Token::Word(w) if w.keyword == Keyword::REGEXP => Ok(p!(Like)),
                    Token::Word(w) if w.keyword == Keyword::MATCH => Ok(p!(Like)),
                    Token::Word(w) if w.keyword == Keyword::SIMILAR => Ok(p!(Like)),
                    _ => Ok(self.prec_unknown()),
                },
    

    I think this is missing a case for Keyword::NULL but I need to do some more research to confirm that.

    To confirm, I see that x IS NULL parses ok:

    WITH t AS (SELECT NULL AS x) SELECT COUNT(CASE WHEN x IS NULL THEN 0 ELSE 1 END) AS x FROM t

    So I need to see if x NOT NULL is a duckdb-ism or a more generally accepted expression.

  3. ryanschneider commented on Jul 2, 2025

    @ryanschneider
    ContributorAuthor

    I did some research and x NOT NULL isn't universally supported, but is supported by both DuckDB and SQLite. Additionally DuckDB, SQLite, and Postgres support x NOTNULL.

  4. ryanschneider commented on Jul 2, 2025

    @ryanschneider
    ContributorAuthor

    I think the way forward is to add supports_notnull_expr and supports_not_null_expr methods to the Dialect trait, both defaulting to false but overridden to true for the above dialects, and then inspect that in the parse_expr. I'm not a huge fan of the two methods being so similarly named, happy to consider alternative names.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions