Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy do SUBSTRING or LEFT make the query much slower?
    primarykey
    data
    text
    <p>I have a blacklist of people that should never be contacted. When I want to see if a person is in this list, I do the following:</p> <pre><code>-- Query 1 SELECT * FROM bldb.dbo.blacklist l WHERE l.matchcode = dbo.fn_matchcode('12345','Sesame Street','1','Eddie','Bert') </code></pre> <p>The query runs very fast, since there is an index on matchcode column, and <code>fn_matchcode</code> is deterministic.</p> <p>Think of matchcode as a compressed form of address and name, which helps me not to be affected from typos in street names etc. It consists of 22 chars: 13 for the address, 9 for the name. When I want to see if any person in <strong><em>1 Sesame Street, 12345</em></strong> is in blacklist, I do the following:</p> <pre><code>-- Query 2 SELECT * FROM bldb.dbo.blacklist l WHERE LEFT(l.matchcode,13) = LEFT(dbo.fn_matchcode('12345','Sesame Street','1','Eddie','Bert'),13) </code></pre> <p>This runs extremely long...</p> <p>On the contrary, this runs much faster:</p> <pre><code>-- Query 3 SELECT * FROM bldb.dbo.blacklist l WHERE LEFT(l.matchcode,13) = (SELECT LEFT(dbo.fn_matchcode('12345','Sesame Street','1','Eddie','Bert'),13)) </code></pre> <p>That means, the right hand side of the where condition gets calculated for every row! But why? The UDF is deterministic. Is it <code>LEFT()</code>, which is not deterministic?</p> <p><strong>EDIT:</strong></p> <p>The answers so far claimed that it is because the index does not get used. However, it is still not clear to me why the following happens.</p> <p>When I write the query like this:</p> <pre><code>-- Query 4 SELECT * FROM bldb.dbo.blacklist WHERE matchcode LIKE LEFT(dbo.fn_matchcode('12345','Sesame Street','1','Eddie','Bert'),13) + '%' </code></pre> <p>it still takes several minutes to finish. Please note that the <code>fn_matchcode</code> just does some string manipulation and returns instantly.</p> <p>When I hardcode the result of <code>fn_matchcode</code> into the query:</p> <pre><code>-- Query 5 SELECT * FROM bldb.dbo.blacklist WHERE matchcode LIKE '12345SSMSTRT1%' </code></pre> <p>it takes a couple of milliseconds! How would you explain that?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload