[Solved] Postgresql SELECT performance and optimization
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

Postgresql SELECT performance and optimization

Database type:

I have a table with 14_000 rows. Not to many. My query

SELECT "wells".* FROM "wells" WHERE (LOWER(name) LIKE '%abc%' OR code LIKE '%ABC%')
  ORDER BY "wells"."name_nso" ASC, "wells"."extra_name" ASC
  LIMIT 10;

takes "Execution Time: 2.701 ms"

For this table i have two indexes:

CREATE INDEX wells_btree_idx_on_name_nso
ON public.wells USING btree
(name_nso COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;

and

CREATE INDEX wells_gin_idx_on_name_lower
ON public.wells USING gin
(lower(name) COLLATE pg_catalog."default" gin_trgm_ops)
TABLESPACE pg_default;

If i remove LIMIT 10, it takes "Execution Time: 0.894 ms". 4 times faster.

Is it worth looking into how to speed up a query with LIMIT 10 to those 0.894 ms, or are those 2.701 ms fast enough and not worth bothering with?

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Calling Functions With Indexed Columns (query line: 7): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. For example, if the column `name` is indexed, the index won’t be used as it’s wrapped with the function `LOWER`. If you can’t find an alternative condition that won’t use a function call, a possible solution is to store the required value in a new indexed column.
  2. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  3. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
CREATE INDEX wells_idx_name_nso_extra_name ON "wells" ("name_nso","extra_name");
The optimized query:
SELECT
        "wells".* 
    FROM
        "wells" 
    WHERE
        (
            LOWER("wells".name) LIKE '%abc%' 
            OR "wells".code LIKE '%ABC%'
        ) 
    ORDER BY
        "wells"."name_nso" ASC,
        "wells"."extra_name" ASC LIMIT 10

Related Articles



* original question posted on StackOverflow here.