Skip to content

Parameterized Query is Magnitudes Slower When Using LIKE #224

@JamoCA

Description

@JamoCA

I was troubleshooting a MSSQL query that used LIKE. If inline SQL was used, the result was returned within 400-550 ms. QB (or even using QueryExecute w/bind parameters) was taking ~27,000 ms by comparison.

While researching the issue, I came across a SQL resource with good advice:

I ended up changing this:

DECLARE @company NVARCHAR(100);
SET @company = '%My Partial Company Name%';
SELECT ID, Company FROM Clients WHERE Company LIKE @company;

to something like this:

DECLARE @company NVARCHAR(100);
SET @company = '%My Partial Company Name%';
SELECT ID, Company FROM Clients WHERE COALESCE(Company,'') LIKE @company;
--- or SELECT ID, Company FROM Clients WHERE Company+'' LIKE @company;

and the query performance was increased where the sql execution time was reduced from 26,777ms to 62ms! (Even faster than Inline SQL; which was 438ms).

Here's what it looks like using QB syntax.

q.whereRaw( "Company+'' LIKE ?", ["%My Partial Company Name%"]);

NOTE: I'm posting this in case developers blame QB for the slowness and return to writing unsafe, inline SQL (without data binding.) Would you be interested in automatically parsing the LIKE value, identify the "%" prefix and automatically generate this "LIKE obfuscation" hack. (I'm not sure if this should be the default approach or not, but it was extremely beneficial for our project.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions