358

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 ...)
3
  • 1
    MySQL code: select isnull(mycolumn) from mytable returns 1 if mycolumn is null. Sep 15, 2014 at 13:39
  • 2
    what about length(trim(mycolumn)) > 0 ? Oct 14, 2015 at 17:12
  • For MSSQL > WHERE COLUMN <> '' OR WHERE LEN(COLUMN) > 0 OR WHERE NULLIF(LTRIM(RTRIM(COLUMN)), '') IS NOT NULL
    – DxTx
    Apr 23, 2018 at 17:52

22 Answers 22

542

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

SELECT * FROM table WHERE some_col IS NULL OR some_col = '';
2
  • 9
    If you change the condition to WHERE some_col IS NULL OR some_col = ' ' (one space inserted in the string) then it works on both MySQL and Oracle, see answer of "onedaywhen". some_col = '' doesn't work on Oracle as empty strings mean NULL there.
    – Johanna
    May 18, 2015 at 14:07
  • 2
    @Johanna but if you switch to ' ', then it won't work in SQLite. It only handles identical/direct string matching.
    – Magne
    Oct 3, 2017 at 12:02
159

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;
3
  • 9
    Thanks for mentionning the padded spaces. You can profit of them and change the condition to WHERE some_col IS NULL OR some_col = ' ' (one space inserted in the string) then it works on both MySQL and Oracle. some_col = '' doesn't work on Oracle as empty strings mean NULL there and the complete condition becomes NULL.
    – Johanna
    May 18, 2015 at 14:09
  • My requirement was to find SELECT * FROM T WHERE some_col IS NOT NULL OR same_col <> ' '; and SELECT * FROM T WHERE NULLIF(some_col, ' ') IS NOT NULL; worked for me in MySQL. Hope this will be useful. Mar 9, 2017 at 9:49
  • Actually '' = ' ' works in SQLServer but not in SQLite, as far as I can tell, from testing it now.
    – Magne
    Oct 3, 2017 at 9:59
95

A shorter way to write the condition:

WHERE some_col > ''

Since null > '' produces unknown, this has the effect of filtering out both null and empty strings.

6
  • 4
    Is there a way of getting the reverse of this, getting all the records where it is NULL or an empty string? Aug 11, 2014 at 15:50
  • 18
    @JoshPinter: coalesce(some_col, '') = ''
    – Andomar
    Aug 12, 2014 at 4:46
  • 6
    This may have been true sometime, but doesn't work in MySQL 14.14. Jul 18, 2016 at 20:27
  • 1
    works great and is in fact the only way I could figure out how to filter out both null and empty fields in MariaDB
    – Neal Davis
    Dec 13, 2018 at 22:14
  • 3
    I use some_col <> '' to find the reverse of this
    – Chargnn
    Jul 11, 2019 at 15:39
40

Please mind: the best practice it at the end of the answer.


You can test whether a column is null or is not null using WHERE col IS NULL or WHERE col IS NOT NULL e.g.

SELECT myCol 
FROM MyTable 
WHERE MyCol IS NULL 

