I have this query:
SELECT Q_ID,
Q_DESC,
COUNT(Q_ID)
FROM #tmp_rep
LEFT OUTER JOIN po_Questions po
ON Q_ID = Certificate AND FUNCS = 1
AND LEN(LTRIM(RTRIM(po.UserName))) > 0
AND LEN(LTRIM(RTRIM(po.UserNumber))) > 0
GROUP BY
Q_ID,
Q_DESC
ORDER BY
Q_ID
the table #tmp_rep has 2 columns(Q_ID,Q_Desc) and 4 rows.and table po_Questions has 10 that use 3 Q_ID code in column Certificate rows. If I run this query every thing is ok and for Q-ID=4 I get 0 for count,but If I wrote that query this way:
SELECT Q_ID,
Q_DESC,
COUNT(Q_ID)
FROM #tmp_rep
LEFT OUTER JOIN po_Questions po
ON Q_ID = Certificate
WHERE FUNCS = 1
AND LEN(LTRIM(RTRIM(po.UserName))) > 0
AND LEN(LTRIM(RTRIM(po.UserNumber))) > 0
GROUP BY
Q_ID,
Q_DESC
ORDER BY
Q_ID
then I get just 3 rows in the result and Q_ID=4 does not belong to result.Why SQL Server has this behaivior?
thanks
For the non matching rows
po.UserNamewill beNULLsoLEN(LTRIM(RTRIM(po.UserName)))isNULLNULL > 0evaluates toUNKNOWNnotTRUEso when the predicate is in theWHEREyou are turning your outer join back into an inner one. Similarly forFUNCSas SQLMenace points out.You might want to Download Itzik Ben Gan’s Logical Query Processing poster.
Conceptually the following happens (this should not be confused with how it is physically implemented however!)
For your first query:
#tmp_rep,po_QuestionsON Filteris applied which effectively does anINNER JOINonQ_ID = Certificatebut also excludes anypo_Questionsrows that don’t match your predicate.OuterRows from#tmp_repare added back in. These will haveNULLfor all columns frompo_QuestionsWHEREclause so this is the final result.For your second query:
#tmp_rep,po_QuestionsON Filteris applied which effectively does anINNER JOINonQ_ID = Certificate.OuterRows from#tmp_repare added back in. These will haveNULLfor all columns frompo_QuestionsWHEREclause is evaluated. This will definitely remove all rows from the previous step and possibly additional rows too.