1
votes

Is it possible to write a sql query where you know you have to use the left outer join..but cannot or are not allowed to use the "outer join" Key Word

I have two table sand want to get rows with null vaues from the left table ...this is pretty simple ...but am not supposed to use the key word....outer join....I need to right the logic for outer join myself

5
Why is this requirement? May be you should explain what you are trying to do first. - CoolBeans
Are you trying to write the equivalent to LEFT OUTER JOIN without using those SQL keywords? - ThomasMcLeod
If this is homework, please use homework tag. - ThomasMcLeod
If it's homework, add the homework tag. It attracts attention. Also, show us what you've already tried. you'll learn a lot from comments on your best efforts. - Mike Sherrill 'Cat Recall'
@abbas - SQL is a relational database system, which means it works by JOINing tables together. Not being able to use JOIN means you may as well not be using a Relational Database. - JNK

5 Answers

3
votes
SELECT Field1 
FROM table1 
WHERE id NOT IN (SELECT id FROM table2)

SELECT Field1 
FROM table1 
WHERE NOT EXISTS (SELECT * FROM table2 where table2.id = table1.id)

This is something people do but it is deprecated and it does not currently work correctly (it sometimes will return a cross join instead of a left join) so it should NOT be used. I'm telling this only so you avoid using this solution.

SELECT Field1 
FROM table1, table2 where table1.id *= table2.id
3
votes
;WITH t1(c,d) AS
(
SELECT 1,'A' UNION ALL 
SELECT 2,'B'
),t2(c,e) AS
(
SELECT 1,'C' UNION ALL 
SELECT 1,'D' UNION ALL 
SELECT 3,'E'
)

SELECT t1.c, t1.d, t2.c, t2.e
FROM t1, t2 
WHERE t1.c = t2.c
UNION ALL
SELECT t1.c, t1.d, NULL, NULL
FROM t1 
WHERE c NOT IN (SELECT c 
                FROM t2 
                WHERE c IS NOT NULL)

Returns

c           d    c           e
----------- ---- ----------- ----
1           A    1           C
1           A    1           D
2           B    NULL        NULL          

(Equivalent to)

SELECT t1.c, t1.d, t2.c, t2.e
FROM   t1
       LEFT JOIN t2
         ON t1.c = t2.c  
0
votes

For SQL Server, you can just use LEFT JOIN - the OUTER is optional, just like INTO in an INSERT statement.

This is the same for all OUTER JOINs.

For an INNER JOIN you can just specify JOIN with no qualifiers and it is interpreted as an INNER JOIN.

0
votes

This will give you all the rows in table A that don't have a matching row in table B:

SELECT * 
FROM A
WHERE NOT EXISTS (
  SELECT 1
  FROM B
  WHERE A.id = B.id
);
0
votes

Returns all the matching rows from both tables:

    SELECT a.*,b.* FROM table_a a, table_b b
    WHERE a.key_field = b.key_field

Potential drawback is non-matches will be skipped.