sqlmysqloperatorsbetween

why "Between" operator not working with month text in mysql?


In my dataset, months are stored in a format as 'June-21', 'Aug-21' like that.

For a query with Between:

Select sum(downloads) 
from ratings
where months between 'October-21'and 'December-21';   

It fetches null values whereas with IN operator it gives perfect results.

Query with IN Operator:

SELECT SUM(downloads) AS total_downloads
FROM ratings 
WHERE months in ('October-21', 'November-21' , 'December-21') 

Why a query with between is not working?

I tried with the IN operator, and it worked. But my question is why it is not working with between?

Dataviewerror with between operator


Solution

  • That is because BETWEEN a AND B means greater or equal to a and smaller or equal to b .

    The 'O' of 'October' comes after the 'D' of December, so there is nothing between those two. You are comparing strings, not dates. See also this test:

    SELECT 
      CASE 
        WHEN 'October-21' < 'December-21' THEN 'TRUE'
        ELSE 'FALSE'
      END AS string_comp_test
    , CASE 
        WHEN DATE '2021-10-01' < DATE '2021-12-01' THEN 'TRUE'
        ELSE 'FALSE'
      END AS date_comp_test
    ;
    
    string_comp_test date_comp_test
    FALSE TRUE

    fiddle