In your example you have various permutations of white space. You can strip white space using TRIM and you can use COALESCE to default a NULL value (COALESCE will return the first non-null value from the values you suppy.

e.g.

SELECT myCol
FROM MyTable
WHERE TRIM(COALESCE(MyCol, '')) = '' 

This final query will return rows where MyCol is null or is any length of whitespace.

If you can avoid it, it's better not to have a function on a column in the WHERE clause as it makes it difficult to use an index. If you simply want to check if a column is null or empty, you may be better off doing this:

SELECT myCol
FROM MyTable
WHERE MyCol IS NULL OR MyCol =  '' 

See TRIM COALESCE and IS NULL for more info.

Also Working with null values from the MySQL docs

2
  • 6
    You present the real solution in a very convoluted way. First you present an incomplete solution to his problem "where mycol is null". Then you present a solution using two nested functions in the where clause, even while saying this should be avoided. Only then do you get to the real solution. In the future, present your real solution first.
    – user4843530
    Sep 22, 2015 at 15:41
  • What if I want to check if any of the column has a blank value. Let's say my table has 50 columns. Now check for each column one by one is time taking. Sep 9, 2022 at 8:06
20

Another method without WHERE, try this..

Will select both Empty and NULL values

SELECT ISNULL(NULLIF(fieldname,''))  FROM tablename
2
  • this returns 1 if there is something null, why is that so?
    – noobie-php
    Mar 17, 2016 at 11:01
  • the NULLIF checks fieldname for the empty value and would convert to NULL if it was empty. The ISNULL returns 1 (true) if the NULLIF succesfully changed an empty field to NULL or if it was already NULL.... try for your self on a null and empty field in a table with the two functions seperated select isnull (X) , select nullif(y)
    – PodTech.io
    Mar 18, 2016 at 15:50
11

Either

SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1 from tablename

or

SELECT case when field1 IS NULL or field1 = ''
        then 'empty'
        else field1
   end as field1 from tablename
8

This statement is much cleaner and more readable for me:

select * from my_table where ISNULL(NULLIF(some_col, ''));
6

try

SELECT 0 IS NULL ,  '' IS NULL , NULL IS NULL

-> 0, 0, 1

or

SELECT ISNULL('  ') , ISNULL( NULL )
 -> 0 ,1

Reference

6

I hate messy fields in my databases. If the column might be a blank string or null, I'd rather fix this before doing the select each time, like this:

UPDATE MyTable SET MyColumn=NULL WHERE MyColumn='';
SELECT * FROM MyTable WHERE MyColumn IS NULL

This keeps the data tidy, as long as you don't specifically need to differentiate between NULL and empty for some reason.

1
  • 1
    That's interesting as a one-time fix. Or an occasional maintenance operation. But it wouldn't be practical while a database was in active use - UPDATE has to LOCK the table (for consistency). That would degrage PERFORMANCE if anyone else needs to access the same table. And then there is no guarantee that someone else wouldn't create a record that had a blank in it immediately after UPDATE finishes. This is a slippery slope. Aug 31, 2020 at 21:42
5

While checking null or Empty value for a column in my project, I noticed that there are some support concern in various Databases.

Every Database doesn't support TRIM method.

Below is the matrix just to understand the supported methods by different databases.

The TRIM function in SQL is used to remove specified prefix or suffix from a string. The most common pattern being removed is white spaces. This function is called differently in different databases:

  • MySQL: TRIM(), RTRIM(), LTRIM()
  • Oracle: RTRIM(), LTRIM()
  • SQL Server: RTRIM(), LTRIM()

How to Check Empty/Null :-

Below are two different ways according to different Databases-

The syntax for these trim functions are:

  1. Use of Trim to check-

    SELECT FirstName FROM UserDetails WHERE TRIM(LastName) IS NULL

  2. Use of LTRIM & RTRIM to check-

    SELECT FirstName FROM UserDetails WHERE LTRIM(RTRIM(LastName)) IS NULL

Above both ways provide same result just use based on your DataBase support. It Just returns the FirstName from UserDetails table if it has an empty LastName

Hoping this will help you :)

4
SELECT * FROM tbl WHERE trim(IFNULL(col,'')) <> '';
3
  • I had an issue comparing to a field that was sometimes null. This helped: col1 != IFNULL(col2,'')
    – webaholik
    Sep 3, 2019 at 4:45
  • FWIW: Its impossible for a string to be less than an empty string, so instead of <> can use >. Aug 31, 2020 at 21:55
  • I found that using TRIM uses more resources (takes more time) than just <> '' etc. Not using it if not necessary though it's working, of course.
    – davidman77
    Oct 8, 2021 at 3:47
4

My two cents.

In MySQL you can use the COALESCE function:

Returns the first non-NULL value in the list, or NULL if there are no non-NULL values.

So you can simplify your query like this:

SELECT * FROM table WHERE COALESCE(some_col, '') = '';
3

If you want to have NULL values presented last when doing an ORDER BY, try this:

SELECT * FROM my_table WHERE NULLIF(some_col, '') IS NULL;
0
3

You can also do

SELECT * FROM table WHERE column_name LIKE ''

The inverse being

