PostgreSQL Tutorial: SELECT INTO

August 2, 2023

Summary: in this tutorial, you will learn how to use the PostgreSQL SELECT INTO statement to create a new table from the result set of a query.

Table of Contents

If you are looking for the way to select data into variables, check it out the PL/pgSQL SELECT INTO statement.

Introduction to PostgreSQL SELECT INTO statement

The PostgreSQL SELECT INTO statement creates a new table and inserts data returned from a query into the table.

The new table will have columns with the names the same as columns of the result set of the query. Unlike a regular SELECT statement, the SELECT INTO statement does not return a result to the client.

The following illustrates the syntax of the PostgreSQL SELECT INTO statement:

SELECT
    select_list
INTO [ TEMPORARY | TEMP | UNLOGGED ] [ TABLE ] new_table_name
FROM
    table_name
WHERE
    search_condition;

To create a new table with the structure and data derived from a result set, you specify the new table name after the INTO keyword.

The TEMP or TEMPORARY keyword is optional; it allows you to create a temporary table instead.

The UNLOGGED keyword if available will make the new table as an unlogged table.

The WHERE clause allows you to specify the rows from the original tables that should be inserted into the new table. Besides the WHERE clause, you can use other clauses in the SELECT statement for the SELECT INTO statement such as INNER JOIN, LEFT JOIN, GROUP BY, and HAVING.

Note that you cannot use the SELECT INTO statement in PL/pgSQL because it interprets the INTO clause differently. In this case, you can use the CREATE TABLE AS statement which provides more functionality than the SELECT INTO statement.

PostgreSQL SELECT INTO examples

We will use the film table from the sample database for the demonstration.

PostgreSQL SELECT INTO sample table

The following statement creates a new table called film_r that contains films with the rating R and rental duration 5 days from the film table.

SELECT
    film_id,
    title,
    rental_rate
INTO TABLE film_r
FROM
    film
WHERE
    rating = 'R'
AND rental_duration = 5
ORDER BY
    title;

To verify the table creation, you can query data from the film_r table:

SELECT * FROM film_r;

img

The following statement creates a temporary table named short_film that contains the films whose lengths are under 60 minutes.

SELECT
    film_id,
    title,
    length 
INTO TEMP TABLE short_film
FROM
    film
WHERE
    length < 60
ORDER BY
    title;

The following shows the data from the short_film table:

SELECT * FROM short_film;

img

In this tutorial, you have learned how to use the PostgreSQL SELECT INTO statement to create a new table from the result set of a query.