0

I need to add an if/else stament inside a MySQL query but can't get it to work.

Below is an example with pseudo-code of what I want to accomplish.

SELECT *
FROM calendar
WHERE calendar.alert = 1

IF calendar.repeat = 0 THEN HAVING calendar.UTC_1 > UNIX_TIMESTAMP();

ELSE "get all records regardless of calendar.repeat value";

END IF;

Any suggestions to make this happen? I couldn't find the correct syntax for this MySQL IF ELSE.

Thanks for helping!

1
  • What you ask for is not sargable -- it's possible to do, but not the best performing option available. Commented May 14, 2011 at 22:49

2 Answers 2

1
SELECT *
FROM calendar
WHERE calendar.alert = 1 
AND CASE 
WHEN `repeat` =0 THEN UTC_1 > UNIX_TIMESTAMP()
ELSE 1=1 END;

You can use IF-ELSE only inside the body of stored procedure/trigger. You can use IF(condition, value_if_condition_is_true, value_if_condition_is_false) in SELECT, but I prefer CASE(you can easily rewrite the query above to

 .... AND IF(`repeat` = 0, UTC_1>UNIX_TIMESTAMP(),1=1)
Sign up to request clarification or add additional context in comments.

2 Comments

Are you sure that calendar.alert = 1 is true for these records? Maybe it should be OR instead of AND - I didn't get it from your question
sorry i was updating my comment when yours came through - your code works, the record (with repeat = 1) i was testing did not return initially because it had alert = 0 -- once i corrected this it works nicely - thanks so much for helping!
1

Not sure I got the syntax all right here, but I like the idea of somethign like this. In my opinion it is much easier to look at in the future and see the two groups you're grabbing with the following example. I'm not educated on efficiency of case vs union in MySQL but it seems to me like the case would be less efficient as well. Maybe someone can answer that for sure?

SELECT *
FROM calendar
WHERE 
    calendar.alert = 1
    AND calendar.repeat = 0
    AND calendar.UTC_1 > UNIX_TIMTESTAMP();
UNION
SELECT *
FROM calendar
WHERE
    calendar.alert = 1
    AND calendar.repeat != 0

Comments

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.