Complete the code to select each department's name and the name of its top-paid employee using a LATERAL subquery.
SELECT d.name, e.name FROM departments d, LATERAL (SELECT name FROM employees WHERE department_id = d.id ORDER BY salary DESC LIMIT [1]) e;The LATERAL subquery selects the top-paid employee by ordering salaries descending and limiting to 1.
Complete the code to join each order with its latest shipment date using a LATERAL subquery.
SELECT o.id, s.shipment_date FROM orders o, LATERAL (SELECT shipment_date FROM shipments WHERE order_id = o.id ORDER BY shipment_date DESC LIMIT [1]) s;The LATERAL subquery fetches the latest shipment date per order by ordering descending and limiting to 1.
Fix the error in the LATERAL subquery that tries to select employee names by limiting it to one row.
SELECT d.name, e.name FROM departments d, LATERAL (SELECT name FROM employees WHERE department_id = d.id ORDER BY salary DESC LIMIT [1]) e;The subquery must have LIMIT 1 to return exactly one employee per department and the alias 'e' is correctly used.
Fill both blanks to select each customer and their most recent order date using a LATERAL subquery.
SELECT c.name, o.[1] FROM customers c, LATERAL (SELECT [2] FROM orders WHERE customer_id = c.id ORDER BY order_date DESC LIMIT 1) o;
The outer query selects the order_date from the lateral subquery which also selects order_date ordered descending to get the most recent.
Fill all three blanks to select each product and its top 3 reviews' ratings using a LATERAL subquery.
SELECT p.name, r.rating FROM products p, LATERAL (SELECT rating FROM reviews WHERE product_id = p.id ORDER BY rating DESC LIMIT [1]) r WHERE r.rating > [2] AND r.rating <= [3];
The subquery limits to top 3 ratings. The WHERE clause filters ratings greater than 2 and less or equal to 5.