Create a temporary table similar to a regular table with MySQL LIKE

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable1
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(100)
);
Query OK, 0 rows affected (0.59 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1(Name) values('Chris');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1(Name) values('Robert');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1(Name) values('Mike');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1(Name) values('Sam');
Query OK, 1 row affected (0.07 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+----+--------+
| Id | Name   |
+----+--------+
|  1 | Chris  |
|  2 | Robert |
|  3 | Mike   |
|  4 | Sam    |
+----+--------+
4 rows in set (0.00 sec)

Following is the query to create a temporary table LIKE a regular table −

mysql> create temporary table DemoTable2 like DemoTable1;
Query OK, 0 rows affected (0.04 sec)

Let us check the description of the table −

mysql> desc DemoTable2;

This will produce the following output −

+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| Id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| Name  | varchar(100) | YES  |     | NULL    | NULL           |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.04 sec)
raja
Published on 30-Sep-2019 11:38:04
Advertisements