Compute an aggregate once and join it back.

Section: subqueries and ctes

Join to a derived table

sql
sql
SELECT u.id, u.email, x.last_order_at
FROM users u
LEFT JOIN (
  SELECT user_id, MAX(created_at) AS last_order_at
  FROM orders
  GROUP BY user_id
) x ON x.user_id = u.id;
Explanation

Derived tables are handy when you want one summarized row per parent entity.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing subqueries and ctes
Filter with a subquery
Return users who have at least one paid order.
OpenIn sheetsqlsame section
Use EXISTS for correlated filtering
Return users who have orders.
OpenIn sheetsqlsame section
Use a CTE to isolate recent orders
Create a readable query pipeline with `WITH`.
OpenIn sheetsqlsame section
Inner join two tables
Return rows where both tables match.
OpenIn sheetsql1 tag match
Left join to keep unmatched parent rows
Return all rows from the left table and matching rows from the right table.
OpenIn sheetsql1 tag match
Join and aggregate child rows
Count child rows per parent.
OpenIn sheetsql1 tag match