Home >Database >Mysql Tutorial >Why Does My T-SQL LEFT JOIN Return Fewer Rows Than Expected?

Why Does My T-SQL LEFT JOIN Return Fewer Rows Than Expected?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-04 02:36:40294browse

Why Does My T-SQL LEFT JOIN Return Fewer Rows Than Expected?

T-SQL Left Join Not Yielding Expected Results

In this inquiry, a LEFT JOIN operation between two tables, #appSteps and #appProgress, is not returning the desired result set. The intended result set contains three rows, but the actual result has only two.

The provided SQL query is as follows:

select p.appId, s.stepId, s.section, p.start
from #appSteps s with (nolock)
left join #appProgress p on s.stepId = p.stepId
where s.section is not null
and p.appId = 101

The issue stems from the inclusion of the right-hand table (#appProgress) in the WHERE clause. To rectify this, the condition should be moved to the ON condition of the LEFT JOIN:

Select    P.appId, S.stepId, S.section, P.start
From      #appSteps    S   With (NoLock)
Left Join #appProgress P   On  S.stepId = P.stepId 
                           And P.appId = 101
Where     S.section Is Not Null

This modification ensures that the WHERE clause is evaluated after the LEFT JOIN, preventing the filtering out of NULL results from the join. By placing the condition in the ON clause, the LEFT JOIN effectively behaves as intended, returning all rows from the left-hand table (#appSteps) with matching rows in the right-hand table (#appProgress) and NULLs for unmatched rows.

The above is the detailed content of Why Does My T-SQL LEFT JOIN Return Fewer Rows Than Expected?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn