Question

SELECT st.state_id, 
       st.state_name, 
       st.country_id 
FROM   state_table st 
WHERE  EXISTS (SELECT 0 / 0 
               FROM   country c 
               WHERE  st.country_id = c.country_id 
                      AND c.country_name = 'India')

This query produces the expected output matching st.country_id = c.country_id. In this query however, 0 / 0, in the inner subquery is expected to be replaced by c.country_id.

The equivalent IN() query would look like the following.

SELECT st.state_id, 
       st.state_name, 
       st.country_id
FROM   state_table st
WHERE  country_id IN(SELECT c.country_id 
                     FROM   country c
                     WHERE  c.country_name = 'India')

It appears that the list of columns in the select clause inside EXISTS() subquery is ignored. Is this true?

Was it helpful?

Solution

It appears that the list of columns in the select clause inside EXISTS() subquery is ignored. Is this true?

Yup! All that matters is how many rows it returns.

(Actually, it wouldn't surprise me if some DBMSes do at least evaluate the field-list, even though the values themselves are discarded. So 0 / 0 may not be portable.)

Addendum: I just tested using sqlfiddle.com, and it appears that MySQL treats 0 / 0 as NULL rather than an error, so that doesn't signify; but even on DMBSes such as Oracle that normally do treat 0 / 0 as an error, the predicate EXISTS (SELECT 0 / 0 ...) was successful. So, maybe it is portable? (Granted, I only tested a handful of DBMSes — one version each of MySQL, PostgreSQL, Oracle, and SQL Server — so I can't make a guarantee.)

OTHER TIPS

It appears that the list of columns in the select clause inside EXISTS() subquery is ignored. Is this true?

Yes, it is.

As per documentation on EXISTS - NOT EXISTS

SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);
Traditionally, an EXISTS subquery starts with SELECT *, but it could begin with SELECT 5 or SELECT column1 or anything at all. MySQL ignores the SELECT list in such a subquery, so it makes no difference.

For the preceding example, if t2 contains any rows, even rows with nothing but NULL values, the EXISTS condition is TRUE. This is actually an unlikely example because a [NOT] EXISTS subquery almost always contains correlations.

Some of references to other DBMS's that explain the same are listed below:

  1. Oracle: Exists and Not Exists with SubQueries
  2. T-SQL Exists
  3. PostgreSQL: Exists
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top