0

I am solving performance issues on PostgreSQL and I have the following table:

 CREATE TABLE main_transaction (
   id integer NOT NULL DEFAULT nextval('main_transaction_id_seq'::regclass),
   description character varying(255) NOT NULL,
   request_no character varying(18),
   account character varying(50),
   ....
 )

Above table has 34 columns including 3 FOREIGN KEYs and it has over 1 Million rows data. I have the following conditional SELECT query:

SELECT * FROM main_transaction
WHERE upper(request_no) LIKE upper(concat('%','20080417-0258-0697','%'))

Returning the result in over 2 seconds. I want to decrease working time by using table indexing. So far, I have used btree indexing. However, I didn't notice any fast result. My question is, how can I improve performance for above query?

2
  • 1
    Why the %? the search string already has the maximum length for the column... Commented Apr 20, 2018 at 10:06
  • ('%','20080417-0258-0697','%') -> (('%',:field,'%') ) Commented Apr 20, 2018 at 10:36

1 Answer 1

2

Your only chance to search for a pattern that begins with % is a trigram index:

CREATE EXTENSION pg_trgm;

CREATE INDEX ON main_transaction
   USING gin (upper(request_no) gin_trgm_ops);
Sign up to request clarification or add additional context in comments.

3 Comments

Great! I also have foreign keys in my table and I am using CROSS JOIN to link the tables by id and it is causing slow performance. I have a profile_id column in main_transaction table for profile table and in profile table I have customer_id for customer table. SELECT * FROM main_transaction t CROSS JOIN main_profile p CROSS JOIN main_customer c WHERE t.profile_id = p.id AND p.user_id = c.id AND ( upper(t.request_no) LIKE upper(concat('%','0-90-6 12 ','%')) OR upper(c.phone) LIKE upper(concat('%','0-90-6 12','%')) ). Thank you
Well, then open a question for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.