rearrange query script