I was wondering if someone could help me understand what this code is doing. I have inhereted a SQL script and I’m trying to update the code so it’s easier to read. I’ve looked at the below code and it seems like there’s an easier way to do this, but I can’t wrap my head around what this code is actually doing. Could anyone help me just describe this code? (Maybe clue me into how to do this with a subquery or EXISTS or an easier way to read this?
SELECT DISTINCT
s.id
,f.FLAG1
,f.FLAG1
,f.FLAG1
INTO #DLK_TEMP
from Inner_Source D
LEFT OUTER JOIN Outer_Source_1 S on D.au = S.AU
AND D.wcv_entity_key = S.wcv_entity_key
LEFT OUTER JOIN Outer_Source_2 F on S.id = F.id
WHERE S.id IS NOT NULL
It seems strange that it’s performing an
LEFT OUTER JOINonSand then testing for those rows where the join succeeds. It should be anINNER JOINinstead. And ifS.IDis not nullable then you can also remove theWHEREclause.If you like, you can change the first join to an
EXISTSclause to make it clear that the join is only acting as a filter: