0

i want to use a if condition in a sql query according to following need.
"if a year field is null then do not calculate age and if it is set then it have to execute.
here is my query.where is the problem?please consider this scenario 'if month and date is there like for example 0000-03-12'

SELECT id, name, birth_date, birth_time, 
            city_native, country_native, sex, 
            city_current, country_current, image,
            if(YEAR(birth_date)='','',YEAR(CURDATE()) - YEAR(birth_date) - 
              (RIGHT(CURDATE(),5) < RIGHT(birth_date,5)),'') AS age
        FROM birth_user u
        WHERE <condition>;
1
  • Which DBMS are you using? Commented Apr 4, 2014 at 11:29

3 Answers 3

1

You can use IFNULL() to check birth_date is NULL

CASE WHEN IFNULL(birth_date,0)=0 THEN '' ELSE YEAR(CURDATE()) - YEAR(birth_date) END as age
Sign up to request clarification or add additional context in comments.

Comments

0

If your need is "if it is null", why are you comparing it to zero?

if(birth_date is null, 0, YEAR(CURDATE()) - ......) AS age

Where that 0 there is a suitable "default age".

5 Comments

because in my code if year is not available then set it to '0000' instead of 1970.
So it's not null, it's 0000-00-00? In that case, why not just check if( birth_date = '0000-00-00', ...)?
but it will fail when there is month and date is there like for example 0000-03-12
Why would there ever be a month and date when the year is zero?
this is coming from facebook friend list friend,when a user does not allow to show a year feild.
0

Use NULL instead of 0000

SELECT id, name, birth_date, birth_time, 
city_native, country_native, sex, 
city_current, country_current, image,
if(birth_date is null,'',YEAR(CURDATE()) - YEAR(birth_date) - 
(RIGHT(CURDATE(),5) < RIGHT(birth_date,5)),'') AS age
FROM birth_user u
WHERE " . implode(' AND ', $where);

1 Comment

in my code if year is not available then set it to '0000' instead of 1970.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.