Fixed race condition in database query