Search code examples
mysqlsqldatabasesql-like

SQL Select Statement not working with 'like' as expected


The following query works as expected and doesn't return data with 'c' flag:

SELECT * 
FROM  `func` 
WHERE  `next_act` < 1484870400
AND  `assigned_to` IS NULL
AND `type` like '%FTTC%'
AND  (`flags` NOT LIKE '%c%' OR `flags` IS NULL)
ORDER BY `priority`, `kci3_date`, `kci3_time` ASC
LIMIT 1

When I add an additional 'not like' it starts to return data with 'c' in flags

SELECT * 
FROM  `func` 
WHERE  `next_act` < 1484870400
AND  `assigned_to` IS NULL
AND `type` like '%FTCT%'
AND  (`flags` NOT LIKE '%c%' OR `flags` NOT LIKE 'w' OR `flags` IS NULL)
ORDER BY `priority`, `date`, `time` ASC
LIMIT 1

Solution

  • You have used OR with a not like.

    SELECT * 
    FROM  `func` 
    WHERE  `next_act` < 1484870400
    AND  `assigned_to` IS NULL
    AND `type` like '%FTCT%'
    AND  ((`flags` NOT LIKE '%c%' 
           AND `flags` NOT LIKE 'w' ) -- Should this be '%w%' ?
         OR `flags` IS NULL)
    ORDER BY `priority`, `date`, `time` ASC
    LIMIT 1
    

    You can also use:

    SELECT * 
    FROM  `func` 
    WHERE  `next_act` < 1484870400
    AND  `assigned_to` IS NULL
    AND `type` like '%FTCT%'
    AND  (NOT (`flags` LIKE '%c%' 
           OR `flags` LIKE 'w' ) -- Should this be '%w%' ?
          OR `flags` IS NULL)
    ORDER BY `priority`, `date`, `time` ASC
    LIMIT 1
    

    Saying (not like 'xxx' or not like 'yyy') means that 'xxx' is, in fact, not like 'yyy', so it will return the value.