SQL SELECT INTO Statement
The SQL SELECT INTO statement is used to create a new table from the result set of a SELECT statement. The SELECT INTO statement allows us to create a new table with the same data structure and data as an existing table.
Consider the following table:
| OrderID | CustomerID | 
|---|---|
| 1 | 10 | 
| 2 | 20 | 
| 3 | 30 | 
To create a new table NewOrders with the same data as the Orders table, we can use the following SELECT INTO statement:
1SELECT * INTO NewOrders 2FROM Orders;
The output of the above query will be:
| OrderID | CustomerID | 
|---|---|
| 1 | 10 | 
| 2 | 20 | 
| 3 | 30 | 
As we can see from the output, the SELECT INTO statement creates a new table NewOrders with the same data as the Orders table.
It's important to note that the SELECT INTO statement creates a new table in the current database, and the new table will have the same data structure and data as the result set of the SELECT statement. If a table with the same name already exists, the SELECT INTO statement will raise an error.
In conclusion, the SQL SELECT INTO statement is a useful tool for creating new tables from existing tables in a database. It's a quick and easy way to create a new table with the same data structure and data as an existing table.
SQL SELECT INTO Statement with WHERE Clause
The SQL SELECT INTO statement can be combined with a WHERE clause to create a new table that only includes data that satisfies a specific condition. The WHERE clause can be used to filter the data that will be inserted into the new table.
| OrderID | CustomerID | 
|---|---|
| 1 | 10 | 
| 2 | 20 | 
| 3 | 30 | 
To create a new table NewOrders with only the orders where CustomerID is equal to 20, we can use the following SELECT INTO statement:
1SELECT * INTO NewOrders 2FROM Orders 3WHERE CustomerID = 20;
The output of the above query will be:
| OrderID | CustomerID | 
|---|---|
| 2 | 20 | 
As we can see from the output, the SELECT INTO statement with a WHERE clause creates a new table NewOrders that only includes the order where CustomerID is equal to 20.