DEV Community

Masui Masanori
Masui Masanori

Posted on

1

[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

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs