patternsqlMinor
In PostgreSQL is there a way to rank/weigh columns so as to order the results?
Viewed 0 times
postgresqlweighordertherankcolumnswayresultsthere
Problem
Let's say I am searching through three text columns. I don't just want results that match a given word or phrase, but I also want to weigh them (
Is this possible? Can you provide me with some terminology or suggestions for further reading?
column A > column B > column C) - thereby ordering the results such that those rows matching the word in column A will come up higher than those matching in column B, and those matching in column B will come up higher than those matching in column C.Is this possible? Can you provide me with some terminology or suggestions for further reading?
Solution
Full text search has detailed weighting mechanisms.
For simple pattern matching:
I don't use
For simple pattern matching:
SELECT *
FROM t
WHERE col_a ILIKE '%keyword%' OR
col_b ILIKE '%keyword%' OR
col_c ILIKE '%keyword%'
ORDER BY col_a ILIKE '%keyword%' OR NULL
, col_b ILIKE '%keyword%' OR NULL
, col_c ILIKE '%keyword%' OR NULL;I don't use
col_a ILIKE '%keyword%' DESC, because that would sort NULL columns first. We want to treat NULL just like FALSE, which is achieved this way.Code Snippets
SELECT *
FROM t
WHERE col_a ILIKE '%keyword%' OR
col_b ILIKE '%keyword%' OR
col_c ILIKE '%keyword%'
ORDER BY col_a ILIKE '%keyword%' OR NULL
, col_b ILIKE '%keyword%' OR NULL
, col_c ILIKE '%keyword%' OR NULL;Context
StackExchange Database Administrators Q#66356, answer score: 8
Revisions (0)
No revisions yet.