PostgreSQL LIKE query performance variations

后端 未结 8 2548
青春惊慌失措
青春惊慌失措 2020-11-22 00:54

I have been seeing quite a large variation in response times regarding LIKE queries to a particular table in my database. Sometimes I will get results within 20

8条回答
  •  一向
    一向 (楼主)
    2020-11-22 01:25

    When ever you use a clause on a column with functions eg LIKE, ILIKE, upper, lower etc. Then postgres wont take your normal index into consideration. It will do a full scan of the table going through each row and therefore it will be slow.

    The correct way would be to create a new index according to your query. For example if i want to match a column without case sensitivity and my column is a varchar. Then you can do it like this.

    create index ix_tblname_col_upper on tblname (UPPER(col) varchar_pattern_ops);
    

    Similarly if your column is a text then you do something like this

    create index ix_tblname_col_upper on tblname (UPPER(col) text_pattern_ops);
    

    Similarly you can change the function upper to any other function that you want.

提交回复
热议问题