w3resource

Create the structure of a MySQL table named dup_countries similar to the existing table named countries

MySQL Create Tables: Exercise-3 with Solution

3. Write a MySQL query to create the structure of a table dup_countries similar to countries.

Sample Solution:

-- Creating a table named 'dup_countries' if it doesn't already exist, with the same structure as the 'countries' table

CREATE TABLE IF NOT EXISTS dup_countries
-- Using the LIKE keyword to copy the structure of the 'countries' table to 'dup_countries'
LIKE 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.03 sec)

Explanation:

The above MySQL code creates a new table named dup_countries with the same structure as the existing table countries.

  • The IF NOT EXISTS clause ensures that the new table is only created if it doesn't already exist in the database.
  • The LIKE keyword is used to copy the structure (columns, data types, etc.) of the countries table to the new dup_countries table.

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a SQL statement to create a simple table countries including columns country_id,country_name and region_id which is already exists.
Next: Write a SQL statement to create a duplicate copy of countries table including structure and data by name dup_countries.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.