In SQL, EXISTS is slightly more powerful than IN #150
Replies: 2 comments
-
The In that mixed style, people need a way to write a predicate and then work backwards, figuring out the set of arguments for which the predicate might be true. The We considered asking people to write
but it would be intimidating to ask people to work with infinite sets of values, and it is unnecessary to specify the type
|
Beta Was this translation helpful? Give feedback.
-
Oso on twitter remarked that lack of types makes code difficult to understand. You can use type annotations if you wish:
|
Beta Was this translation helpful? Give feedback.
-
In SQL, any query that uses
IN
can be converted into an equivalent one that usesEXISTS
. For example,is equivalent to
The two solutions match relational algebra and relational calculus styles of thinking:
IN
formulation is relational algebra, which is closer to how the query is evaluated by typical engines, and tends to map fairly directly onto efficient join operatorsEXISTS
formulation is relational calculus, which is closer to logic. As is typical, theEXISTS
query is correlated: there is a reference toe.deptno
inside the subquery. It will need to be decorrelated, to something like theIN
query, in order to be executed efficiently.But not every
EXISTS
query can be converted toIN
. Consider this:The problem is that we need to generate the list of integers values that are higher than each
deptno
value from theDept
table. In pseudo-syntax, it would look like this:We have invented the
EXTENT
operator for this example. Its argument is a data type, and it generates the set of values of that data type.EXTENT(INTEGER)
generates the set of all values of theINTEGER
data type.Clearly, it's impossible to implement
EXTENT
(it would return an unbounded set of values), but in this case we see thati
is restricted to the values of thedeptno
column of theDept
table. So we can write the following:Beta Was this translation helpful? Give feedback.
All reactions