views:

381

answers:

4

I've wrote a query to check for users with certain criteria, one being they have an email address.

Our site will allow a user to have or not have an email address.

$aUsers=$this->readToArray('
 SELECT `userID` 
 FROM `users` 
 WHERE `userID` 
 IN(SELECT `userID`
         FROM `users_indvSettings`
  WHERE `indvSettingID`=5 AND `optionID`='.$time.')
  AND `email`!=""
 ');

Is this the best way to check for an empty field in SQL? I've just tried "IS NOT NULL" and this still returned a users record without them having an email address.

The query above works but out of curiosity I wondered if I'm doing it the correct way.

+2  A: 

Yes, what you are doing is correct. You are checking to make sure the email field is not an empty string. NULL means the data is missing. An empty string "" is a blank string with length of 0.

You can add the null check also

AND (email != "" OR email IS NOT NULL)
Yada
Your expression will match the empty strings as well. `OR email IS NOT NULL` is redundant here (it is implied by the previous condition).
Quassnoi
Interesting, this still returns records that have an empty `email` field.
The OR should be an AND here. "OR email IS NOT NULL" will match a blank email string with length of 0.
pdavis
A: 

An empty field can be either an empty string or a NULL.

To handle both, use:

email > ''

which can benefit from the range access if you have lots of empty email record (both types) in your table.

Quassnoi
+1  A: 

There's a difference between an empty string (email != "") and NULL. NULL is null and an Empty string is something.

Leslie
Which is why AND (email != "" OR email IS NOT NULL) is failing?
should be `AND (email != '' AND email IS NOT NULL)`
thetaiko
@thetaiko: `email IS NOT NULL` is redundant here. `!=` predicate will never match a `NULL` value.
Quassnoi
what if you try:AND (trim(email) != '')
Leslie
@Quassnoi - you're right
thetaiko
A: 

This will work but there is still the possibility of a null record being returned. Though you may be setting the email address to a string of length zero when you insert the record, you may still want to handle the case of a NULL email address getting into the system somehow.

     $aUsers=$this->readToArray('
     SELECT `userID` 
     FROM `users` 
     WHERE `userID` 
     IN(SELECT `userID`
               FROM `users_indvSettings`
               WHERE `indvSettingID`=5 AND `optionID`='.$time.')
     AND `email` != "" AND `email` IS NOT NULL
     ');
pdavis
@op's query leaves no possibility of the `NULL` record returned.
Quassnoi