Languages
[Edit]
EN

MySQL - duplicate table with indexes and data

0 points
Created by:
Keisha-Acosta
380

In this article, we would like to show you how to duplicate table with indexes and data in MySQL.

Quick solution:

CREATE TABLE `new_table` LIKE `old_table`; 
INSERT INTO `new_table` SELECT * FROM `old_table`;

Practical example

To show how to duplicate table with indexes and data, we will use the following table:

MySQL - example data used to duplicate table with indexes and data
MySQL - example data used to duplicate table with indexes and data

Note:

At the end of this article you can find database preparation SQL queries.

Example

In this example, we will create an exact copy of users table named users_copy.

Query:

CREATE TABLE `users_copy` LIKE `users`; 
INSERT INTO `users_copy` SELECT * FROM `users`;

Output:

MySQL - duplicate table with indexes and data - result
MySQL - duplicate table with indexes and data - result in HeidiSQL

Database preparation

create_tables.sql file:

CREATE TABLE `users` (
	`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(50) NOT NULL,
	`surname` VARCHAR(50) NOT NULL,
	`email` VARCHAR(50),
	PRIMARY KEY (`id`)
);

insert_data.sql file:

INSERT INTO `users`
	( `name`, `surname`, `email`)
VALUES
	('John', 'Stewart', 'john@email.com'),
	('Chris', 'Brown', 'chris@email.com'),
	('Kate', 'Lewis', 'kate@email.com'),
	('Ailisa', 'Gomez', 'ailisa@email.com'),
	('Gwendolyn', 'James', 'gwen@email.com'),
	('Simon', 'Collins', 'simon@email.com'),
	('Taylor', 'Martin', 'taylor@email.com'),
	('Andrew', 'Thompson', 'andrew@email.com');

Alternative titles

  1. MySQL - copy table with indexes and data
  2. MySQL - copy table including indexes
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

MySQL - indexes

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join