How to fix MYSQL between date not giving accurate results?

How to fix MYSQL between date not giving accurate results?

SELECT
IF
    (
        SUM( t.debit )>= SUM( t.credit ),
        SUM( t.debit ) - SUM( t.credit ),
    SUM( t.credit ) - SUM( t.debit )) AS Balance,
    
    IF(SUM( t.debit )>= SUM( t.credit ) ,"Profit", "Loss") AS status 
FROM
    transactions AS t 
WHERE
    t.userId = 1 AND t.dateIssued BETWEEN  '2021-07-09' AND '2021-07-10';

I expected to give 6000 as the output because the between should be date inclusive

How to fix MYSQL between date not giving accurate results?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

dateIssued is not a Date, it is a DateTime/timestamp.
So, when you compare its value 2021-07-10 13:11:12 to dates like '2021-07-09' and '2021-07-10' the comparison is interpreted as:

'2021-07-10 13:11:12' BETWEEN '2021-07-09 00:00:00' AND '2021-07-10 00:00:00'

which returns false.

Convert dateIssued to Date with the function Date() and then compare:

WHERE t.userId = 1 AND DATE(t.dateIssued) BETWEEN  '2021-07-09' AND '2021-07-10';

For better performance you should consider writing the conditions without BETWEEN and the function Date():

WHERE t.userId = 1 
  AND t.dateIssued >=  '2021-07-09' 
  AND t.dateIssued < '2021-07-11';


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x