I need to match a user input against a string column. Both contain space-separated words.
The ordering criteria is:
- count of words matched from the beginning (prefix match) desc
- count of words matched desc
- columns where matched words come in the same order as in the input phrase come first
So given the following sample data
"one sample"
"un moment"
"no match"
"sample uno"
"uno sample"
"sample oun"
and the sample input "sa un foo"
, the output should be:
"sample uno"
- 2 prefix matches"uno sample"
- the same but the order of words differs"sample oun"
- 1 prefix match + 2 words matched"un moment", "one sample"
- 1 prefix match
The question is: can I implement this in a single SQL query (postgresql
)?
I'm fairly unexperienced with SQL, so I appreciate any help. Thanks!
I include a simple SQL FIDDLE