Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a MySQL if else endif statement?

I'd like a simple example of a MySQL if, else, endif statement.

I want to do something like this (in Java):

SELECT COUNT(*) FROM  `table` WHERE  `userID` =  1

if(count == 0){
  INSERT INTO  `table` (`userID`,`A` ,`B`)VALUES ('1',  '323',  '232')
}
else{
  UPDATE  `table` SET  `A` =  '323', `B` =  '232' WHERE  `userID` =1
}
like image 817
James MV Avatar asked Mar 04 '13 02:03

James MV


People also ask

How do I write if and else in MySQL?

MySQL IF-THEN-ELSEIF-ELSE statement The syntax is given below: IF condition THEN statements; ELSEIF elseif-condition THEN elseif-statements; ... ELSE else-statements; END IF; Let's review each block.

How do you write if/then else in SQL?

IF color = red THEN dbms_output. put_line('You have chosen a red car') ELSE dbms_output. put_line('Please choose a color for your car'); END IF; If the Boolean expression condition evaluates to true, then the if-then block of code will be executed otherwise the else block of code will be executed.

What is the syntax of if else?

Syntax. If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will be executed. C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.


2 Answers

MySQL has INSERT ON DUPLICATE KEY UPDATE that allows you to update if the value already exist or Insert if not.

First you need to setup a UNIQUE Constraint,

ALTER TABLE myTable ADD CONSTRAINT tb_uq UNIQUE (ID)

that's it if you want ID to be unique. (This is just an example)

INSERT INTO tableName(userID, A, B) 
VALUES (1, 323, 232)
ON DUPLICATE KEY
UPDATE  A = 323,
        B = 232
  • INSERT ... ON DUPLICATE KEY UPDATE Syntax
like image 58
John Woo Avatar answered Oct 04 '22 22:10

John Woo


The if statement (in a stored block):

IF search_condition THEN statement_list
    [ELSEIF search_condition THEN statement_list] ...
    [ELSE statement_list]
END IF

Or the if function (in-line):

IF(expr1,expr2,expr3)

which works as: IF( condition, what_to_do_if_true, what_to_do_if_false ) The last part being the same as an 'else'. An if-else-if would need to be embedded like:

SELECT IF( id==1, "1", IF( ID==2, "2", "Neither" );

Which would do the same as this in most programming languages:

if( id == 1 ) {
    print "1"
} elsif( id == 2 ) {
    print "2"
} else {
    print "Neither"
}
like image 30
Jim Black Avatar answered Oct 04 '22 21:10

Jim Black