2

Is it possible to determine if an ARRAY column contains overlapping values from another array with the LIKE clause?

The && operator works but the strings have to be exact matches

 q = """select * from articles where keywords && '{"mortgage brokers"}';""" // Exact match

Is it possible to filter the keywords where rows contain values with substring, not the full string? Something like:

 q = """select * from articles where keywords && LIKE '{"mortgage"}';""" // HOW TO FILTER keywords containing value with substring

2 Answers 2

2

LIKE operates on strings. To check whether two arrays overlap, you can use &&.

From the Array Functions and Operators documentation:

&& : overlap (have elements in common)

SELECT ARRAY[1,4,3] && ARRAY[2,1] arrays_overlap;

| arrays_overlap |
| -------------- |
| true           |

To see if there are values in an array that are LIKE those from another array, one solution would be to unnest both arrays and compare the results with LIKE:

SELECT EXISTS (
  SELECT 1
    FROM 
    unnest(ARRAY['abc', 'def' ]) my_array(x)
    INNER JOIN unnest (ARRAY['a', 'z' ]) my_keywords(x)  
        ON my_array.x LIKE '%' || my_keywords.x || '%'
 ) arrays_have_similar_elements;

| arrays_have_similar_elements |
| ---------------------------- |
| true                         |

SELECT EXISTS (
  SELECT 1
    FROM 
    unnest(ARRAY['abc', 'def' ]) my_array(x)
    INNER JOIN unnest (ARRAY['y', 'z' ]) my_keywords(x)  
        ON my_array.x LIKE '%' || my_keywords.x || '%'
 ) arrays_have_similar_elements;

| arrays_have_similar_elements |
| ---------------------------- |
| false                        |

Demo on DB Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

is it possible to combine && and like? && only returns results on exact matches
@kye: ah I see what you mean now. I updated my answer.
1

Thanks to @GMB for the guidance. I was able to solve the problem using the query below.

      SELECT * from articles, unnest(keywords) my_array(x)
            INNER JOIN unnest(ARRAY['broker']) my_keywords(x)
            ON my_array.x LIKE '%' || my_keywords.x || '%';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.