What's the best way to get accurate and fast queries in PostgreSQL for a longest prefix match?
Is it:
A.) select * from table where column in (subselect) ; B.) select * from table where strpos(column,column2) = 1 order by length(column2) desc limit 1 ; C.) select * from table where column ~ column2 order by length(column2) desc limit 1
I'm planning to use in an update. Any ideas?
I wouldn't know of a function doing this out of the box in PostgreSQL.
A recursive CTE would be the key element for a rather elegant solution (available in PostgreSQL 8.4 or later).
I am assuming a table
filter
to hold the filter strings:And a table
tbl
to be search for the longest match:Query
Detailed explanation how the final SELECT works in this related answer.
Working demo on sqlfiddle.
You did not define which match to pick from a set of equally long matches. I am picking one arbitrary winner from ties.
PostgreSQL 9.1 introduced data modifying CTEs, so you can use this in an
UPDATE
statement directly.