The EXISTS keyword
The keyword
EXISTS is known as an existential qualifier because the
subquery is true only if the outer SELECT, as the following query
shows, finds at least one row.
You can often construct a query with EXISTS that is equivalent
to one that uses IN. The following query uses an IN predicate to construct
a query that returns the same result as the query above.
Query and Query return rows for the manufacturers
that produce a kind of shoe, as well as the lead time for ordering
the product. The result shows the return values.
Add the keyword NOT to IN or to EXISTS to create a search condition that is the opposite of the condition in the preceding queries. You can also substitute !=ALL for NOT IN.
The following query shows two ways to do the same thing.
One way might allow the database server to do less work than the other,
depending on the design of the database and the size of the tables.
To find out which query might be better, use the SET EXPLAIN command
to get a listing of the query plan. SET EXPLAIN is discussed in your HCL OneDB™ Performance
Guide and HCL OneDB Guide to SQL:
Syntax.
Each statement in the query above returns the following
rows, which identify customers who have not placed orders.
The keywords EXISTS and IN are used for the set operation known as intersection, and the keywords NOT EXISTS and NOT IN are used for the set operation known as difference. These concepts are discussed in Set operations.
The
following query performs a subquery on the items table to identify
all the items in the stock table that have not yet been ordered.
The query returns the following rows.
No logical limit exists to the number of subqueries a SELECT statement can have.
Perhaps
you want to check whether information has been entered correctly in
the database. One way to find errors in a database is to write a query
that returns output only when errors exist. A subquery of this type
serves as a kind of audit query, as the following query
shows.
The query returns only those rows for which the total
price of an item on an order is not equal to the stock unit price
times the order quantity. If no discount has been applied, such rows
were probably entered incorrectly in the database. The query returns
rows only when errors occur. If information is correctly inserted
into the database, no rows are returned.