3

I have two tables (fruit_cost and fruit_availability) in oracle database, details below:

fruit_cost looks like this:

fruit_name | fruit_cost
apple | 30
orange | 7
melon | 14

fruit_availability looks like this:

fruit_name | fruit_availability
table is empty

is there any good option to get results like these:

fruit_name | fruit_cost | fruit_availability
apple | 30 | null
orange | 7 | null
melon | 14 | null

3 Answers 3

7

You can just join the tables using a LEFT JOIN.

A LEFT JOIN will return all records in the fruit_cost table regardless of whether there is a matching record in the fruit_availability table. Your query will look like this:

select fc.fruit_name, 
  fc.fruit_cost,
  fa.fruit_availability
from fruit_cost fc
left join fruit_availability fa
  on fc.fruit_name = fa.fruit_name

See SQL Fiddle with Demo

The result is:

| FRUIT_NAME | FRUIT_COST | FRUIT_AVAILABILITY |
------------------------------------------------
|      melon |         14 |             (null) |
|     orange |          7 |             (null) |
|      apple |         30 |             (null) |

If you need help learning join syntax here is a great visual explanation of joins.

Sign up to request clarification or add additional context in comments.

6 Comments

@constantine while the syntax in the other answer is valid for oracle only, Oracle does recommend that you use OUTER JOIN syntax rather than the join operator. Here is a question explaining -- stackoverflow.com/questions/1193654/…
Thanks for Your explanations, they were very helpful.
One more question to You, should I use LEFT JOIN or LEFT OUTER JOIN in my case (ORACLE DB) and what's the difference between these two syntaxes?
I have found this: link but the article applies to MSSQL not ORACLE and that is why I'm still trapped :). Please help.
@constantine The OUTER is not required syntax when using a JOIN
|
4

Oracle syntax:

select *
from fruit_cost fc, fruit_availability fa
where fc.fruit_name = fa.fruit_name (+);

SQL Fiddle here.

1 Comment

Best and shortest result 4 my solution. Thanks!
0
select c.fruit_name, c.fruit_cost, a.fruit_availability
from fruit_cost c 
   left outer join on fruit_availability a on
   c.fruit_name = a.fruit_name
order by c.fruit_name

1 Comment

select c.fruit_name, c.fruit_cost, a.fruit_availability from fruit_cost c left outer join fruit_availability a on c.fruit_name = a.fruit_name order by c.fruit_name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.