I came accross a strange problem with a MySQL Query
x
SELECT COUNT(id) FROM members100SELECT COUNT(id) FROM members WHERE lastname = 'Smith'20SELECT COUNT(id) FROM members WHERE lastname <> 'Smith'0The problem is, that the last query (Members with lastname != ‘Smith’) returns 0.
If there are 100 members in total and 20 members named ‘Smith’, the number of member with other last names should be 80, shouldn’t it?
I tried different version using <>, !=, enclosing Smith with ' or ". The result when using LIKE and NOT LIKE instead is the same.
How is this possible? It seems that I am missing something quite obvious, but what…?
Advertisement
Answer
because others are null
try this :
SELECT COUNT(id) FROM members WHERE IFNULL(lastname ,'--')<> 'Smith'Example :
CREATE TABLE my_table SELECT 'ersin' name FROM dualunion allSELECT 'ersin' name FROM dualunion allSELECT 'ersin' name FROM dualunion allSELECT null name FROM dualunion allSELECT null name FROM dualunion allSELECT null name FROM dual;select script:
select count(*) from my_table where IFNULL(name ,'--') <> 'ersin' ;output:
count(*)3