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?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228

2 Answers2

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:

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
-1
select name, position('ef', name)
from your_table
where position('ef', name) > 0
juergen d
  • 201,996
  • 37
  • 293
  • 362