I am building a search functionality and need help with a postgres query. My use case is – When a string is an input, what is the best (optimized) way in postgres to get all records where each words in string exists on any of the columns in a table ?
Sample Table: (The table I am working with has 40 columns)
FName | Occupation |
---|---|
John | Engineer |
Carlos | Doctor |
Case 1: Given a string ‘John Doctor’, In this case it would return both the records.
Output:
FName | Occupation |
---|---|
John | Engineer |
Carlos | Doctor |
Case 2: Given a string ‘John Engineer’, it would only return 1 row
Output:
FName | Occupation |
---|---|
John | Engineer |
Case 3: Given a string ‘Carlos’, it would return 1 row
Output:
FName | Occupation |
---|---|
Carlos | Doctor |
2
Answers
Basically, you want to do following:
I don’t know if this is already a sufficient answer for you because it’s unclear if the logic to fetch the different names from your "search string" must be written as SQL query, too. I think that’s a much better task for your application.
If this must also be done in pure SQL, you could use
UNNEST
to split your string.Something like this:
This will split your string by spaces into the different names, i.e. you need to provide a search string in the form you have mentioned, with a space between the names.
This will produce the correct results according to your description.
We can verify this here: db<>fiddle1
This can be extended for as many column as needed. Let’s for example add a further column
col
and searchTest3
in this column, then the query will be like this:Or again with
UNNEST
like this:Try this here: db<>fiddle2
Use regexp match operator (case insensitive) and
any
to find the records that contain at least one of the words in the list.DB Fiddle demo