Zeeshan Arif
Zeeshan Arif

Reputation: 23

Conditional Insert Statement in MySQL

I would like to achieve the following in a MySQL insert statement.

Say for example there is a MySQL statement like below:

Insert into table_name (col1, col2, col3) values (val1, val2, val3, val4);

What I want to achieve is: If val3 is empty, then val4 should be inserted to col3. If val4 is empty, then val3 should be inserted to col3.

How can I achieve this in a MySQL insert statement?

Upvotes: 0

Views: 166

Answers (2)

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

You can use a case statement to check for null or '' string

Insert into table_name (col1, col2, col3) 
values (val1, val2, case when val3 is null or val3 = '' then val4 else val3 end);

Upvotes: 2

Akina
Akina

Reputation: 42632

If "If val3 is empty" means "val3 is NULL" then

Insert into table_name (col1, col2, col3) values (val1, val2, COALESCE(val3, val4));

If val3 is not NULL - this value will be inserted, and val4 will be ignored anycase. If val3 is null, then val4 will be inserted, even it is NULL.

Upvotes: 3

Related Questions