9

If i write a sql:

select * 
from a,b 
where     a.id=b.id(+) 
      and b.val="test"

and i want all records from a where corresponding record in b does not exist or it exists with val="test", is this the correct query?

mkb
  • 1,106
  • 1
  • 18
  • 21
Victor
  • 16,609
  • 71
  • 229
  • 409

4 Answers4

22

You're much better off using the ANSI syntax

SELECT *
  FROM a
       LEFT OUTER JOIN b ON( a.id = b.id and
                             b.val = 'test' )

You can do the same thing using Oracle's syntax as well but it gets a bit hinkey

SELECT *
  FROM a, 
       b
 WHERE a.id = b.id(+)
   AND b.val(+) = 'test'

Note that in both cases, I'm ignoring the c table since you don't specify a join condition. And I'm assuming that you don't really want to join A to B and then generate a Cartesian product with C.

Justin Cave
  • 227,342
  • 24
  • 367
  • 384
  • Is this correct: SELECT * FROM a, b WHERE a.id = b.id(+) AND b.val(+) = 'test' and b.col2(+) = 'test2'; I wish to get all rows from a if corresponding row in b is null or corresponding row in b has col2='test2' and val = 'test' So, it is either null OR (col2='test2' AND val = 'test') – Victor Aug 23 '13 at 13:18
1

Move the condition into the JOIN clause and use the ANSI standard join pattern.

SELECT NameYourFields,...
FROM A
LEFT OUTER JOIN B
ON A.ID = B.ID
AND B.VAL = 'test'
INNER JOIN C
ON ...
Declan_K
  • 6,726
  • 2
  • 19
  • 30
0

A LEFT OUTER JOIN is one of the JOIN operations that allow you to specify a join clause. It preserves the unmatched rows from the first (left) table, joining them with a NULL row in the shape of the second (right) table.

So you can do as follows :

SELECT
FROM a LEFT OUTER JOIN b ON a.id = b.id

--Note that you have used double quote "test" which is not used for varchar in SQL you should use single quote 'test'

AND b.val = 'test';

GKP
  • 1,057
  • 1
  • 11
  • 24
-1
SELECT * FROM abc a, xyz b
 WHERE a.id = b.id
   AND b.val = 'test'
teo van kot
  • 12,350
  • 10
  • 38
  • 70
santosh
  • 7
  • 1
  • 1
    Hi and welcome to SO. Thanks for your contribution but it would be extremely helpful if you could expand your answer with a few details about how it answers Victors question. – Deepend Aug 03 '16 at 13:49