I inherited a query that uses left joins. One of the things the query is doing is removing any archived records, that is where archived = 'Y'. This is how the query looks:
select P.firstname, E.entityid, C.committeeid, L.locationname
from Pract P
left join Committee C
on P.commiteeid = C.committeeid
and c.archived = 'N'
left join Entity E
on P.entityid = E.EntityID
and e.archived = 'N'
left join Location L
on E.location = L.location
and l.archived = 'N'
The result should only return records where archived <> 'Y'. I think a problem with putting the filter with the "on" is that it will return a record where c.archived = 'N' and just put a null in the archived field, which is not correct:
FirstName EntityID CommitteeId
John 55 null
If c.archived = 'Y' then the record should not show up.
I believe the archived filter should be in the where clause, like this:
select firstname, entityid, committeeid
from Pract P
left join Committee C
on P.commiteeid = C.committeeid
left join Entity E
on P.entityid = E.entityid
left join Location L
on E.Locationid = L.locationid
where c.archived = 'N'
and e.archived = 'N'
and l.archived = 'N'
The problem I'm finding is that there are instances where the archived field from Committee is null(it's not a 'Y' or an 'N'). Using my solution incorrectly eliminates the records since null <> 'N.'
If I try this:
where c.archived <> 'Y'
it does not work, I'm guessing because NULL does not evaluate to anything.
If I try this:
where (c.archived = 'N' or c.archived is null)
it doesn't work as it now brings back those null records caused by the left join. I can't replace the left join with an inner join because that will exclude records where c.committeeid is null.
I just want to bring back records where archived <> 'Y', which includes those where the field is null.
To be clear, this is what the records in the table can look like:
FirstName EntityID Archived
John 55 Y
Tom 56 NULL
Rob 57 N
In this instance I want the returned records to look like:
Tom 56 NULL
Rob 57 N
John would be eliminated because Archived = 'Y.'
Is there another way to do this?