Oracle SQL Select: If not exist, leave blank

1

I have two tables:

Table1
[ID]   [Number]
1      40
2      100
3      7

and

Table2
[ID]   [Number]   [Name]
1      40         A
3      7          C

Data originates in Table1, then gets copied to Table2 (with an added Name) after some processes are completed. I'm trying to SELECT everything in Table1 while also showing the Name field from Table2, if it exists. If the Name field doesn't exist (or more correctly, if the ID doesn't yet exist in Table2), I want to leave the field blank.

Desired output:

[ID]   [Number]   [Name]
1      40         A
2      100
3      7          C

Attempt:

SELECT Table1.ID,Table1.Number,Table2.Name
WHERE Table1.ID=Table2.ID

My current attempts have completely omitted [ID] 2 since the statement I'm trying is looking for the ID in both tables and only finds it in Table1. My guess is I may need to use COALESCE, ISNULL, or a JOIN, all of which are foreign to me. Are any of these (or combination of many) the right tools for the job? Is there a way I can include the Name field only if it exists, and otherwise leave it blank?

root

Posted 2014-09-11T12:19:04.353

Reputation: 2 992

Answers

2

To achieve your desired result you have to use an outer join (example in Syntax valid since Oracle 9i):

SELECT
  Table1.ID,
  Table1.Number,
  Table2.Name
FROM Table1
OUTER JOIN Table2
  ON Table1.ID = Table2.ID

Update

To explain things a bit more (as mentioned by duDE):

The join used in the question is called equi-join, this means that only rows in Table1 are selected that also exists in Table2 (and vice versa).

The outer join selects all rows contained in Table1 and joins all matching rows from Table2. If Table2 does not contain a matching row then null is returned for all columns.

Uwe Plonus

Posted 2014-09-11T12:19:04.353

Reputation: 1 354

With a small explanation of OUTER JOIN would be the perfect answer, smth like "An outer join is a join similar to the equi join, but Oracle will also return non matched rows from the table. " . Nevertheless +1 from me :) – duDE – 2014-09-11T12:29:07.083