clear markdown compare help best fiddles feedback dbanow.uk
clear markdown donate comments/suggestions/bugs a leap of faith? bible365 diddy dollings
By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0. 2805490 fiddles created (40771 in the last week).

CREATE TABLE tbl ( version INT PRIMARY KEY , col_a text , col_b text , col_c text ); INSERT INTO tbl (VERSION, col_a, col_b, col_c) VALUES (1, 'A1', 'B1', NULL) , (2, 'A2', 'B2', NULL) , (3, 'A3', 'B3', NULL) , (4, 'A5', NULL, 'C1') , (5, 'A1', NULL, NULL) ;
5 rows affected
 hidden batch(es)


CREATE OR REPLACE FUNCTION func(OUT _col_a text, OUT _col_b text, OUT _col_c text) LANGUAGE plpgsql AS $func$ DECLARE _row record; BEGIN FOR _row IN SELECT col_a, col_b, col_c FROM tbl ORDER BY version DESC LOOP IF _col_a IS NULL AND _row.col_a IS NOT NULL THEN _col_a := _row.col_a; END IF; IF _col_b IS NULL AND _row.col_b IS NOT NULL THEN _col_b := _row.col_b; END IF; IF _col_c IS NULL AND _row.col_c IS NOT NULL THEN _col_c := _row.col_c; END IF; EXIT WHEN (_col_a, _col_b, _col_c) IS NOT NULL; END LOOP; END $func$;
 hidden batch(es)


SELECT * FROM func();
_col_a _col_b _col_c
A1 B3 C1
 hidden batch(es)