Optimized code by reducing number of intermediate tables