UPDATE: Crap! it’s not an integer it’s character varying(10)
Executing the query like this uses the index
SELECT t."FieldID"
FROM table t
WHERE t."FieldID" = '0123456789'
But does not use the index if I execute this
SELECT t."FieldID"
FROM table t
WHERE t."FieldID" LIKE '01%'
or this
SELECT t."FieldID"
FROM table t
WHERE "substring"(t."FieldID", 0, 3) = '01'
also this
SELECT t."FieldID"
FROM table t
WHERE t."FieldID" ~ '^01'
My index looks like this
CREATE UNIQUE INDEX fieldid_index
ON "table"
USING btree
("FieldID");
Running PostgreSQL 7.4 (Yep Upgrading)
I’m optimizing my query and wanted to know if there is any performance gains using one of the three types of expressions in either the SELECT or WHERE clause in the statement.
NOTE: The query that executes with these style of constraints returns around 200,000 records
Example Data is a character varying(10): 0123456789 and it is indexed as well
1. (Substring)
SELECT CASE
WHEN "substring"(t."FieldID"::text, 0, 3) = '01'::text
THEN 'Found Match'::text
ELSE NULL::text
END AS matching_group
2. (Like)
SELECT CASE
WHEN t."FieldID"::text LIKE '01%'
THEN 'Found Match'::text
ELSE NULL::text
END AS matching_group
3. (RegEx)
SELECT CASE
WHEN t."FieldID" ~ '^01'
THEN 'Found Match'::text
ELSE NULL::text
END AS matching_group
Also is there any performance advantages using one over the other in the WHERE clause?
1. (Substring)
WHERE CASE
WHEN "substring"(t."FieldID"::text, 0, 3) = '01'::text
THEN 1
ELSE 0
END = 1
2. (Like)
WHERE CASE
WHEN t."FieldID"::text LIKE '01%'
THEN 1
ELSE 0
END = 1
3. (RegEx)
WHERE CASE
WHEN t."FieldID" ~ '^01'
THEN 1
ELSE 0
END = 1
Would using one option in the SELECT and a different option in the WHERE clause improve performance?
In SQL Server the version with
LIKE '01%'would be sargable. It actually converts theseLIKEqueries without leading wildcards to range queries.The execution plan shows the seek predicate as being
YourCol >= '01' AND YourCol < '02'perhaps a similar sort of rewrite could help in Postgresql?