Optimize db queries