Search code examples
postgresqlindexingdatabase-performance

Table Indexing on PostgreSQL for performance


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?


Solution

  • 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);