Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL SET IF Statement

Can someone show me the correct mysql syntax to do the following:

Update a column in a table with 1 of 3 values:

If col_A = 4 set col_Z to col_A If col_B = 4 set col_Z to col_B Else set col_Z to NULL (or leave alone because col_Z is initialized to NULL)

Here's what I have:

Update my_table
SET col_Z = IF(col_A = 4, col_A, IF(col_B = 4, col_B, NULL))
WHERE id = "001"

IS this correct?

like image 470
H. Ferrence Avatar asked May 01 '11 20:05

H. Ferrence


People also ask

Can we use if statement in select query in MySQL?

Answer: MySQL IF() function can be used within a query, while the IF-ELSE conditional statement construct is supported to be used through FUNCTIONS or STORED PROCEDURES.

Is set MySQL?

SET is a data type of String object that can hold zero or more, or any number of string values. They must be chosen from a predefined list of values specified during table creation. It is one of the rarely used data type in the MySQL database.


Video Answer


1 Answers

Yes, it looks correct.

The following code will be simpler though.

UPDATE my_table
SET col_Z = IF(col_A = 4 OR col_B = 4, 4, NULL)
WHERE id = "001"
like image 120
Johan Avatar answered Oct 05 '22 23:10

Johan