Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a quick way to check if ANY column is NULL?

I have a table with around 20 columns. Aside from typing out:

Where column1 is null OR column2 is null OR column3 is null etc...

Is there a quicker way to just check every column and see if any value is null and if so, return that record?

like image 543
The Vanilla Thrilla Avatar asked Mar 14 '12 15:03

The Vanilla Thrilla


People also ask

WHERE any column is not null SQL?

A NOT NULL constraint in SQL is used to prevent inserting NULL values into the specified column, considering it as a not accepted value for that column. This means that you should provide a valid SQL NOT NULL value to that column in the INSERT or UPDATE statements, as the column will always contain data.

Is NULL in column?

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.

Which clause is used to search for NULL values in any column?

The IS NULL condition is used in SQL to test for a NULL value.


2 Answers

No. There are ways to code it quicker, but there are no shortcuts like you imply. Taken from an answer I gave on dba.stackexchange:

DECLARE @tb NVARCHAR(255), @sql NVARCHAR(MAX);

SET @tb = N'dbo.[table]';

SET @sql = N'SELECT * FROM ' + @tb + ' WHERE 1 = 0';

SELECT @sql = @sql + N' OR ' + QUOTENAME(name) + ' IS NULL'
    FROM sys.columns 
    WHERE [object_id] = OBJECT_ID(@tb);

EXEC sp_executesql @sql;
like image 119
Aaron Bertrand Avatar answered Oct 24 '22 18:10

Aaron Bertrand


You can find the column names using something like this:

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = <table_name> 

Then, I would write a procedure using this, and that would loop through the entries in your table and the column names.

Source: http://codesnippets.joyent.com/posts/show/337

like image 29
tiktak Avatar answered Oct 24 '22 19:10

tiktak