Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if any column is NOT NULL

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?

like image 647
bitsmuggler Avatar asked Jan 03 '12 16:01

bitsmuggler


People also ask

How do you check if a column is not null?

The IS NULL constraint can be used whenever the column is empty and the symbol ( ' ') is used when there is empty value. mysql> SELECT * FROM ColumnValueNullDemo WHERE ColumnName IS NULL OR ColumnName = ' '; After executing the above query, the output obtained is.

Where columns are not null?

By default, a column can hold NULL values. The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.

IS NOT NULL check in SQL?

The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

IS NULL in SQL for multiple columns?

SQL Server ISNULL() With Multi Column NamesNull values are the values with no data; that means the data is missing or unknown. In this article, initially we will understand the SQL Server IsNull function, then we will move towards extending the IsNull functionality using Coalesce function.


1 Answers

You can use COALESCE for this. COALESCE returns the first non-null value, if any. This will likely not perform any better, but is much more readable.

Example:

where coalesce(column_a, column_b, column_c, column_x) is not null 

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.

like image 108
D'Arcy Rittich Avatar answered Sep 28 '22 03:09

D'Arcy Rittich