Create a duplicate copy of the MySQL table named countries with both structure and data, naming it dup_countries
MySQL Create Tables: Exercise-4 with Solution
4. Write a MySQL query to create a duplicate copy of countries table including structure and data by name dup_countries.
Sample Solution:
-- Creating a new table named 'dup_countries' if it doesn't already exist
CREATE TABLE IF NOT EXISTS dup_countries
-- Populating the new table by selecting all columns and rows from the existing 'countries' table
AS SELECT * FROM countries;
Let execute the above code in MySQL command prompt
Here is the structure of the table:
mysql> DESC dup_countries; +--------------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+---------------+------+-----+---------+-------+ | COUNTRY_ID | varchar(2) | YES | | NULL | | | COUNTRY_NAME | varchar(40) | YES | | NULL | | | REGION_ID | decimal(10,0) | YES | | NULL | | +--------------+---------------+------+-----+---------+-------+ 3 rows in set (0.11 sec)
Explanation:
The above MySQL code creates a new table named "dup_countries" if it doesn't already exist. It populates the new table by selecting all columns and rows from the existing "countries" table using the "AS SELECT * FROM countries" statement. In essence, it duplicates the structure and data of the "countries" table into the new table "dup_countries".
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a SQL statement to create the structure of a table dup_countries similar to countries.
Next: Write a SQL statement to create a table countries set a constraint NULL.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/mysql-exercises/create-table-exercises/create-table-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics