UPDATE with logical AND operator in MySQL


For this, you can use AND operator with WHERE clause. Let us first create a table −

mysql> create table DemoTable1616
    -> (
    -> StudentId int,
    -> StudentName varchar(20),
    -> StudentMarks int
    -> );
Query OK, 0 rows affected (0.44 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1616 values(101,'Chris',56);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1616 values(102,'Bob',87);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1616 values(103,'David',56);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1616 values(101,'Bob',89);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1616;

This will produce the following output −

+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
|       101 | Chris       |           56 |
|       102 | Bob         |           87 |
|       103 | David       |           56 |
|       101 | Bob         |           89 |
+-----------+-------------+--------------+
4 rows in set (0.00 sec)

Here is the query to update with logical AND operator −

mysql> update DemoTable1616 set StudentName='Adam' where StudentId=101 and StudentMarks=56;
Query OK, 1 row affected (0.48 sec)
Rows matched: 1  Changed: 1 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1616;

This will produce the following output −

+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
|       101 | Adam        |           56 |
|       102 | Bob         |           87 |
|       103 | David       |           56 |
|       101 | Bob         |           89 |
+-----------+-------------+--------------+
4 rows in set (0.00 sec)

Updated on: 28-Feb-2020

291 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements