Select Into statement in SQL Server
In SQL Server, the SELECT INTO statement is used to create a new table and populate it with data from an existing table or tables. It allows you to perform a query and store the result set into a new table. Here's the basic syntax for using SELECT INTO:
SELECT column1, column2, ...
INTO new_table
FROM source_table
WHERE condition;
Let's break down the components of the SELECT INTO statement:
-
SELECT column1, column2, ...: Specifies the columns you want to select from the source table.
-
INTO new_table: Specifies the name of the new table that will be created to store the result set.
-
FROM source_table: Specifies the source table or tables from which to retrieve the data.
-
WHERE condition: Optional clause that allows you to specify conditions to filter the rows before populating the new table.
Here are some examples of using SELECT INTO in SQL Server:
1- Create a new table from an existing table:
SELECT *
INTO new_customers
FROM customers
WHERE Country = 'USA';
This example creates a new table called "new_customers" and populates it with all columns and rows from the "customers" table where the country is 'USA'.
2- Create a new table with selected columns:
SELECT FirstName, LastName, City
INTO new_employees
FROM employees
WHERE Department = 'IT';
In this example, a new table called "new_employees" is created, and it contains only the "FirstName," "LastName," and "City" columns from the "employees" table for employees in the IT department.
3- Create a new table with joined data:
SELECT c.CustomerID, o.OrderDate, o.TotalAmount
INTO new_orders
FROM customers AS c
JOIN orders AS o ON c.CustomerID = o.CustomerID
WHERE o.Status = 'Completed';
This example creates a new table called "new_orders" by joining the "customers" and "orders" tables. It selects the customer ID, order date, and total amount for completed orders and populates the new table with the result.
The SELECT INTO statement in SQL Server is a convenient way to create a new table and populate it with data from an existing table or tables. It allows you to perform transformations or filtering on the data before storing it in the new table. However, keep in mind that the new table will have the same structure as the result set, including data types and column names, based on the selected columns in the query.