I need to check whether a column is NOT NULL in my SQL statement.
My SQL query:
select column_a, column_b, column_c, column_d, column_x
from myTable
I’ve a lot of columns in my select. So I’ve got a performance issue, If I would do the following:
select column_a, column_b, column_c, column_d, column_x
from myTable
where column_a is not null or column_b is not null or column_c is not null
or column_x is not null
Is there another (better) way to check if there are any columns that are NOT NULL?
You can use
COALESCEfor this.COALESCEreturns the first non-null value, if any. This will likely not perform any better, but is much more readable.Example:
Depending on the cardinality of your data, you may be able to add indexes to help performance.
Another possibility is to use persisted computed column that tells you whether all four columns are NULL or not.