Copy a few columns from a table to another in MySQL


Let us first create a table −

mysql> create table DemoTable1
   -> (
   -> Id int,
  -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(10,'John');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable1 values(11,'Chris');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable1 values(12,'Robert');
Query OK, 1 row affected (0.32 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+------+--------+
| Id   | Name   |
+------+--------+
|   10 | John   |
|   11 | Chris  |
|   12 | Robert |
+------+--------+
3 rows in set (0.00 sec)

Following is the query to copy few columns from a DemoTable1 to another table DemoTable2 −

mysql> create table DemoTable2 (
-> select Name from DemoTable1 where Id=11
-> );
Query OK, 1 row affected (0.70 sec)
Records: 1 Duplicates: 0 Warnings: 0

Now check the table records of table ‘DemoTable2’ −

mysql> select *from DemoTable2;

Output

This will produce the following output −

+-------+
| Name  |
+-------+
| Chris |
+-------+
1 row in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jun-2020

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements