CREATE OR REPLACE FUNCTION purge_usage_stat_proc()
RETURNS VOID
LANGUAGE plpgsql
VOLATILE
AS
$$
DECLARE
  l_purge_interval interval;
begin

select  (value::int || ' sec')::interval
into    l_purge_interval
from    VPX_PARAMETER
where   NAME = 'vpxd.usageStats.duration';

delete from VPX_USAGE_SAMPLE_TIME VTD
WHERE VTD.SAMPLE_TIME <= timezone('UTC', now()) - l_purge_interval;

delete from VPX_USAGE_STAT VHS
WHERE VHS.TIME_ID < (SELECT MIN(TIME_ID) FROM VPX_USAGE_SAMPLE_TIME);

delete from VPX_USAGE_STAT VHS
WHERE NOT EXISTS  (
                  SELECT  1
                  FROM    vpx_stat_counter TMP
                  WHERE   TMP.counter_id = VHS.counter_id);

exception
  when others then
    null;
end
$$