Minimizing database queries