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

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
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
  • 2
    for next generation :)
    – FLICKER
    Apr 9, 2016 at 4:45
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
  • 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, ...)
    – tomvo
    Jul 26, 2022 at 7:32
-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
  • i believe, this is used, when you want to fill the null column to zero :/
    – Ravi
    Jan 1, 2013 at 16:53
  • but, OP just need to show the related information, whose column holds NULL value, nevertheless, good effort. :)
    – Ravi
    Jan 1, 2013 at 16:55

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.