Escolar Documentos
Profissional Documentos
Cultura Documentos
Note: A select can be more than just a SELECT. What that means is the word
select in lowercase is used in this book to refer to a query that returns a result
set. Every query or select involves at least one SELECT keyword, written in
uppercase in this book. However, a select may involve more than one SELECT, as
shown in the example above. For more information about queries, see Chapter
3, Selecting.
The result set from the SELECT in an INSERT statement is completely materi-
alized before any rows are inserted. If the target table itself is named in any
clauses of the SELECT, only those rows that already exist in the table will affect
the result set produced by the SELECT. The example below illustrates the point.
The final INSERT statement copies values from t2.non_key_1 into t1.key_1,
and the WHERE clause specifies that only values that dont already exist are to
be selected. This is an attempt to prevent any duplicate values from being
inserted into t1.key_1. It works okay for the value 1 because it already exists in
t1.key_1, but not for the value 2 because it doesnt exist in t1.key_1 before the
INSERT is started, and the statement fails with the error Primary key for table
't1' is not unique because there are two rows in t2 with the value 2.
CREATE TABLE t1 (
key_1 INTEGER NOT NULL PRIMARY KEY );
INSERT t1 VALUES ( 1 );
CREATE TABLE t2 (
key_1 VARCHAR ( 10 ) NOT NULL PRIMARY KEY,
non_key_1 INTEGER NOT NULL );
INSERT t1
SELECT t2.non_key_1
FROM t2
WHERE NOT EXISTS ( SELECT *
FROM t1
WHERE t1.key_1 = t2.non_key_1 );