MySQL query to insert data from another table merged with constants?


Let us first create a table −

mysql> create table DemoTable1(Name varchar(100));
Query OK, 0 rows affected (0.83 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values('John');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1 values('Chris');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1 values('Robert');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+--------+
| Name   |
+--------+
| John   |
| Chris  |
| Robert |
+--------+
3 rows in set (0.00 sec)

Following is the query to create second table −

mysql> create table DemoTable2(
   ConstantValue int,
   EmployeeName varchar(100)
);
Query OK, 0 rows affected (0.70 sec)

Following is the query to insert data from another table merged with constants −

mysql> insert into DemoTable2(ConstantValue,EmployeeName) select '1000',Name from DemoTable1;
Query OK, 3 rows affected (0.13 sec)
Records: 3 Duplicates: 0 Warnings: 0

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+---------------+--------------+
| ConstantValue | EmployeeName |
+---------------+--------------+
| 1000          | John         |
| 1000          | Chris        |
| 1000          | Robert       |
+---------------+--------------+
3 rows in set (0.00 sec)

Updated on: 26-Aug-2019

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements