Write a query to create a new table with the data and structure of another table

Description: Create a table named students_backup with all the data of students.

Tables: the exercises use the students (id, name, city, marks, course_id) and courses (id, course_name) tables, with the data from our MySQL INSERT chapter. The students are: Robin (Delhi, 85), Maria (Mumbai, 92), John (Pune, 78), Asha (Jaipur, 88), Vikram (Delhi, 65), Neha (Mumbai, 45).

Hint:

  • Use CREATE TABLE new_table AS SELECT * FROM old_table.

MySQL query to copy a table

CREATE TABLE students_backup AS
SELECT * FROM students;

SELECT COUNT(*) AS rows_in_backup FROM students_backup;

Output:

Tutorials Class - Output Window
rows_in_backup
6

How it works

  • The new table gets the same columns and all 6 rows.
  • Primary keys and indexes are not copied. Use CREATE TABLE ... LIKE if you need them, and then INSERT INTO ... SELECT.

Read the interview question create a new table from another table.


Learn more about the similar topics:
Tutorials
MySQL Data Types
MySQL CREATE DATABASE
MySQL USE and SHOW DATABASES
MySQL DROP DATABASE
MySQL CREATE TABLE
MySQL Constraints
MySQL DROP TABLE
Exercises & Assignments
Write a query to get all column names of a database table
Write a query to create a new table with the data and structure of another table
Interview Questions & Answers
Write a query to create a new table which consists of data and structure copied from the other table
What is a primary key in MySQL?
What is a foreign key in MySQL?
What is the difference between CHAR and VARCHAR in MySQL?
What is normalization in MySQL?
What is AUTO_INCREMENT in MySQL?
What is the difference between primary key and unique key?