I have to write a LEFT JOIN query of find the records that do exist in one table and exists in other table (standard use for left join). There is only one table in this one for the join.
Table name: products
Join condition column: prdname
Two where clause conditions: subdivision='abc', subdivision='xyz'
Objecttive
With these two where clauses I will get two results containing prdname of two sets, I have to find prdname which exits in one but does not in another.
When I wrote the standard LEFT JOIN (case 2 below), it does not give any results that were incorrect so I wrote a subquery to check the results. It was 8 records so I decided to modify the query to case1 down here, and it worked.
My doubt is that both of them are pretty much the same so why second is incorrect?
Can any one help me?
Also, abc and xyz are random values so bother about them much.
Case in which It is working:
SELECT a.prdname
FROM products a
LEFT OUTER JOIN (SELECT prdname
FROM products
WHERE subdivision = 'xyz') b
ON a.prdname = b.prdname
WHERE a.subdivision = 'abc'
AND b.prdname IS NULL
Case in which it is not working
SELECT DISTINCT( a.prdname )
FROM products a
LEFT OUTER JOIN products b
ON a.prdname = b.prdname
WHERE a.subdivision = 'abc'
AND b.subdivision = 'xyz'
AND b.prdname IS NULL
Subquery Query to test
SELECT DISTINCT( prdname )
FROM products
WHERE subdivision = 'abc'
AND prdname NOT IN (SELECT DISTINCT prdname
FROM products
WHERE subdivision = 'xyz')
By adding a
WHEREcondition on columns of the “outer” table you are essentially turning the outer join into an inner join because those rows that do not satisfy the join criteria will have aNULLvalue in those columns. And the comparison withNULLremoves those rows from the result.You need to move that condition into the JOIN clause:
To make things a bit clearer, here is a simplified example.
Assuming the following tables:
Person
Vehicle
Now fetch all people and their vehicles:
This returns the following:
Now think about what happens when you add
to the query. The two rows where vehicle_car is null won’t satisfy that condition and thus are removed from the result.
Now to your real question:
To find products with subdivision ‘abc’ which do not exist in subdivision ‘xyz’ you can use the except operator:
(For Oracle you must replace
exceptwithminus)