Wednesday, 26 May 2021

Create a table from an existing table | SQL

CREATE A NEW TABLE FROM THE EXISTING TABLE  WITH DATA OR WITHOUT DATA ALONG WITH FEW COLUMNS OR ALL THE COLUMNS USING ONE TABLE OR MULTIPLE TABLES
These SQL queries will create the basic table and its fields but not indexes, constraints, or triggers as it is in the existing table.

CREATE AN EMPTY TABLE FROM AN EXISTING TABLE:

Syntax:
CREATE TABLE new_table 
  AS (SELECT * 
      FROM old_table WHERE 1=2); 

Example:
CREATE TABLE suppliers 
AS (SELECT * 
 FROM companies 
 WHERE 1=2);


CREATE A TABLE FROM AN EXISTING TABLE WITH DATA:

Syntax:
CREATE TABLE new_table 
  AS (SELECT * 
      FROM old_table); 

Example:
CREATE TABLE suppliers 
AS (SELECT * 
 FROM companies 
 WHERE id > 1000);


CREATE A TABLE WITH ONLY A FEW COLUMNS FROM AN EXISTING TABLE WITH DATA:

Syntax:
CREATE TABLE new_table 
AS (SELECT column_1, column2, ... column_n 
FROM old_table); 

Example:
CREATE TABLE suppliers 
AS (SELECT id, address, city, state, zip 
FROM companies 
WHERE id > 1000); 


CREATE A TABLE WITH ONLY A FEW COLUMNS FROM AN EXISTING MULTIPLE TABLES WITH DATA:

Syntax:
CREATE TABLE new_table 
  AS (SELECT column_1, column2, ... column_n 
      FROM old_table_1, old_table_2, ... old_table_n); 

Example:
CREATE TABLE suppliers 
AS (SELECT companies.id, companies.address, categories.cat_type 
FROM companies, categories 
WHERE companies.id = categories.id 
AND companies.id > 1000); 


Read More:

  • What does count 1 mean in SQL?
  • How to include a single quote in a SQL query?

  • No comments:

    Post a Comment