Optimized database logic