📅  最后修改于: 2023-12-03 15:18:38.496000             🧑  作者: Mango
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.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
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
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.