0

Working on a query but I need to implement some if else logic to check for a loop but I keep getting a 1064 bad syntax error.

I've gone over the manual and some examples but still no luck. So I stripped down my query to the most basic comparison below:

SET @start_date = '2019-06-01';
SET @other_date = CURDATE();

IF @start_date < @other_date THEN 
Select 'True';
ELSE
Select 'False';
END IF;

The below is the read out I receive from status:

SET @start_date = '2019-06-01' OK Time: 0.065s

SET @other_date = CURDATE()

OK Time: 0.065s

IF @start_date < @other_date THEN Select 'True'

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF @start_date < @other_date THEN Select 'True'' at line 1 Time: 0.067s

I understand that I'm going wrong somewhere with my syntax on the IF clause but in the docs it states:

IF [condition] THEN if-statements ELSE else-statements; END IF;

I'm not sure why this is failing, any insight would be appreciated.

0

2 Answers 2

1

For queries there is no IF...ELSE... statement (which you can use in stored procedures/functions).
Instead you can use the function IF():

SELECT IF(@start_date < @other_date, 'True', 'False');

or the CASE expression:

SELECT CASE WHEN @start_date < @other_date THEN 'True' ELSE 'False' END;

See the demo.

Sign up to request clarification or add additional context in comments.

5 Comments

What about for Loops? The whole reason I started looking at this and got stuck was because this logic is the control factor for a loop for a custom report. If stored procs and functions have different if/else syntax. Which is appropriate for a loop? This is what I had. WHILE (@start_date < NOW() && SUBDATE(@start_date, INTERVAL -2 WEEK) < NOW()) DO ...
You don't normally use loops in queries. In stored procedures/functions of course you can. If what you want is to write a stored procedure then you can use loops and if statements as well.
@nbk What does this have to do with RANK?
i shoud you an example with a loop where you use a if clause, i thought you meant that with your question about ifs and loops
@nbk this is not a loop (if this is what you implied).
1

You syntax is false

SET @start_date = '2019-06-01';
SET @other_date = CURDATE();

SELECT 
IF (@start_date < @other_date, 'True','False');

The result is true

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.