0

I'm getting error near the if statement...don't know why

#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 @a=0 then select @a' at line 1

set @a = (SELECT COUNT(*) FROM hi where x=33 and y=-4);

if @a = 0 then select @a; end if;

2
  • "Getting syntax error" is not a problem description unless you also include the error message you're getting, so we know what the error is. You have that information right in front of you - there is absolutely no reason for you to fail to include it in your question. Commented Jun 24, 2014 at 22:37
  • updated with error message Commented Jun 24, 2014 at 22:40

1 Answer 1

2

You can't use if like that as plain sql, but you can refactor it to a insert into select ... and apply the condition in the where clause:

insert into hi (x,y)
select * from (select '33', '-4') x
where @a = 0

See demo of the select part

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

3 Comments

What does the x do at the end of the select statement ?
And the second select is a subquery right ? , but not sure what it's doing
The 'x' is an alias that names the result of the subquery query - effectively given the table of results a name do you can refer to it like it was a real table. It's required by SQL syntax, whether or not you refer to it. The inner subquery is required to allow a where clause to be used, because to have a "where" you must have a "from". However, you can have a "select" without a "from", so by using an inner query you can select constant values, then by wrapping it up as a table you can use apply a where.

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.