'PostgreSQL function returns one column instead of 4 columns [duplicate]
I have a PostgreSQL function that returns one column instead of 4 columns like it should. Moreover, all four data points are nested within one column and the updates were not performed. Can you please review my code and offer suggestions?

code:
-- FUNCTION: public.update_funcnull()
-- DROP FUNCTION IF EXISTS public.update_funcnull();
CREATE OR REPLACE FUNCTION public.update_funcnull(
)
RETURNS TABLE(ride_id text, duration interval, lat_change real, long_change real)
LANGUAGE 'plpgsql'
COST 100
VOLATILE PARALLEL UNSAFE
ROWS 1000
AS $BODY$
BEGIN
UPDATE bikeshare3 SET duration = NULL;
UPDATE bikeshare3 SET lat_change = NULL;
UPDATE bikeshare3 SET long_change = NULL;
RETURN QUERY SELECT ride_id, duration, lat_change, long_change FROM bikeshare3 LIMIT 5;
END;
$BODY$;
ALTER FUNCTION public.update_funcnull()
OWNER TO postgres;
Solution 1:[1]
You should to call function with "tabular context":
SELECT * FROM public.update_funcnull();
Tabular functions (or Set Returning functions in PostgreSQL terminology) returns composite values in "scalar context".
CREATE OR REPLACE FUNCTION public.foo()
RETURNS TABLE(a integer, b integer)
LANGUAGE plpgsql
AS $function$
BEGIN
a := 1; b := 2;
RETURN NEXT;
RETURN NEXT;
END;
$function$;
(2022-04-18 05:55:32) postgres=# SELECT foo();
?????????
? foo ?
?????????
? (1,2) ?
? (1,2) ?
?????????
(2 rows)
(2022-04-18 05:55:37) postgres=# SELECT * FROM foo();
?????????
? a ? b ?
?????????
? 1 ? 2 ?
? 1 ? 2 ?
?????????
(2 rows)
Composite value can be unpacked, but packing to composite and unpacking has some performance impact:
(2022-04-18 05:55:43) postgres=# SELECT (foo()).*;
?????????
? a ? b ?
?????????
? 1 ? 2 ?
? 1 ? 2 ?
?????????
(2 rows)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pavel Stehule |
