I have a list in my application as;
tags = ["nature", "science", "funny", "politics", "news"]
and I want to check if all these elements exist in my Tags.name table field. The idea is that user is not able to add any new tag which is not already in the system.
Currently, I am trying to run a .foreach loop in my query as;
DO $$
BEGIN
FOREACH itag IN ARRAY {'nature', 'politics'} LOOP
IF EXISTS (SELECT 1 FROM tags WHERE name = itag) THEN
INSERT INTO TAGS (name, post_id) values itag, 'post01' ;
ELSE
RAISE EXCEPTION 'Tag % doesnt exists in table', itag;
END IF;
END LOOP;
END; $$
this gives error as;
ERROR: syntax error at or near "{"
LINE 3: FOREACH itag SLICE 1 IN ARRAY {'nature', 'politics'} LOOP
I am not sure how to query for a list in postgres. I dont want to do this via application code and fire multiple queries as there can be a lot of elements in my list. I want to have the list checked against the table values in a single query.
Also, if possible, is there a way to optimize my query?
EDIT: I have used @a_horse_with_no_name 's answer to come up with a flow similar to what I am looking for. If all tags are present in my table, I will add these entries else I will throw an exception.
DO $$
BEGIN
IF (with to_check (itag) as (
values ('nature'),('science'),('politics'),('scary')
)
select bool_and(exists (select * from tags t where t.name = tc.itag)) as all_tags_present
from to_check tc) THEN
RAISE INFO 'ALL GOOD. Here I will add the insert statement in my app';
ELSE
RAISE EXCEPTION 'One or more tags are not present';
END IF;
END; $$