DO $$ DECLARE i INTEGER; DECLARE f INTEGER; DECLARE s INTEGER; BEGIN i := 0; f := (SELECT MIN("Id")FROM "public"."ElasticQueryLog"); s := 1; WHILE( i <=s ) loop DELETE FROM "public"."ElasticQueryLog" WHERE "Id" IN (SELECT "Id" FROM "public"."ElasticQueryLog" WHERE "CreateDate"<=(CURRENT_TIMESTAMP - INTERVAL '30 day') AND "Id" between f AND f+1000000); i = i + 1; f = f + 1000000; RAISE NOTICE 'Value: % , %', i, f; END loop; END $$;