Create a MySQL table from already created table selecting specific rows?


To create a table from an already created table, use CREATE TABLE AS SELECT statement. Let us first create a table −

mysql> create table DemoTable1318
-> (
-> Id int,
-> FirstName varchar(10),
-> LastName varchar(10),
-> Age int
-> );
Query OK, 0 rows affected (0.50 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1318 values(1,'Chris','Brown',21);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1318 values(2,'David','Miller',24);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1318 values(3,'Carol','Taylor',23);
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1318;

Output

+------+-----------+----------+------+
| Id   | FirstName | LastName | Age  |
+------+-----------+----------+------+
|   1  | Chris     | Brown    |  21  |
|   2  | David     | Miller   |  24  |
|   3  | Carol     | Taylor   |  23  |
+------+-----------+----------+------+
3 rows in set (0.00 sec)

Following is the query to create a table from an already created table selecting specific rows −

mysql> create table DemoTable1319
-> as select *from DemoTable1318
-> where Age IN(21,23);
Query OK, 2 rows affected (0.81 sec)
Records: 2 Duplicates: 0 Warnings: 0

Display all records from the table using select statement −

mysql> select * from DemoTable1319;

Output

+------+-----------+----------+------+
| Id   | FirstName | LastName | Age  |
+------+-----------+----------+------+
| 1    | Chris     | Brown    | 21   |
| 3    | Carol     | Taylor   | 23   |
+------+-----------+----------+------+
2 rows in set (0.00 sec)

Updated on: 04-Nov-2019

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements