Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a column is empty or null in MySQL?

Tags:

sql

mysql

I have a column in a table which might contain null or empty values. How do I check if a column is empty or null in the rows present in a table?

(e.g. null or '' or '  ' or '      ' and ...) 
like image 812
priya Avatar asked Dec 12 '11 06:12

priya


People also ask

How do I check if a column is empty?

The formula =COUNTA(A1:A100) will return the number of non-blank cells in the range A1:A100. So if this formula returns 0, the range A1:A100 is completely empty.

How do I find the NULL column in MySQL?

To search for column values that are NULL , you cannot use an expr = NULL test. The following statement returns no rows, because expr = NULL is never true for any expression: mysql> SELECT * FROM my_table WHERE phone = NULL; To look for NULL values, you must use the IS NULL test.

How do you check whether the column has data or not?

If you compare this to the "num_rows" value from all_tables (or dba_tables) you can easily determine if a column has all null values, or not. Or, you can simply compare the "num_nulls" value to the "num_distinct" value for different columns in a single table to determine if a column has all null values.


2 Answers

This will select all rows where some_col is NULL or '' (empty string)

SELECT * FROM table WHERE some_col IS NULL OR some_col = ''; 
like image 69
maček Avatar answered Oct 16 '22 00:10

maček


As defined by the SQL-92 Standard, when comparing two strings of differing widths, the narrower value is right-padded with spaces to make it is same width as the wider value. Therefore, all string values that consist entirely of spaces (including zero spaces) will be deemed to be equal e.g.

'' = ' ' IS TRUE '' = '  ' IS TRUE ' ' = '  ' IS TRUE '  ' = '      ' IS TRUE etc 

Therefore, this should work regardless of how many spaces make up the some_col value:

SELECT *    FROM T  WHERE some_col IS NULL         OR some_col = ' '; 

or more succinctly:

SELECT *    FROM T  WHERE NULLIF(some_col, ' ') IS NULL; 
like image 27
onedaywhen Avatar answered Oct 16 '22 00:10

onedaywhen