SELECT * FROM table WHERE column_name NOT LIKE ''
2
  • 1
    Apparently does not work: select NULL like '' returns NULL - at least in MySQL.
    – Titus
    Jun 28, 2018 at 17:35
  • PERFORMANCE: Don't use LIKE for an expression that can be done without it. Aug 31, 2020 at 21:59
1
select * from table where length(RTRIM(LTRIM(column_name))) > 0
2
  • 4
    What's the point in using both RTRIM and LTRIM, but not TRIM?
    – Nico Haase
    Jan 25, 2019 at 15:11
  • I find it interesting, but not recommendable ;) - uses up too many resources/time.
    – davidman77
    Oct 8, 2021 at 3:49
0

The below SQL query works fine.

SELECT * FROM <table-name> WHERE <column-name> IS NULL;
1
  • This won't return rows where column-name contains a blank ("").
    – pbarney
    Dec 1, 2022 at 16:56
0

In my case, space was entered in the column during the data import and though it looked like an empty column its length was 1. So first of all I checked the length of the empty looking column using length(column) then based on this we can write search query

SELECT * FROM table WHERE LENGTH(column)=0;

3
  • 1
    Huh? I don't understand what that code snippet says. Are you trying to say LENGTH(column)=0? Aug 31, 2020 at 21:50
  • @ToolmakerSteve, did you know you have a high enough reputation to be able to edit answers to fix obvious spelling errors?
    – pbarney
    Dec 1, 2022 at 17:06
  • 2
    @pbarney - look at edit history, and see what the code looked like at the time I wrote my comment: SELECT * FROM TABLE WHERE LENGHT(COLUMN)= length of column for empty column. Then you'll see that Mr And edited the answer, in response to my comment. (If I had noticed he had edited answer, I would have removed my comment. This entire comment chain is now moot; I will ask moderator to remove it soon.) Dec 1, 2022 at 20:38
0

Below code works great, to check null or empty and fallback to other column:

SELECT COALESCE(NULLIF(col1, ''), col2) as 'someName'

Above sql means:

if `col1` column value is NOT null and NOT empty string  
then take `col1`
otherwise take `col2`  

return above value as `someName`
-1

Check for null

$column is null
isnull($column)

Check for empty

$column != ""

However, you should always set NOT NULL for column,
mysql optimization can handle only one IS NULL level

4
  • 4
    Never accepting NULL values is another whole topic for discussion. I don't think it's appropriate to make that recommendation without providing your reasoning.
    – maček
    Dec 12, 2011 at 6:56
  • I did include, be patient. Plus is really make life difficult using NULL (just like this question).
    – ajreal
    Dec 12, 2011 at 6:58
  • 6
    That's a terrible recommendation. Setting NOT NULL on a column whose value may not be known at the time of INSERT only serves to encourage the use of non-standard "null" values like -1 and ''. Feb 14, 2014 at 19:43
  • @Dan if you aren't sure what are the value during insertion, you may have difficulties to conduct any possilbe optimization
    – ajreal
    Feb 15, 2014 at 4:17
-1

try this if the datatype are string and row is null

SELECT * FROM table WHERE column_name IS NULL OR column_name = ''

if the datatype are int or column are 0 then try this

SELECT * FROM table WHERE column_name > = 0
-1

Get rows with NULL, 0, '', ' ', ' '

    SELECT * FROM table WHERE some_col IS NOT TRUE;

Get rows without NULL, 0, '', ' ', ' '

    SELECT * FROM table WHERE some_col IS TRUE;
1
  • I don't think this will work. SELECT 'abc' <> '', 'abc' IS TRUE; returns 1 and 0.
    – Max Ivanov
    May 19, 2021 at 23:16
-2
SELECT column_name FROM table_name WHERE column_name IN (NULL, '')
2
  • 2
    Wrong answer. This won't select NULL.
    – Pang
    Jun 7, 2017 at 3:36
  • To clarify @Pang's comment: Can't use NULL in an expression as if it were a value. You have to do special tests such as ... IS NULL or ISNULL(...) Notice that code examples never say column_name = NULL. It just doesn't work that way. Aug 31, 2020 at 21:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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