Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL replace statement too slow

Tags:

sql

sql-server

I have a replace statement that does something like this:

SELECT Distinct Forenames, Surname, dbUSNs.DateOfBirth, Datasetname, 
       dbUSNs.MoPIGrade, SourceAddress, VRM, URNs 
FROM Person 
WHERE ( Replace(Replace(Replace(Replace(Replace(Replace(Replace
        (Replace(Replace(Replace(Replace(Replace(Replace(Replace
        (Replace(Replace(Replace(Replace(Replace(Replace(Replace
        (Replace(Replace(Replace(Replace
        (Surname,'/',''''),'?',''''),'',''''),'^',''''),'{',''''),'}',''''),
                '[',''''),']',''''),';',''''),'$',''''),'=',''''),'*',''''),
                '#',''''),'|',''''),'&',''''),'@',''''),'\',''''),'<',''''),
                '>',''''),'(',''''),')',''''),'+',''''),',',''''),'.',''''),
                ' ','''') LIKE 'OREILLY%')

Therefore even though OReilly is passed, O'Reilly will be found. However, this is too slow. Is there a better way of approaching it?

like image 832
w0051977 Avatar asked Aug 22 '26 17:08

w0051977


1 Answers

The problem isn't that REPLACE is "too slow", but that using it at all makes that part of the query unsargable, meaning that it can't use an index.

Wikipedia: Sargable

Basically you've forced a tablescan / indexscan, from top to bottom. On top of that you have the overhead of REPLACE.

If you want this query to run fast, I would instead do one of the following:

  • Create an additional column containing a searchable text version of the Surname
  • Create an indexed, materialized view with those REPLACE functions
like image 192
Lasse V. Karlsen Avatar answered Aug 25 '26 06:08

Lasse V. Karlsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!