![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Is it possible to make an insert or an update in the same MySQL query?
Yes, use ON DUPLICATE KEY UPDATE. Let us first create a table −
mysql> create table DemoTable(Id int NOT NULL PRIMARY KEY, Number int); Query OK, 0 rows affected (0.83 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(1,190) ON DUPLICATE KEY UPDATE Number=Number+10; Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(2,130) ON DUPLICATE KEY UPDATE Number=Number+10; Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(1,190) ON DUPLICATE KEY UPDATE Number=Number+10; Query OK, 2 rows affected (0.14 sec) mysql> insert into DemoTable values(2,130) ON DUPLICATE KEY UPDATE Number=Number+10; Query OK, 2 rows affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output. We have inserted and updated records in the same query −
+----+--------+ | Id | Number | +----+--------+ | 1 | 200 | | 2 | 140 | +----+--------+ 2 rows in set (0.00 sec)
Advertisements