I can't seem to figure this out, the following is an attempt to get an array of items to run as foreach loop in postgres using pgadmin query tool, for each item x
in the array, do 2 insert statements where x
is each array value:
I tried this based on https://www.postgresql.org/docs/current/plpgsql-control-structures.html#PLPGSQL-FOREACH-ARRAY section 42.6.7. Looping through Arrays, here is some pseudocode:
DO
$do$
BEGIN
FOREACH x IN ['Apple','Banana','Cantaloupe']
LOOP
INSERT INTO foods.fruits(id, comment, fruit_name)
VALUES ((SELECT MAX(id) + 1 FROM foods.fruits), 'a comment', x);
INSERT INTO foods.fruits_ordered(id, price, fruit_id)
VALUES ((SELECT MAX(id) + 1 FROM foods.fruits_ordered), '5.00', (SELECT id FROM foods.fruits WHERE fruit_name = x));
END LOOP;
END
$do$;
This should run the loop 3 times and do a total of 6 insertions. Any idea how to get this to work?
select max() + 1
is a terrible way to generate unique IDs. You should use aserial
column (based on a sequence). But you don't need PL/pgSQL or a loop to begin with: dbfiddle.uk/… – a_horse_with_no_name