Sei sulla pagina 1di 1

118 Chapter 3: Selecting

CREATE TABLE t2 (
key_1 INTEGER NOT NULL REFERENCES t1 ( key_1 ),
key_2 INTEGER NOT NULL,
non_key_1 INTEGER NOT NULL,
PRIMARY KEY ( key_1, key_2 ) );

INSERT t1 VALUES ( 5, 5 );
INSERT t1 VALUES ( 6, 6 );
INSERT t1 VALUES ( 7, 7 );
INSERT t2 VALUES ( 6, 44, 77 );
INSERT t2 VALUES ( 6, 55, 88 );

SELECT *
FROM t1
WHERE EXISTS ( SELECT *
FROM t2
WHERE t2.key_1 = t1.key_1 );
This kind of subquery is often called a correlated subquery or correlated
subselect because it contains a reference to a table in the outer query, and that
outer reference is called a correlation. Heres how it works, logically speak-
ing: For every row in t1 the subquery is evaluated and checked to see if it
returns any rows where t2.key_1 = t1.key_1. If the subquery doesnt return any
rows, the EXISTS predicate returns FALSE and the row from t1 is discarded.
Otherwise, EXISTS returns TRUE and the row from t1 is left alone. This pro-
cess eliminates two of the rows in t1, leaving one behind to produce this final
result set:
key_1 non_key_1
===== =========
6 6
The NOT EXISTS predicate has the opposite effect:
SELECT *
FROM t1
WHERE NOT EXISTS ( SELECT *
FROM t2
WHERE t2.key_1 = t1.key_1 );
In this case, only childless rows from t1 are returned:
key_1 non_key_1
===== =========
5 5
7 7
When you use EXISTS and NOT EXISTS, the subquery select list is immate-
rial. All the query engine has to do is determine if there are any rows in the
subquery result, not what those rows actually are. That means SELECT * is per-
fectly okay and there is no advantage to coding SELECT 1 or anything else.

3.12.3 IN Predicates
The third kind of predicate tests to see if a value exists in a list or a single-
column subquery:
<in_predicate> ::= <expression>
[ NOT ] IN
"(" <expression> "," <expression> { "," <expression> } ")"
| <expression>

Potrebbero piacerti anche