Create a New table by copying all rows or column data from an Existing table that is another table OR Copying only selected columns OR Copying Selected Columns and Selected Rows from an Existing table

1) Creating a New Table by copying all the columns/data from an Existing table – Here the table "NewTable" is newly created

Example:
Select * INTO NewTable FROM ExistingTable

Note - For the above query the table "NewTable" need not exist in the database, The schema will be automatically created based on the table "ExistingTable"
The Data types of the Newly Created table will be exactly same as the Existing table.
All the constraints wont be copied like DEFAULT Constraint wont be preserved where as NULL Constraints will be preserved

2) Creating a New Table by Copying selected Columns from an Existing table

Example:
Select Employee_Id,First_Name,Last_Name INTO NewTable FROM ExistingTable

Note - Here Employee_Id,First_Name and Last_Name are few of the many columns that are present in the table ExistingTable.

3) Creating a New Table by Copying Selected columns and selected Rows from an Existing table using where condition

Example:
Select Employee_Id,First_Name,Last_Name INTO NewTable FROM ExistingTable where Employee_Id < 5

4) Creating a New Table by not copying any data from an Existing table

Example:
SELECT Employee_Id,First_Name,Last_Name INTO NewTable FROM ExistingTable where 1 = 2


With above queries, we have learnt a new concept called as - CTAS, which stands for ‘Create Table As Select’, that is creating a Table from an Existing table with Select Query

No comments: