Search code examples
sql-serverquery-optimizationpatindex

sql: optimize query with many conditions


I have this sql query:

SELECT
    [Id],
    [Content]    
FROM 
    [MyTable] with (nolock)
where
    Content is not null
    and (PATINDEX('%"number" : "[0-9]%', Content) > 0
         or PATINDEX('%"number":"[0-9]%', Content) > 0
         or PATINDEX('%"number" :"[0-9]%', Content) > 0
         or PATINDEX('%"number": "[0-9]%', Content) > 0
         --del
         or PATINDEX('%"del":"[0-9]%', Content) > 0
         or PATINDEX('%"del":"[0-9]%', Content) > 0
         or PATINDEX('%"del":"[0-9]%', Content) > 0
         or PATINDEX('%"del":"[0-9]%', Content) > 0
)

On my server, with caches cleared, it takes more than two minutes to return around 400 rows, maybe because I have a lot of conditions with or.

I've created the query that way because of the possibilities of the "number" string in the Content column of having a space or not between ":" and "number" string or the next digit.

Is there a way to reduce from the or conditions?


Solution

  • Try it

    SELECT
        [Id],
        [Content]    
    FROM 
        [MyTable] with (nolock)
    where
        Content is not null
        and (PATINDEX('%"number":"[0-9]%', replace(Content,' ','')) > 0
             or PATINDEX('%"del":"[0-9]%', replace(Content,' ','')) > 0)
    

    and you can remove Content is not null part also