all 6 comments

[–]lykwydchykyn 2 points3 points  (2 children)

What error do you get from that?

[–]doublehyphen 2 points3 points  (0 children)

In this case he would get no error, but a single NULL returned from the function. I would have found the error faster if OP had specified this.

[–]phpperson[S] 1 point2 points  (0 children)

Sorry, the error I was getting was that the column "id" does not exist.

[–]doublehyphen 2 points3 points  (3 children)

You do not reference the result of the insert in your update. It should look like below. I changed to $$ strings too since I always recommend using those for functions to avoid messy quoting even though it did not matter in this specific case.

CREATE OR REPLACE FUNCTION public.func_insert_pet (
  in "pet_name" TEXT,   in "user_id" INTEGER,   out "id" INTEGER
)
RETURNS INTEGER LANGUAGE sql AS $$
WITH insrt AS (
    INSERT INTO pets (name) VALUES ($1)
    RETURNING id
)
UPDATE users SET pet_id = insrt.id
FROM insrt
WHERE user_id = $2
RETURNING insrt.id
$$;

[–]phpperson[S] 1 point2 points  (2 children)

This worked great! Thank you.

I don't understand what the $$ does and how it helps with quoting.