How can I create a new table based on an existing table in SQL?

In SQL, you can use the CREATE TABLE statement to create a new table based on an existing table. The basic syntax of this statement is as follows:

CREATE TABLE new_table_name AS
SELECT column1, column2, ...
FROM existing_table_name
WHERE condition;

In this case, new_table_name is the name of the new table and existing_table_name is the name of the existing table.

For example, let’s say there is a table named customers with columns customer_id, customer_name, and email. We can create a new table named new_customers with only customer_id and customer_name columns using the following statement:

CREATE TABLE new_customers AS
SELECT customer_id, customer_name
FROM customers;

Please note that the WHERE clause in the statement above is optional and can be omitted if filtering criteria are not needed.

Instead of using the SELECT statement to create a new table, you can also manually specify the column definitions in the CREATE TABLE statement. For example:

CREATE TABLE new_table_name (
   column1 datatype,
   column2 datatype,
   ...
);

This method allows for manually defining the structure of a new table based on the structure of an existing table.

bannerAds