Get id from INSERT or SELECT
<p>I've this function that inserts a row into a <code>city</code> table without duplicates. It returns the id of the inserted row:</p>

<pre><code>CREATE OR REPLACE FUNCTION public.insert_city(
character varying,
character varying,
character varying,
character varying,
character varying,
character varying)
RETURNS integer AS
$BODY$
DECLARE
name_city1 ALIAS FOR $1;
country1 ALIAS FOR $2;
province1 ALIAS FOR $3;
region1 ALIAS FOR $4;
cap1 ALIAS FOR $5;
nationality1 ALIAS FOR $6;
id_city1 integer;
BEGIN
   INSERT INTO city (name_city, country, province, region, cap, nationality) 
   SELECT name_city1, country1, province1, region1, cap1, nationality1
WHERE NOT EXISTS (SELECT id_city FROM city WHERE name_city = name_city1)
RETURNING id_city INTO id_city1;

-- xxx

END;
$BODY$
LANGUAGE plpgsql VOLATILE;
</code></pre>

<p><code>xxx</code> marks the spot where I need something like this:</p>

<pre><code>IF is_number(id_city1) THEN
    RETURN id_city1;
ELSE
RETURN query select id_city from city where name_city=name_city1;
END IF;
</code></pre>

<p>If the first query does not insert a new row and I don't get an <code>id_city</code> from it, I want to execute the second query to select an existing <code>id_city</code>.</p>

<p>How can I do this?</p>