- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Use UNION ALL to insert records in two tables with a single query in MYSQL
Here is the query to create first table.
mysql> create table DemoTable1 -> ( -> StudentName varchar(20), -> StudentMarks int -> ); Query OK, 0 rows affected (0.67 sec)
To understand the above concept, let us create second table.
mysql> create table DemoTable2 -> ( -> Name varchar(20) -> ); Query OK, 0 rows affected (0.61 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2 values('Chris'); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable2;
This will produce the following output −
+-------+ | Name | +-------+ | Chris | +-------+ 1 row in set (0.00 sec)
Here is the query to select and insert records with a single MySQL query −
mysql> insert into DemoTable1 -> select Name,89 from DemoTable2 -> union all -> select Name,98 from DemoTable2; Query OK, 2 rows affected (0.15 sec) Records: 2 Duplicates: 0 Warnings: 0
Now you can select records from the first table −
mysql> select * from DemoTable1;
This will produce the following output −
+-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | Chris | 89 | | Chris | 98 | +-------------+--------------+ 2 rows in set (0.00 sec)
- Related Articles
- MySQL select and insert in two tables with a single query
- How to insert into two tables using a single MySQL query?
- Insert all the values in a table with a single MySQL query separating records by comma
- MySQL SELECT from two tables with a single query
- Merge two tables with union in MySQL?
- Insert values in two tables with a single stored procedure call in MySQL
- Can we use stored procedure to insert records into two tables at once in MySQL?
- A single MySQL query to insert records (not all) in the second table from the first table
- Insert records from multiple tables in MySQL
- How to count rows from two tables in a single MySQL query?
- MySQL UNION SELECT and IN clause in a single query
- A single MySQL select query on two tables is possible?
- Fastest way to insert with multiple values in a single MySQL query?
- Delete records from a MySQL table with IN() in a single query
- How to insert multiple rows with single MySQL query?

Advertisements