rewrite database query