Question

I am doing a select statement trying to look for data where the column inactive is not set to 1, but the result is always Empty Set. Why is this happening?

 mysql> select id, time, num, inactive from data limit 10;
+--------+------------+------+----------+
| id     | time       | num  | inactive |
+--------+------------+------+----------+
| 276975 | 1388024838 |   55 |     NULL |
| 276976 | 1388025072 |  138 |     NULL |
| 276977 | 1388025435 |  211 |     NULL |
| 276978 | 1388025841 |  240 |     NULL |
| 276979 | 1388026372 |  329 |     NULL |
| 276980 | 1388026515 |  119 |     NULL |
| 276981 | 1388027029 |   57 |     NULL |
| 276982 | 1388027117 |  314 |     NULL |
| 276983 | 1388027251 |   47 |     NULL |
| 276984 | 1388027340 |   68 |     NULL |
+--------+------------+------+----------+
10 rows in set (0.00 sec)

So I would expect this to work, but it doesn't:

mysql> select id from data where inactive != 1;
Empty set (0.01 sec)

Here's some more info:

mysql> describe data;
+-------------+---------------+------+-----+---------+-------+
| Field       | Type          | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+-------+
| id          | bigint(20)    | NO   |     | NULL    |       |
| time        | bigint(20)    | YES  |     | NULL    |       |
| num         | int(11)       | YES  |     | NULL    |       |
| inactive    | tinyint(1)    | YES  |     | NULL    |       |
+-------------+---------------+------+-----+---------+-------+
Était-ce utile?

La solution

NULL doesn't compare equal to anything. You'll need to accept nulls explicitly:

select id from data where inactive <>1 or inactive is null;

See Working with NULL for more information about NULL handling.

Autres conseils

This is because SQL uses three valued logic. inactive != 1 doesn't include NULL.

select id from data where inactive != 1 OR inactive IS NULL;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top