There are always multiple ways to write the same thing in SQL. For example this
SELECT * FROM
(SELECT A,B FROM Table_1) T1
...may be rewritten as this:
SELECT A, B
FROM Table_1
The latter is simpler and I see no reason to prefer the former. Rewriting your first query accordingly
SELECT A, B
FROM Table_1
WHERE EXISTS (
SELECT 'X'
FROM Table_1
WHERE A = 3
);
I've removed the correlation name T1
because it server no purpose. The subquery does not reference its 'outer' table expression so each appearance Table_1
does not need to be disambiguated.
I think you understand what is going on here: if one or more rows in Table_1
satisfy the search condition A = 3
then the entire table is returned, otherwise the empty set is returned. While it is a valid query it is not often a very useful construct.
For your second query, however, at least one correlation name is required because the subquery does reference its outer table:
SELECT A, B
FROM Table_1 T1
WHERE EXISTS (
SELECT 'X'
FROM Table_1 T2
WHERE T1.A IN (3, 4)
);
Again this is semantically equivalent to your second query. Note that I've given the apperance of Table_1
in the subquery the correlation name T2
but T2
does not appear in the subquery's WHERE
clause. Because T2
is not being used, we can remove the subquery (hence the need for correlation names) entirely:
SELECT A, B
FROM Table_1
WHERE A IN (3, 4);
It's worth pointing out that the ability for a subquery to reference an 'outer' table expression is usually exploited as a 'correlated subquery' i.e. the search condition (WHERE
clause) involves both 'inner' and 'outer' tables (your second query's search condition involves the 'outer' table only).
Using the usual parts and suppliers database, here is an example of a correlated subquery to implement a semijoin to find suppliers (S
) who supply (SP
) at least one part:
SELECT SNO, SNAME
FROM S
WHERE EXISTS (
SELECT *
FROM SP
WHERE SP.SNO = S.SNO
);
Note the subquery's search condition relates the 'outer' table SP
to the 'inner' table S
. Also, the projection SELECT SNO, SNAME
in the 'outer' table does not require the inclusion of the correlation name S
because SP
from the 'outer' table is not in scope for the 'inner' table.