0

I've searched through google and here but didn't find an answer to my question.

I'm trying to use IF in a query (not stored procedure) in that way:

IF EXISTS (SELECT *  FROM TABLE WHERE COLUMN=VALUE) THEN
DO SOMETHING
END IF;

I've tryed in MySql Workbench and didn't work (Syntax error).

Anybody knows if it's possible to use IF in that way?

Thanks in advance.

2
  • 3
    What SOMETHING do you wish to DO ? Commented Jan 19, 2013 at 17:05
  • SOMETHING in that case in an INSERT . Commented Jan 19, 2013 at 17:33

2 Answers 2

1

It depends on what is SOMETHING

If it is an UPDATE, DELETE or SELECT, you can specify the conditions in the where clause.

WHERE IF( (SELECT COUNT(*) FROM TABLE WHERE COLUMN=VALUE) > 0, 1, 2) = 1

For other statements (INSERT, CREATE, etc.) i don't think this is possible.

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

4 Comments

I need to do an insert but before that I need to check if already exists a row with these values.
@Valerio: So, if a record already exists with COLUMN=VALUE you don't want the INSERT to be performed? Why not define a UNIQUE index over COLUMN, which will enforce such a constraint for you?
for inserts, see the INSERT ... ON DUPLICATE KEY UPDATE. It is not exactly the same, but maybe it is what you are looking for
@eggyal: In my case I need to check 4 column for duplicate value. I'll try in that way. Thanks a lot.
0

In your comments you say that "SOMETHING" is an INSERT operation. You can then, instead of:

INSERT INTO tableName
  (colA, colB, ...)
VALUES
  (a, b, ...) ;

use:

INSERT INTO tableName
  (colA, colB, ...)
SELECT
  a, b, ... 
FROM 
  dual
WHERE
  EXISTS (SELECT * FROM TABLE WHERE COLUMN=VALUE) ;

3 Comments

Didn't know this syntax :( . I'm gonna try. Thanks!
OK, I've tryed this syntax and I need to insert only if record doesn't alredy exists so after a couple of test I've seen that the correct syntax for me is : INSERT INTO tableName (colA, colB, ...) SELECT a, b, ... FROM dual WHERE NOT EXISTS (SELECT * FROM TABLE WHERE COLUMN=VALUE);
Thanks ! I've some problem with writing 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.