T-SQL Tutorial

INTO clause


The INTO clause in SQL Server is used to specify the destination table where the results of a query will be inserted. The INTO clause is used in conjunction with the SELECT statement to create a new table and populate it with data returned by the query.


Syntax

The syntax for the INTO clause is as follows:

SELECT column1, column2, ...
INTO new_table
FROM source_table
WHERE condition;

In this syntax, the SELECT statement retrieves the specified columns from the source table, which can be a table or a view. The INTO keyword specifies the new table that will be created to hold the query results. The name of the new table is specified after the INTO keyword. Finally, the WHERE clause specifies any conditions that the rows must meet to be included in the new table.


Example

For example, suppose we have a table called "employees" with columns "emp_id", "emp_name", and "emp_salary". We want to create a new table called "top_earners" that contains only the employees with salaries greater than $100,000. We can use the following query:

SELECT emp_id, emp_name, emp_salary
INTO top_earners
FROM employees
WHERE emp_salary > 100000;

This query will create a new table called "top_earners" and populate it with the results of the SELECT statement. The new table will contain only the columns specified in the SELECT statement and only the rows that meet the condition specified in the WHERE clause.

It's important to note that the INTO clause creates a new table, and if a table with the same name already exists, it will be overwritten without warning. Additionally, the new table will not have any indexes or constraints, so it's important to add those separately if needed.

In summary, the INTO clause in SQL Server is a useful tool for creating new tables and populating them with data from existing tables. It can be used to create temporary tables for data manipulation or to create permanent tables for storing query results.