0

I want an if query like below.

set @i=1;
set @j=2;
if @i < @j then select * from test limit 1;
end if;

Im getting the below error,

1064 (42000): 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 @i < @j then select * from test limit 1' at line 1

Also tried this in procedure,

DELIMITER $$
DROP PROCEDURE IF EXISTS test $$
create procedure test ()
set @i=1;
set @j=2;
if @i < @j then select * from test limit 1;
end if;
END $$


ERROR 1064 (42000): 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 @i < @j then select * from test limit 1;
end if;
END' at line 1

Can anyone help me to fix this?

3
  • 2
    Unless this code is in a stored procedure or trigger, MySQL has no support for IF..THEN statements. Commented Oct 27, 2017 at 22:40
  • Type fixed, let me try this inside the proc. Commented Oct 27, 2017 at 22:41
  • in procedure also its not working. Commented Oct 27, 2017 at 22:44

2 Answers 2

1

You need a begin:

DELIMITER $$
DROP PROCEDURE IF EXISTS test $$
create procedure test ()
begin
    set @i=1;
    set @j=2;
    if @i < @j then
         select * from test limit 1;
    end if;
END $$

DELIMITER ;

Your first doesn't work because if is only allowed in programming blocks. In fact, that is why your version doesn't work either -- without the begin the if is not in a programming block.

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

2 Comments

thanks, but it didn't return any values. It'll go infinite while hit enter. call test(); -> -> -> ->
Type DELIMITER ; afterwards to go back to the normal delimiter.
1

Instead of using IF, put the test in the query:

SELECT * FROM TEST
WHERE @i < @j
LIMIT 1

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.