Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have two tables: MAINCOLOR and SUBCOLOR with the data as:

1       RED
2       BLUE
3       GREEN

1     1      PINK     0
2     1      ORANGE   1
3     2      VIOLET   1

I need a result set as:

1       RED     ORANGE
2       BLUE    VIOLET
3       GREEN

Resultset should be a join of MAINCOLOR and SUBCOLOR using MAINID. Need child data having status as 1.

share|improve this question
up vote 3 down vote accepted

You can get the result by using a LEFT JOIN between the maincolor and the subcolor.

The key is placing the filter of status=1 on the JOIN condition. Your code will be:

select m.mainid,
from maincolor m
left join subcolor s
  on m.mainid = s.mainid
  and s.status = 1

See SQL Fiddle with Demo.

The LEFT JOIN will return all rows from the maincolor table and any matching rows in the subcolor table. Since you what to apply a WHERE to the data in the subcolor table, then you will want to move that filter to the JOIN condition to get the result.

share|improve this answer
Hurray. It worked. I was trying with a where clause, not resulting the required result. Thanks bluefeet. – Praveen Prasannan Mar 11 '13 at 11:24

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.