Search code examples
sqlsql-like

Why Is my code being ignored?


When I execute the only thing that is working is the Zipcodes. It is not giving me a service date greater than 08/01/16 or my Billing Providers. I am not sure why.

SELECT Name, BirthDate, Address1, Address2, City, StateProvince, ZipCode, BillingProviderID, ServiceDate, ChargeCatID
FROM dbo.PbrChargeTransactions
WHERE ChargeCatID = 'EM'
AND ServiceDate >= '08/01/16'
AND BillingProviderID IN ('AAD.FD','DSD.DFD','ASDF.DD')
AND ZipCode Like '68730%'
OR ZipCode Like '68792%'
OR ZipCode Like '68739%'
OR ZipCode Like '68718%'
OR ZipCode Like '57069%'
OR ZipCode Like '57031%'
OR ZipCode Like '57078%'
OR ZipCode Like '57066%'
OR ZipCode Like '57063%'
OR ZipCode Like '57037%'
OR ZipCode Like '57073%'
OR ZipCode Like '57029%'
OR ZipCode Like '57070%'
ORDER BY Name

Solution

  • Operator precedence: "And" binds more tightly than "or". That is, only the first zip-code comparison is evaluated with the rest of your "and" conditions. The rest are 'OR's and if they match, you get the record.

    Try this:

    SELECT Name, BirthDate, Address1, Address2, City, StateProvince, ZipCode,     BillingProviderID, ServiceDate, ChargeCatID
    FROM dbo.PbrChargeTransactions
    WHERE ChargeCatID = 'EM'
    AND ServiceDate >= '08/01/16'
    AND BillingProviderID IN ('AAD.FD','DSD.DFD','ASDF.DD')
    AND (ZipCode Like '68730%'
    OR ZipCode Like '68792%'
    OR ZipCode Like '68739%'
    OR ZipCode Like '68718%'
    OR ZipCode Like '57069%'
    OR ZipCode Like '57031%'
    OR ZipCode Like '57078%'
    OR ZipCode Like '57066%'
    OR ZipCode Like '57063%'
    OR ZipCode Like '57037%'
    OR ZipCode Like '57073%'
    OR ZipCode Like '57029%'
    OR ZipCode Like '57070%'
    )
    ORDER BY Name