sqlsql-serverkeyword-search

Search keywords on all column of the table


I have Vehicle_parts table like below,

Vehicle_ID Vehicle_Major_Part_Number Vehicle_Sub_Part_Number
1 11111 xxx 22222 xxx
2 33333 zzz 11111 yyy
3 44444 aaa 22222 bbb
4 22222 zzz 11111 yyy
5 88888 zzz 44444 yyy

I need to do keywords search on entire column of the table.

Example: If the Keywords: '11111' & '88888' then the result will be like below table,

Vehicle_ID Vehicle_Major_Part_Number Vehicle_Sub_Part_Number
1 11111 xxx 22222 xxx
2 33333 zzz 11111 yyy
4 22222 zzz 11111 yyy
5 88888 zzz 44444 yyy

I tried Like statement in where clause but the ** where** clause not allowing to search multiple columns.

Also I tried Functions like below,

Create function [Keyword_Search](@Keyword Varchar(100))

Returns table

as

RETURN(SELECT * FROM Vehicle_parts WHERE 
      [Vehicle_Major_Part_Number] LIKE @Keyword
      or [Vehicle_Sub_Part_Number] LIKE @Keyword

SELECT * FROM Keyword_Search ('%11111%')

Here, I could not provide multiple keywords at a time for searching.

Kindly suggest me to the efficient way for searching the multiple keywords on all columns present in the table.


Solution

  • You can put multiple LIKE conditions in the WHERE clause that check every condition you named. According to your description, this query will work:

    SELECT vehicle_id, vehicle_major_part_number, vehicle_sub_part_number
    FROM vehicle_parts
    WHERE vehicle_major_part_number LIKE '11111%'
    OR vehicle_major_part_number LIKE '88888%'
    OR vehicle_sub_part_number LIKE '11111%'
    OR vehicle_sub_part_number LIKE '88888%';
    

    Queries with LIKE and especially with % (to mark further characters might follow) are often slow and as you see, they can be long and bad to read, too. You could also try something like this:

    SELECT vehicle_id, vehicle_major_part_number, vehicle_sub_part_number
    FROM vehicle_parts
    WHERE CONCAT(vehicle_major_part_number, vehicle_sub_part_number) LIKE '%11111%' OR 
    CONCAT(vehicle_major_part_number, vehicle_sub_part_number) LIKE '%88888%';
    

    This might be a bit better to read, but still slow.

    If you do exactly know which string you want to check, this will make your query much shorter, easier to read and will improve the execution time. As example:

    SELECT vehicle_id, vehicle_major_part_number, vehicle_sub_part_number
    FROM vehicle_parts
    WHERE '11111 xxx' IN (vehicle_major_part_number, vehicle_sub_part_number)
    OR '88888 zzz' IN (vehicle_major_part_number, vehicle_sub_part_number);
    

    This will of course get two rows less than the other options, but maybe you will find a way to prevent the usage of LIKE. This would be much better.

    Here a fiddle according to your example: db<>fiddle