I am working on mysql query right now. I write a query from fetch data from march 2018 to march 2019. There are more than 5000 records for this year. I write a query with date range from march 2018 to march 2019 but its showing me only 150 records
One more thing here. The date column in database is varchar. I know its not good but it was taken accidently during creation of database and I am not able to change this to date type because of lots of data in database
Here is the query I created
SELECT a.*,b.*
FROM OrderCalculation a
right join crm_order b on a.orderid = b.orderno
WHERE str_to_date(b.Date,'%Y-%m-%d') >= str_to_date(concat(YEAR(CURDATE()),'-08-01'),'%Y-%m-%d')-INTERVAL 1 YEAR
AND str_to_date(b.Date,'%Y-%m-%d') <= str_to_date(CONCAT(YEAR(CURDATE()),'-08-01'),'%Y-%m-%d')
Please make this query correct if you think something wrong in it
Thank you
Best Answer
You should really fix that. If the string always looks like yyyy-mm-dd, then it will happen to work as a date. (And my code below will work.) That is, the string version of a
DATE
orDATETIME
is handled almost identically the same as the proper datatype. One major difference is: "2019-08-01" versus "2019-8-1"Do not hide a column (
Date
) inside a function call (str_to_date
)-->
Did you really want 365 days, plus today? This disagrees with your statement of "from march 2018 to march 2019". (Plus March is 03, not 08.)
Now,
INDEX(Date)
may help with the speed of the query. I say only "may" because the index will be ignored if the year is most of the table; it would be faster to ignore the table and simply scan the data. (And my version will be as slow as yours).Please rearrange your query to use
LEFT JOIN
instead ofRIGHT JOIN
. My brain has trouble withRIGHT JOIN
.