3

In a MySQL query, I am trying to select either a DATEDIFF() or NOW() based on an IF() condition. The behavior of MySQL is confusing me here.

This query run in phpMyAdmin has some strange results. The values should be identical, but they are not.

SELECT
                 TIMEDIFF(DATE_ADD(NOW(), INTERVAL 1 HOUR), NOW())  AS `A`,
IF(FALSE, NOW(), TIMEDIFF(DATE_ADD(NOW(), INTERVAL 1 HOUR), NOW())) AS `B`

A ----------------- | B -----------------
01:00:00 ---------- | 2001-00-00 00:00:00

If I try this query, changing NOW() to NULL in the first option of the IF condition, it shows the proper result for the TIMEDIFF. Why is this?

SELECT
                TIMEDIFF(DATE_ADD(NOW(), INTERVAL 1 HOUR), NOW())  AS `A`,
IF(FALSE, NULL, TIMEDIFF(DATE_ADD(NOW(), INTERVAL 1 HOUR), NOW())) AS `B`

A ----------------- | B -----------------
01:00:00 ---------- | 01:00:00

So then my question is: how is NOW() versus NULL affecting the IF return?

5
  • What does it return in the first statement?
    – hichris123
    Jan 9, 2014 at 4:58
  • I tried the case. Still the same result when I add in the NOW().
    – axiom82
    Jan 9, 2014 at 5:36
  • may be NOW function has to return a value in all cases, because I was testing the same query with RAND() and SQRT() functions but in that case it is returning the correct value, so may be the issue is with now function return value Jan 9, 2014 at 5:41
  • same thing with curdate function Jan 9, 2014 at 5:46
  • got an ans... see if it works good with you, worked for me Jan 9, 2014 at 5:56

2 Answers 2

0

May be NOW() or other date functions have to return a value in all cases, because I was testing the same query with RAND() and SQRT() functions but in that case it is returning the correct value, so may be the issue is with NOW() function return value

TRY using NOW() with a blank CONCAT(),it won't manipulate your return value also, and it worked well both with TRUE and FALSE

 SELECT
      TIMEDIFF(DATE_ADD(NOW(), INTERVAL 1 HOUR), NOW())  AS `A`,
 IF(TRUE, CONCAT(NOW()), TIMEDIFF(DATE_ADD(NOW(), INTERVAL 1 HOUR), NOW())) AS `B`

OR

SELECT TIMEDIFF( DATE_ADD( NOW( ) , INTERVAL 1 HOUR ) , NOW( ) ) AS  `A` , 
CASE WHEN TRUE THEN TIMEDIFF( DATE_ADD( NOW( ) , INTERVAL 1 HOUR ) , NOW( ) ) 
ELSE CONCAT( NOW( ) ) 
END AS  `B

both gave correct result

0

I submitted this is a bug and it was just verified by MySQL staff members. http://bugs.mysql.com/bug.php?id=71322

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.