optimising query function