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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.