sqlnullpresto

SQL Query include row when at least one of three fields is not null


I would like to include a record in my query when, from a certain three fields, at least one of the three is not null.

I'm probably overthinking this, as there are other "AND" clauses that need to be present.

Do I just need to use parentheses? This is a Presto query.


Solution

  • The most straightforward way would be to test all three columns directly with an or operator between them. As you noticed, you should surround the entire condition with parentheses to avoid bugs related to the fact that the and logical operator in other conditions has a higher precedence:

    (col1 IS NOT NULL OR col2 IS NOT NULL OR col3 IS NOT NULL)
    

    A more elegant solution, however, could be to coalesce all three columns and check the result:

    COALESCE(col1, col2, col3) IS NOT NULL