AdvancedCTEs & Recursive
CTE with MATERIALIZED hint for performance
The query
SQL
WITH MATERIALIZED expensive_calc AS (
-- This CTE will be computed once and stored
SELECT
emp_id,
SUM(hours) AS total_hours,
COUNT(DISTINCT project_id) AS project_count
FROM project_assignments
GROUP BY emp_id
)
SELECT
e.first_name,
e.last_name,
ec.total_hours,
ec.project_count,
ROUND(e.salary / NULLIF(ec.total_hours, 0), 2) AS hourly_cost
FROM employees e
JOIN expensive_calc ec ON e.emp_id = ec.emp_id
ORDER BY hourly_cost DESC;Note
“MATERIALIZED forces CTE to be computed once (PostgreSQL 12+). Default is INLINE optimization which may recalculate.