📜  PostgreSQL – SELECT INTO(1)

📅  最后修改于: 2023-12-03 15:18:38.496000             🧑  作者: Mango

PostgreSQL - SELECT INTO

Introduction

In PostgreSQL, SELECT INTO statement is used to create a new table from the result of a SELECT statement. The new table contains the columns that are specified in the SELECT statement.

The syntax of SELECT INTO statement is as follows:

SELECT {column1 [, column2, column3, ...]}
INTO new_table_name
FROM table_name
[WHERE condition];
  • column1, column2, column3, ... - the columns that you want to copy from the source table to the new table.
  • new_table_name - the name of the table that you want to create.
  • table_name - the name of the source table.
  • WHERE condition - the condition to be applied to the records in the source table.
Examples
Example 1 - Create a new table from an existing table

Suppose we have a table called employees with the following columns and data:

id   | name  | age | department
-----+-------+-----+-----------
1    | John  | 25  | IT
2    | Jane  | 30  | Marketing
3    | Peter | 40  | Finance

We can create a new table called employees_copy with only the columns id, name, and age using the following SELECT INTO statement:

SELECT id, name, age
INTO employees_copy
FROM employees;

Now, we have a new table called employees_copy with the following columns and data:

id   | name  | age
-----+-------+-----
1    | John  | 25
2    | Jane  | 30
3    | Peter | 40
Example 2 - Include a WHERE condition

Suppose we want to create a new table called marketing_employees that only contains the employees who work in the Marketing department from the employees table.

SELECT id, name, age
INTO marketing_employees
FROM employees
WHERE department = 'Marketing';

Now, we have a new table called marketing_employees with the following columns and data:

id   | name  | age
-----+-------+-----
2    | Jane  | 30
Conclusion

In conclusion, the SELECT INTO statement in PostgreSQL is a powerful tool that allows you to create a new table based on the result of a SELECT statement. It is useful for creating ad hoc tables from existing tables or for filtering data using a WHERE condition.