Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL SELECT where boolean field is NULL or false

OK I must be missing something really simple here. I just want to return all records from a table where the user_id matches (easy!) and the 'paid' field is either NULL or 0. My 'paid' field is a TinyInt (1).

My CakePHP model code is:

$workingRecord = $this->find('first',array(
    'conditions'=>array(
        'Subscription.user_id'=>$userId,
        array('not' => array('Subscription.paid' => true)) // Not True, to catch both false or NULL values
    )
));

The SQL generated by CakePHP is like this:

SELECT `Subscription`.`id`, `Subscription`.`paid` FROM `subscriptions` AS `Subscription` WHERE `Subscription`.`user_id` = 3 AND NOT (`Subscription`.`paid` = '1') LIMIT 1

Common sense would say this should work. The problem is that that SQL will return rows containing 0 in the 'paid' column, but will never return NULLs.

Is there any way to return zero's and NULLs in the one stroke, without using 'or'?

Thanks in advance.

like image 956
joshua.paling Avatar asked Nov 12 '12 06:11

joshua.paling


People also ask

Can boolean be NULL MySQL?

A NULL boolean has three possible values: true , false , and null . A NOT NULL boolean has only two, true and false . Your application logic will have to suffice for telling you which is the correct choice.

IS NULL boolean false SQL?

BOOLEAN can have TRUE or FALSE values. BOOLEAN can also have an “unknown” value, which is represented by NULL. Boolean columns can be used in expressions (e.g. SELECT list), as well as predicates (e.g. WHERE clause).

Is NULL in MySQL in WHERE clause?

To test for NULL in a query, you use the IS NULL or IS NOT NULL operator in the WHERE clause. You can use the IS NOT operator to get all leads who provided the email addresses. Even though the NULL is not equal to NULL , two NULL values are equal in the GROUP BY clause.

Is NULL in SELECT MySQL?

Let's look at an example of how to use MySQL IS NULL in a SELECT statement: SELECT * FROM contacts WHERE last_name IS NULL; This MySQL IS NULL example will return all records from the contacts table where the last_name contains a NULL value.


1 Answers

When you left join a table with a boolean field, the result set may contain a NULL value even though the joined table's schema does not permit it.

So as a general case I would suggest:

where `Subscription`.`paid` = 0 or `Subscription`.`paid` IS NULL
like image 100
Steven Spungin Avatar answered Oct 03 '22 18:10

Steven Spungin