Find the count of EMPTY or NULL columns in a MySQL table

前端 未结 4 1991
慢半拍i
慢半拍i 2021-01-21 20:04

I have around 30 columns in a MySQL table. I want to calculate how many column fields for a particular row are empty. This table is for storing user information. I want to fin

4条回答
  •  长情又很酷
    2021-01-21 20:49

    You can compute it like this:

    SELECT SUM((`Name` = '') + (`Age` = 0) + (`Location` = '' OR `Location` IS NULL) + ...)
    

    You didn't specify what types of columns you have so I used different comparing methods to illustrate the point. As a general idea you should compare to see if a specific column value is equal to the default value for that field (i.e. field not specified by the user). Use = '' for strings, = 0 for numbers, IS NULL for columns that have default NULL etc. You could also combine checks for NULL and empty value if you want. It all depends on what you want to find out.

    Of course, as dnagirl pointed out in her answer, you should test for both empty and NULL values, but that really depends on how your columns are defined and also if you consider empty values to be filled or not. The point I was trying to make is that you can use SUM to add up boolean expression results.

    EDIT: Didn't notice that you wanted for each row. Just remove the SUM and you'll get it per row.

提交回复
热议问题