Sei sulla pagina 1di 1

Chapter 2: Inserting 53

2.2.3 INSERT Select All Columns


If you want to insert data into a table by copying data that already exists some-
where else, you can use a select instead of a VALUES list. The simplest form
uses a select that provides values for every column in the table.
<insert_select_all_columns> ::= INSERT [ INTO ]
[ <owner_name> "." ] <target_table_name>
[ <on_existing> ]
<select_all_columns>
<select_all_columns> ::= <select> -- values for all the columns in the target table
<select> ::= see <select> in Chapter 3, "Selecting"
INSERT statements using a select have two main advantages over ones that use
a VALUES list. First, you can insert more than one row with a single INSERT.
Second, you can insert data without specifying explicit values.
Here is an example where all the rows and columns in t1 are copied into t2:
CREATE TABLE t1 (
key_1 INTEGER NOT NULL DEFAULT AUTOINCREMENT,
non_key_1 VARCHAR ( 100 ) NOT NULL DEFAULT 'xxx',
last_updated TIMESTAMP NOT NULL DEFAULT TIMESTAMP,
PRIMARY KEY ( key_1 ) );

CREATE TABLE t2 (
key_1 INTEGER NOT NULL DEFAULT AUTOINCREMENT,
non_key_1 VARCHAR ( 100 ) NOT NULL DEFAULT 'xxx',
last_updated TIMESTAMP NOT NULL DEFAULT TIMESTAMP,
PRIMARY KEY ( key_1 ) );

INSERT t2
SELECT key_1, non_key_1, last_updated
FROM t1;
Since the two tables above have exactly the same number of columns in the
same order, the INSERT could be even simpler:
INSERT t2 SELECT * FROM t1;

Tip: This form of INSERT is very popular for loading data from external
sources via proxy tables (e.g., INSERT local_table SELECT * FROM proxy_table).
For more information about proxy tables, see Section 1.14, Remote Data
Access.

Heres the rule you must follow: The select must return the same number of col-
umns as exist in the target table, with the same or compatible data types in the
same order as they exist in the CREATE TABLE for the target table. In other
words, if the result set fits, it will be inserted.
As long as you follow that rule you can use all of the sophisticated features
described in Chapter 3, Selecting, when coding an INSERT. Heres an exam-
ple that uses a UNION to add two more rows to the ones selected from t1:
INSERT t2
SELECT 0, 'first', '2001-01-01'
UNION
SELECT * FROM t1
WHERE key_1 BETWEEN 1 AND 9998
UNION
SELECT 9999, 'last', CURRENT TIMESTAMP;

Potrebbero piacerti anche