Search code examples
sqlsql-serverssmsssms-17

SQL Query Returning Unwanted Data Which was Filtered on Where Statement


I've got the following query: When I execute the query, I get a lot of results for ad.Branch, including 106804. If I remove BOR.SSN like and COB.SSN like, and just leave branch, it returns only 106804 records which is the desired result. So I believe the like statement is what's causing the issues.

declare @Social varchar(5);

set @social = '%####'

SELECT
ABC.AccountNumber

FROM gcc.AccountDailyFact ABC

JOIN gcc.Today T ON ABC.CalendarDate = T.Today
JOIN gcc.ADReference AD ON  ABC.ADReferenceRowId = AD.ADReferenceRowId
JOIN gcc.CDAccountData BOR ON ABC.BDLeaseHolderRowId = BOR.CDAccountDataRowId
JOIN gcc.CDAccountData COB ON ABC.CoBDLeaseHolderRowId = COB.CDAccountDataRowId
JOIN gcc.VDAssetFile VD ON ABC.VDAssetFileRowID = VD.VDAssetFileRowID

WHERE BOR.SSN like @social or COB.Ssn like @social and ad.Branch in ('106804')


Solution

  • I think you just need parentheses:

    WHERE (BOR.SSN like @social or COB.Ssn like @social) and
          ad.Branch in ('106804')