In Microsoft SQL Server (MS SQL), the SELECT INTO
statement is used to create a new table and insert data into it based on the result of a SELECT
query. Here’s a more detailed look at how to use SELECT INTO
in SQL Server:
Basic Syntax
Example
Let's say you have an existing table named employees
and you want to create a new table named high_salaries
that contains employees earning more than $100,000. The SELECT INTO
statement would look like this:
In this example:
employee_id
,first_name
,last_name
, andsalary
are the columns being selected.high_salaries
is the name of the new table that will be created.employees
is the existing table from which data is being selected.- The
WHERE
clause filters rows to include only those where the salary exceeds $100,000.
Points to Consider
-
Table Creation: The
SELECT INTO
statement will create the new tablehigh_salaries
with columns and data types that match those of the selected columns from theemployees
table. -
No Existing Table: If a table named
high_salaries
already exists, theSELECT INTO
statement will fail. You can useINSERT INTO
to add data to an existing table if needed. -
Indexes and Constraints: The new table will not inherit indexes, primary keys, foreign keys, or any constraints from the source table. You will need to add these manually if required.
-
Schema: The new table will be created in the same schema as the table being queried. If you need to specify a different schema, you might need to use explicit
CREATE TABLE
statements or other methods. -
Data Types: Data types of the columns in the new table will be automatically inferred from the data types of the selected columns.
Additional Example
If you need to copy the structure of a table without the data, you can use a TOP 0
clause to select zero rows:
This creates a new table new_table_structure
with the same schema as existing_table
but without any data.
Error Handling
-
Duplicate Table Error: If you try to create a table that already exists, you’ll encounter an error. To avoid this, you might need to drop the table first or use a different name.
-
Permissions: Ensure that you have the required permissions to create tables and perform the
SELECT INTO
operation.
This approach is particularly useful for quickly making backups, creating temporary tables for analysis, or transferring data between tables.