Languages
[Edit]
EN

MySQL - UPDATE query with IF condition (conditional update)

0 points
Created by:
WGates
412

In this article, we would like to show you UPDATE query with IF condition in MySQL.

Quick solution:

Practical example

Edit

To show UPDATE query with IF condition, we will use the following users table:

MySQL - example data used for conditional update
MySQL - example data used for conditional update

Note:

At the end of this article you can find database preparation SQL queries.

Example 1

Edit

In this example, we will update every department_id to 11 if it is equal to 1.

Query:

Output:

MySQL - UPDATE query with IF condition - result
MySQL - UPDATE query with IF condition - result

Note:

Go to this article to see more IF() function practical examples.

Example 2 - with WHERE clause

Edit

Optionally you can add WHERE clause to Example 1.

In this example, we will update every department_id to 11 if it is equal to 1 but only for users whose id > 3.

Query:

Output:

MySQL - conditional UPDATE - result
MySQL - conditional UPDATE - result

Database preparation

Edit

create_tables.sql file:

insert_data.sql file:

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join