CREATE OR REPLACE FUNCTION core.get_second_root_account_id(_account_id bigint, _parent bigint DEFAULT 0)
RETURNS integer
LANGUAGE plpgsql
AS $function$
DECLARE _parent_account_id bigint;
BEGIN
SELECT
parent_account_id
INTO _parent_account_id
FROM core.accounts
WHERE account_id=$1;
IF(_parent_account_id IS NULL) THEN
RETURN $2;
ELSE
RETURN core.get_second_root_account_id(_parent_account_id, $1);
END IF;
END
$function$