let's say that there're 2 tables (in oracle SQL) like this:
user(user_id, company_id):
123 | company_id_1 |
123 | company_id_2 |
company(id, version_id):
company_id_1 | (null) |
company_id_2 | version_id1 |
the following query returns 2 rows
company_id_1
company_id_2
SELECT distinct(company_id)
FROM user
WHERE user.user_id = 123
AND user.company_id IS NOT NULL
AND EXISTS
(SELECT 1
FROM company
INNER JOIN user ON company.id = user.company_id AND company.version_id IS NOT NULL);
I would expect there's only 1 result, which is company_id_2, but it returns 2 results (company_id_1, company_id_2)
A couple of other notes:
- the following query does return 1 result for me
SELECT distinct(company_id)
FROM user
WHERE user.user_id = 123
AND user.company_id IS NOT NULL
AND EXISTS
(SELECT 1
FROM company
WHERE company.id = user.company_id AND company.version_id IS NOT NULL);
- what's odd to me is the following statement (running the inner join individually) does return 1 result:
SELECT *
FROM company
INNER JOIN user ON company.id = user.company_id AND company.version_id IS NOT NULL
WHERE company.id IN (company_id_1, company_id_2)
- So why does query with inner join inside exists returns 2 results? even though by running the inner join individually it only returns 1 result, and exists condition should only be evaluated to true for only company_id_2, which has the not-null version_id
- Can you elaborate more on what's the difference between the inner join inside the exists vs the regular where clause inside exists, they both looks the same to me?