Complete the code to select each department and its employee count using LATERAL join.
SELECT d.department_name, emp_count.count FROM departments d LEFT JOIN LATERAL (SELECT COUNT(*) AS count FROM employees e WHERE e.department_id = d.id) AS emp_count ON [1];The LATERAL join requires a condition after ON. Using true means the join always applies, allowing the subquery to correlate with the outer query.
Complete the code to select each employee and their latest project using LATERAL join.
SELECT e.name, p.project_name FROM employees e LEFT JOIN LATERAL (SELECT project_name FROM projects p WHERE p.employee_id = e.id ORDER BY p.start_date DESC LIMIT 1) AS p ON [1];
The ON clause for LATERAL join can be true to always join the subquery result for each employee.
Fix the error in the LATERAL join by completing the ON clause correctly.
SELECT d.name, emp.name FROM departments d JOIN LATERAL (SELECT name FROM employees emp WHERE emp.department_id = d.id LIMIT 1) emp ON [1];
The ON clause in a LATERAL join can be true to allow the lateral subquery to run correlated with the outer query.
Fill both blanks to create a LATERAL join that selects each customer and their most recent order date.
SELECT c.customer_name, recent_orders.order_date FROM customers c LEFT JOIN LATERAL (SELECT order_date FROM orders o WHERE o.customer_id = c.id ORDER BY order_date DESC LIMIT 1) AS recent_orders ON [1] [2];
The ON clause can be true for LATERAL joins. If combining conditions, use AND or OR. Here, true AND is syntactically valid but usually only true is needed.
Fill all three blanks to write a query that selects each product and its top 3 reviews using LATERAL join.
SELECT p.product_name, r.review_text FROM products p JOIN LATERAL (SELECT review_text FROM reviews r WHERE r.product_id = p.id ORDER BY r.rating DESC LIMIT [1]) r ON [2] [3];
The LIMIT is 3 to get top 3 reviews. The ON clause can be true. If combining conditions, use AND. Usually, just true is enough for LATERAL joins.