1

I have a column in Postgres like:

name
abc def ghi
lmnop qrst uvw
xyz

Is there any way I get the match and the position of the match?
For example
If I search for 'ef' then I should get the first by using a query like:

select * from table where name like '%ef%';

and the position of the match should be 5. How can I find the position of the match?

2 Answers 2

1

Exact syntax for the Postgres position() function is, quoting the manual:

position ( substring text IN string text ) → integer

With the IN keyword.

To get index support, I suggest:

SELECT *, position('ef' IN name)
FROM   tbl
WHERE  name ~ 'ef';

name ~ 'ef' od name LIKE '%ef%' can use a trigram index on (name), unlike the expression position('ef' IN name) > 0, which is not "sargable". Big difference in performance for big tables.

About that trigram index:

-1
select name, position('ef', name)
from your_table
where position('ef', name) > 0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.