SELECT o.id, u.email, o.status
FROM orders o
INNER JOIN users u ON u.id = o.user_id;`INNER JOIN` excludes rows without a matching parent or child.
inner joins, left joins, self joins, subqueries, derived tables, and common table expressions in MySQL.
Combine related tables with inner and outer joins.
SELECT o.id, u.email, o.status
FROM orders o
INNER JOIN users u ON u.id = o.user_id;`INNER JOIN` excludes rows without a matching parent or child.
Return all rows from the left table and matching rows from the right table.
SELECT u.id, u.email, o.id AS order_id
FROM users u
LEFT JOIN orders o ON o.user_id = u.id;Rows from `users` remain even when there is no matching row in `orders`.
SELECT u.id, u.email, COUNT(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id, u.email;A classic reporting query for dashboards and admin pages.
SELECT e.id, e.full_name, m.full_name AS manager_name
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;Self joins are common in hierarchical data such as org charts.
Filter, rank, and reshape results with subqueries and common table expressions.
SELECT id, email
FROM users
WHERE id IN (
SELECT user_id FROM orders WHERE status = 'paid'
);A simple subquery pattern for membership-based filtering.
SELECT u.id, u.email
FROM users u
WHERE EXISTS (
SELECT 1 FROM orders o WHERE o.user_id = u.id
);`EXISTS` is often clearer and more efficient than counting when you only care whether a match exists.
Create a readable query pipeline with `WITH`.
WITH recent_orders AS (
SELECT id, user_id, total_amount, created_at
FROM orders
WHERE created_at >= NOW() - INTERVAL 30 DAY
)
SELECT user_id, COUNT(*) AS recent_order_count, SUM(total_amount) AS revenue
FROM recent_orders
GROUP BY user_id;CTEs help break complex logic into named steps.
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;Derived tables are handy when you want one summarized row per parent entity.