DROP FUNCTION IF EXISTS invoice.heading_id(integer);

CREATE OR REPLACE FUNCTION invoice.heading_id(
	id_ integer)
    RETURNS INT
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
DECLARE
	num INTEGER=0;
	ret_val integer=0;
BEGIN
	SELECT count(id) INTO num FROM invoice.headers WHERE id=id_ AND heading_id IS NOT NULL;
	IF NUM::BOOL THEN
	 	SELECT heading_id INTO ret_val FROM invoice.headers WHERE id=id_; 
	END IF;
	RETURN ret_val;
END;
$BODY$;
DELETE FROM invoice.headers WHERE id>1;
DELETE FROM account.headings WHERE id>1;

DELETE FROM account.headings WHERE id=72;