8

How can I select any row that contains empty or null column?

I'm trying to run a check on my table, in which I want to see if any of my rows contain a column that doesn't hold a value..

example table: demo

+----+------+------+
| ID | col1 | col2 |
+----+------+------+
| 1  | VAL1 | Val2 |
| 2  | NULL | Val2 |
| 3  | VAL1 | NULL |
+----+------+------+

I want the query to return rows 2-3 , noting that I have many columns in actual table so I don't want to include it in the query with 'where or'.

can it be done with mysql?

3
  • do you want to avoid the first record and fetch other records? Commented Jan 1, 2013 at 16:47
  • i want to fetch all rows that contain a null column, even if i dont know the columns name :) Commented Jan 1, 2013 at 19:53
  • stackoverflow.com/a/20161429/1031945 Commented May 6, 2015 at 9:38

4 Answers 4

9
select * from tablename where col1 is NULL or col2 is NULL

Result

 ID | col1  | col2
 ------------------     
 2  | NULL  | Val2     
 3  | VAL1  | NULL
Sign up to request clarification or add additional context in comments.

Comments

5

the best answer that does not need to hard-code the column names is:

DECLARE @sqlStr VARCHAR(max) = (
        SELECT stuff((
                    SELECT 'and ' + c.NAME + ' is null '
                    FROM sys.columns c
                    WHERE object_name(object_id) = 'yourtablename'
                    ORDER BY c.NAME
                    FOR XML PATH('')
                    ), 1, 3, '')
        )

SET @sqlStr = 'select * from ' + yourtablename + ' where ' + @sqlStr

PRINT @sqlStr

EXEC (@sqlStr)

1 Comment

for next generation :)
5

If you really want not to use ORs, you could use this:

SELECT *
FROM demo
WHERE concat(col1, col2, ...) is Null

or this:

SELECT *
FROM demo
WHERE col1+col2+... is null

but while it's makes the query easier to write, it won't make it faster. I would suggest you just to use ORs.

1 Comment

This will return NULL if there is one column that is NULL. If you want to check if all columns in your list are empty use CONCAT_WS("", col1, col2, ...)
-2
SELECT 
    IFNULL(col1,0),
    IFNULL(col2,0)
FROM mytable
WHERE col1 IS NULL or col2 IS NULL

You can use IFNULL to set default value

2 Comments

i believe, this is used, when you want to fill the null column to zero :/
but, OP just need to show the related information, whose column holds NULL value, nevertheless, good effort. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.