3

For a postgres varchar column that I would very frequently search by prefix, what type of index should I be using?

select * from customer.customers where name like 'James%'

My table is something like

James Bond
James Blond
James Sunderland
David Copperfield
David Beckham
1

2 Answers 2

6

Use a B-tree index with an operator class that supports pattern matching:

CREATE INDEX ON customer.customers (name text_pattern_ops);
Sign up to request clarification or add additional context in comments.

Comments

0

Your query is fine. You can even use a regular index on it:

create index idx_customer_name on customer(name);

This works because like will use a b-tree index when the pattern does not start with wildcards. For more general patterns, you need a GIST or GIN index.

1 Comment

But unless his collation is "c", the index needs to be declared with text_pattern_ops

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.