Wednesday, December 18, 2024

SQL SELECT INTO Statement

 The SELECT INTO statement in SQL is used to select data from one table and insert it into a new table. The new table will be created automatically with the structure based on the result set of the SELECT query.

Syntax:

SELECT column1, column2, ...
INTO new_table
FROM existing_table
WHERE condition;
  • column1, column2, ...: The columns you want to select.
  • new_table: The name of the new table that will be created.
  • existing_table: The name of the table you're selecting data from.
  • WHERE condition: (Optional) A condition to filter the rows.

Example 1: Basic Usage

Create a new table new_table by selecting all columns from old_table:

SELECT * 
INTO new_table
FROM old_table;

Example 2: Select with a Condition

Create a new table filtered_table from employees, selecting only the employees with a salary greater than 50000:

SELECT employee_id, name, salary
INTO filtered_employees
FROM employees
WHERE salary > 50000;

Notes:

  • The SELECT INTO statement does not copy indexes, constraints, or primary keys from the original table.
  • If the new table (new_table) already exists, you'll get an error. Use INSERT INTO to add data into an existing table instead.

No comments:

Post a Comment