patternsqlMinor
42702 'column reference "id" is ambiguous' for RETURNING of table-returning PL/pgSQL function
Viewed 0 times
42702referencecolumnfunctionambiguousreturningforpgsqltable
Problem
This works:
This doesn't:
Is this a bug in PL/pgSQL? How can I fix this while keeping the return type as is?
CREATE OR REPLACE FUNCTION sql_fun()
RETURNS TABLE (id UUID) AS $
INSERT INTO foo DEFAULT VALUES
RETURNING id
$ LANGUAGE SQL;
SELECT *
FROM sql_fun();This doesn't:
CREATE OR REPLACE FUNCTION plpgsql_fun()
RETURNS TABLE (id UUID) AS $
BEGIN
RETURN QUERY
INSERT INTO foo DEFAULT VALUES
RETURNING id;
END
$ LANGUAGE PLpgSQL;
SELECT *
FROM plpgsql_fun();Is this a bug in PL/pgSQL? How can I fix this while keeping the return type as is?
Solution
The solution is to qualify all columns from
If the name of the table is long and there are multiple columns, the name can be aliased:
RETURNING which have the same name as the columns from RETURNS TABLE with the name of the table which was INSERTED INTO:CREATE OR REPLACE FUNCTION plpgsql_fun()
RETURNS TABLE (id UUID) AS $
BEGIN
RETURN QUERY
INSERT INTO foo DEFAULT VALUES
RETURNING foo.id;
END
$ LANGUAGE PLpgSQL;If the name of the table is long and there are multiple columns, the name can be aliased:
CREATE OR REPLACE FUNCTION plpgsql_fun()
RETURNS TABLE (id UUID, foo INT, bar INT) AS $
BEGIN
RETURN QUERY
INSERT INTO table_with_a_very_long_name AS x DEFAULT VALUES
RETURNING x.id, x.foo, x.bar;
END
$ LANGUAGE PLpgSQL;Code Snippets
CREATE OR REPLACE FUNCTION plpgsql_fun()
RETURNS TABLE (id UUID) AS $$
BEGIN
RETURN QUERY
INSERT INTO foo DEFAULT VALUES
RETURNING foo.id;
END
$$ LANGUAGE PLpgSQL;CREATE OR REPLACE FUNCTION plpgsql_fun()
RETURNS TABLE (id UUID, foo INT, bar INT) AS $$
BEGIN
RETURN QUERY
INSERT INTO table_with_a_very_long_name AS x DEFAULT VALUES
RETURNING x.id, x.foo, x.bar;
END
$$ LANGUAGE PLpgSQL;Context
StackExchange Database Administrators Q#268815, answer score: 2
Revisions (0)
No revisions yet.