Performance impact of empty LIKE in a prepared statement

落爺英雄遲暮 提交于 2019-12-14 02:37:58

问题


I have set a GiST pg_trgm index on the name column of the files table.

The simplified query of the prepared statement looks like this:

SELECT * FROM files WHERE name LIKE $1;

The $1 param will be composed of % + user query + %. Since the input might also be an empty string this might result in %%.

Does an "empty" LIKE (%%) result in performance degradation? Should I build a new query in that case, or does it not matter?


回答1:


Postgres 9.2 or later is generally smart enough to realize that the condition

WHERE name LIKE '%%'

is not selective and resorts to a sequential scan ignoring the GiST index - even with prepared statements. You do pay a small price for the useless condition, though.

In Postgres 9.1 or earlier I would build a separate query for the special case.

Compare the Notes section for the PREPARE statement in the manual for the versions 9.1, 9.2 and 9.3.

Verify yourself

Prepare the statement and run EXPLAIN ANALYZE to test:

PREPARE plan1 (text) AS
SELECT  * FROM file
WHERE   name LIKE $1;

EXPLAIN ANALYZE EXECUTE plan1('%123%');

EXPLAIN ANALYZE EXECUTE plan1('%%');

Plans are generally cached for the duration of the session.

Alternative query

Regardless of the version you are running, if you always perform a full text search (wildcards left and right), this query should be faster for a prepared statement:

SELECT * FROM files WHERE name LIKE ('%' || $1 || '%');

And pass the pattern without added wildcards (%), of course. This way, Postgres knows to expect a pattern enclosed in wildcards at planning time.

->SQLfiddle demo.
Note the sequential scan for the empty LIKE and the performance difference between the two plans.
SQLfiddle varies a lot, depending on load etc. A single run may not be reliable. Better test in your environment and run each statement a couple of times to saturate cache and eliminate noise.



来源:https://stackoverflow.com/questions/19010932/performance-impact-of-empty-like-in-a-prepared-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!