Table Joins
Combine relational entities using INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, and SELF JOIN.
Core Learning Objectives
- •Identify unmatched records using LEFT JOIN ... WHERE right_table.id IS NULL
- •Perform self-joins to compare records within the same table (e.g. employee vs manager)
- •Avoid cartesian blowups and duplicate key multiplication
Interactive Cheatsheet
PostgreSQL Syntax-- Finding users who never made a purchase SELECT u.user_id, u.user_name FROM users u LEFT JOIN orders o ON u.user_id = o.user_id WHERE o.order_id IS NULL;
Curated Practice Problems (3)
Facebook Pages With Zero Likes
You are asked by Meta's Social Graph team to identify Facebook Pages that currently have zero likes. Write a SQL query to return the IDs of all Facebook pages that do not have any likes recorded in the `page_likes` table. Sort the output in ascending order by `page_id`. Tables: - `pages` (`page_id` INT, `page_name` VARCHAR) - `page_likes` (`user_id` INT, `page_id` INT, `liked_date` TIMESTAMP)
Employees Earning More Than Their Manager
Meta's Compensation & People Analytics team is evaluating managerial equity balance. Write a SQL query to find all employees who earn strictly more than their direct manager. Return the employee's name (`employee_name`), their salary (`employee_salary`), their manager's name (`manager_name`), and their manager's salary (`manager_salary`). Sort by employee salary descending. Tables: - `employees` (`emp_id` INT, `name` VARCHAR, `salary` INT, `manager_id` INT)
Purchased Products With Zero Customer Reviews
Amazon Marketplace wants to target customers with automated review request emails. Write a SQL query to find all orders where the customer has never written a product review for that item. Return `customer_id`, `product_id`, and `order_date`. Sort by `order_date` descending, then by `customer_id` ascending. Tables: - `customer_orders` (`order_id` INT, `customer_id` INT, `product_id` INT, `order_date` DATE) - `product_reviews` (`review_id` INT, `customer_id` INT, `product_id` INT, `rating` INT)