Rob Avery IV
Rob Avery IV

Reputation: 3720

Is it possible to do a MySQL with IF EXISTS query with two conditions

I want to be able to do something like this:

IF EXISTS (SELECT * FROM table WHERE col=val)
    INSERT ......
ELSE
    UPDATE ......

I know that you are able to do this:

IF EXISTS (SELECT * FROM table WHERE col=val)
    INSERT ......

But I'm not sure if you can do an else along with that.

What would fastest way to do the first query?

Upvotes: 0

Views: 29

Answers (2)

Rahul
Rahul

Reputation: 77846

You should rather use INSERT ... ON DUPLICATE KEY UPDATE

insert into table1 (col1,col2) values(1,2) 
on duplicate key update col2=3, col1=4

See Here for more information.

Upvotes: 0

hlscalon
hlscalon

Reputation: 7552

Yes it is possible. One way to do this is by using a procedure.

DELIMITER $$  

DROP PROCEDURE IF EXISTS `YOUR-PROCEDURE`$$  

CREATE DEFINER=`root`@`localhost` PROCEDURE `YOUR-PROCEDURE`()  
BEGIN  
    IF EXISTS (SELECT * FROM table WHERE col=val)
THEN      
   BEGIN      
     UPDATE table SET ..;  
   END;      
ELSE      
   BEGIN      
     INSERT INTO table ..;  
   END;      
END IF;     
  END$$  

DELIMITER ;  

Upvotes: 1

Related Questions