PostgreSQL Tutorial

Data Types

Querying & Filtering Data

Managing Tables

Modifying Data

Conditionals

Control Flow

Transactions & Constraints

Working with JOINS & Schemas

Roles & Permissions

Working with Sets

Subquery & CTEs

User-defined Functions

Important In-Built Functions

PostgreSQL PL/pgSQL

Variables & Constants

Stored Procedures

Working with Triggers

Working with Views & Indexes

Errors & Exception Handling

PostgreSQL - Select Into

The SELECT INTO statement in PostgreSQL is used to create a new table and populate it with the results of a query. The new table will have columns that match the expressions in the SELECT statement, and it gets filled with the result set of that query. Essentially, SELECT INTO creates a new table from the results of a query.

Basic Syntax:

SELECT column1, column2, ...
INTO new_table
FROM existing_table
WHERE conditions;
  • column1, column2, ...: Columns that you want to select and insert into the new table.

  • new_table: The name of the new table you want to create.

  • existing_table: The name of the table from which you're pulling data.

  • WHERE conditions: Optional conditions to filter the rows that you want to insert into the new table.

Examples:

  1. Create a new table with all columns and rows from an existing table:

    SELECT *
    INTO employees_backup
    FROM employees;
    

    This would create a new table named employees_backup and copy all rows and columns from the employees table into it.

  2. Create a new table with specific columns:

    SELECT first_name, last_name
    INTO employee_names
    FROM employees;
    

    This would create a new table named employee_names and insert the first_name and last_name columns from the employees table.

  3. Create a new table with rows based on a condition:

    SELECT *
    INTO hr_employees
    FROM employees
    WHERE department = 'HR';
    

    This would create a new table named hr_employees and copy all rows from the employees table where the department is 'HR'.

Notes:

  • The SELECT INTO statement creates a new table without any constraints, indexes, defaults, or other properties of the original table. If you need those, you'll have to define them manually on the new table.

  • The new table created with SELECT INTO is a regular table, so it persists beyond the session. If you want a temporary table, you might use the CREATE TEMP TABLE or CREATE TEMPORARY TABLE commands.

  • Another similar command in PostgreSQL is CREATE TABLE AS, which offers functionality akin to SELECT INTO.

  • In some SQL databases, the syntax and behavior of SELECT INTO might differ. For example, in SQL Server, SELECT INTO is used for both creating a new table and inserting data into an existing table.

In PostgreSQL, the SELECT INTO command is handy when you need to quickly create a new table based on the results of a SELECT query.