andrew
andrew

Reputation: 9583

mysql difference between dates expressed in years

I've been using the following for some time to avoid the fact that DATEDIFF doesn't account for leap years.

"select 
  year(now()) 
  - year(`birthdate`) 
  - (date_format(now(), '%m%d') < date_format(`birthdate`, '%m%d');"

But I've never really understood exactly how it works, in particular, what the < operator does here?

Upvotes: 1

Views: 27

Answers (2)

spencer7593
spencer7593

Reputation: 108400

The < is a comparison operator.

So that last line is evaluated as a boolean expression. The expression on the left is being compared to the expression on the right, and the comparison is returning either NULL, 0 or 1. (MySQL returns 1 for TRUE and 0 for FALSE.)

The net effect of that last line is that's subtracting either a "0" or a "1" (if birthdate is not null.)

To see this in action, try running this query:

SELECT '0501' < '1031' AS foo

The result of the boolean expression can be referenced in another expression, for example:

SELECT 24 - ( '0501' < '1031' ) AS foo

If birthdate is non-null, the expression:

(date_format(now(),'%m%d') < date_format(`birthdate`,'%m%d')

Is equivalent to:

IF((date_format(now(),'%m%d') < date_format(`birthdate`,'%m%d'),1,0)

and equivalent to:

CASE WHEN (date_format(now(),'%m%d') < date_format(`birthdate`,'%m%d')
THEN 1
ELSE 0
END

Upvotes: 2

Jirka Kopřiva
Jirka Kopřiva

Reputation: 3089

The last boolean part (< comparsion) makes difference between asking before/after birthday. (Adds 1 OR 0)

Try:

SELECT 10 - 7 - true = 2

SELECT 10 - 7 - false = 3

Upvotes: 0

Related Questions