Take the 2-minute tour ×
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. It's 100% free, no registration required.

I've Table1 and Table2, Table1's PK is the FK of Table2. Now i need to perform a select from Table1 if and only if all the records in Table2 corresponding to a Table1 record has values (if any field value is null then skip).

ie, for an id in Table1 there have multiple sub ids in Table2. Out of those multiple ids if a particular field corresponds to any one id is null then select should be skipped.

Any one please help me out to write a single sql query for this requirement.

share|improve this question
1  
I think I understand what you mean, but it would be much clearer if you provided example data and expected output. –  Mat Nov 3 '12 at 12:27
    
And if a parent row (at Table1) is not related to any child row (at Table2), it should be shown, correct? –  ypercube Nov 3 '12 at 12:51

2 Answers 2

up vote 3 down vote accepted

This is called an "anti-join" (or anti-semijoin). One way to write it in SQL is to use the NOT EXISTS construction:

SELECT t1.*
FROM Table1 AS t1
WHERE NOT EXISTS
      ( SELECT *
        FROM Table2 AS t2
        WHERE t2.FKcolumn = t1.PKcolumn
          AND t2.columnX IS NULL
      ) 

If - as your comment - you want a parent row (at Table1) not related to any child row (at Table2), to NOT be shown, add this (or join Table2 if you also want columns from the second table shown):

  AND EXISTS
      ( SELECT *
        FROM Table2 AS t2
        WHERE t2.FKcolumn = t1.PKcolumn
      ) 
share|improve this answer
    
,Thanks...Also if a parent row (at Table1) is not related to any child row (at Table2), it should NOT be shown. The query is working for the other case. I used join along with your query to link both table1 and table2 and got the desired result. –  Harun Nov 3 '12 at 13:40
select t1.* from table1 t1
where exists(select 1 from table2 t2 where t2.FKcolumn = t1.PKcolumn 
             having count(*)=count(t2.columnX) and count(*)>0)
share|improve this answer

Your Answer

 
discard

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.