DEV Community

Masui Masanori
Masui Masanori

Posted on

[PostgreSQL] Get values from arrays that do not exist in the database

Motivations

I have two array values like below now.
If there are some values that are not registered in my database, I want to know them.

Arrays

Array1

[1, 2, 30, 100]
Enter fullscreen mode Exit fullscreen mode

Array2

['hello', 'world', 'sample']
Enter fullscreen mode Exit fullscreen mode

[Database] sample_tables

id name
1 hello world
2 good morning

Getting existed values

I can get values that are registered in the database.

Array1

SELECT * FROM sample_tables WHERE id IN (1, 2, 30, 100);
Enter fullscreen mode Exit fullscreen mode

Results1

1
2
Enter fullscreen mode Exit fullscreen mode

Array2

SELECT * FROM sample_tables WHERE REGEXP_LIKE(name, '(hello)|(world)|(sample)')
Enter fullscreen mode Exit fullscreen mode

Results2

hello world
Enter fullscreen mode Exit fullscreen mode

Getting not existed values

Conversely, how can I get the values that are not registered in the database?

I can use subquery to do that.

Array1

SELECT t1.keyword FROM (SELECT UNNEST(ARRAY[1, 2, 30, 100]) as keyword) as t1
LEFT JOIN sample_tables as t2 ON t2.id = t1.keyword
WHERE t2.ID IS NULL;
Enter fullscreen mode Exit fullscreen mode

Result1

30
100
Enter fullscreen mode Exit fullscreen mode

Array2

SELECT t1.keyword FROM (SELECT UNNEST(ARRAY['hello', 'world', 'sample']) as keyword) as t1
LEFT JOIN sample_tables as t2 ON t2.name LIKE '%' || t1.keyword || '%'
WHERE t2.ID IS NULL;
Enter fullscreen mode Exit fullscreen mode

Results2

sample
Enter fullscreen mode Exit fullscreen mode

Top comments (0)