Search code examples
sql-serverwhere-clause

Where clause to search for muliple items


I have a table that has a problem name field and a Jurisdiction name field. I want to search for multiple problem names that fall under the same Jurisdiction name.

SELECT TOP (100000) [Master_Incident_Number]
      ,[Response_Date]
      ,[Problem]
      ,[Location_Name]
      ,[Address]
      ,[Apartment]
      ,[City]
      ,[Jurisdiction]
      ,[MethodOfCallRcvd]
      ,[Call_Disposition]
      ,[CallTaking_Performed_By]
      ,[CallClosing_Performed_By]
      FROM [Reporting_System].[dbo].[Response_Master_Incident]  
      where Jurisdiction like 'Sector 5%' 
        and Response_Date >= '2022-01-01 00:00:00.000' 
        and Problem like 'Building / Security Check-LCL' 
         or Problem like 'Park and Walk-LCL'

When I run this I get returns that don't match what I put in for the Jurisdiction like 'Sector 5%'". How can I get it to only return items with the "Jurisdiction like" field being 'Sector 5%' only.

If I only do a search for only one problem name type, the search works and only returns Jurisdictions with the name like "Sector 5". But If I add an additional problem name type it returns all Jurisdiction Names with those 2 problem name types.


Solution

  • It's always the OR condition in these cases. Operator precedence here doesn't work the way you think it should. You need parentheses:

      where Jurisdiction like 'Sector 5%' 
        and Response_Date >= '2022-01-01 00:00:00.000' 
        and (Problem like 'Building / Security Check-LCL' 
            or Problem like 'Park and Walk-LCL')
    

    But since there are no wildcards in either of those checks, we can also simplify it like this:

      where Jurisdiction like 'Sector 5%' 
        and Response_Date >= '2022-01-01 00:00:00.000' 
        and Problem IN ('Building / Security Check-LCL','Park and Walk-LCL')