In addition to inserting into existing tables, SELECT can
use an INTO clause to create a table and place all of its
output into the new table. For example, suppose we want to create
a new table called newfriend that is just like our friend
table but lacks an age column. This task is easily done with
the query shown in Figure .
test=> SELECT firstname, lastname, city, state
test-> INTO newfriend
test-> FROM friend;
SELECT
test=> \d newfriend
Table "newfriend"
Attribute | Type | Extra
-----------+----------+-------
firstname | char(15) |
lastname | char(20) |
city | char(15) |
state | char(2) |
test=> SELECT * FROM newfriend ORDER BY firstname;
firstname | lastname | city | state
-----------------+----------------------+-----------------+-------
Dean | Yeager | Plymouth | MA
Dick | Gleason | Ocean City | NJ
Ned | Millstone | Cedar Creek | MD
Sandy | Gleason | Ocean City | NJ
Sandy | Weber | Boston | MA
Victor | Tabor | Williamsport | PA
(6 rows)
The SELECT...INTO query performs three operations:
SELECT...INTO tablename can also be written as CREATE TABLE tablename AS SELECT.... The preceding query can then be rewritten as CREATE TABLE newfriend AS SELECT firstname, lastname, city, state FROM friend.