A clear explanation of retrieving product names and their sale years using a JOIN between Sales and Product tables.
Problem Restatement
We have two tables:
Sales(sale_id, product_id, year, quantity, price) — each row is a sale.
Product(product_id, product_name) — product information.
We need to return product_name, year, and price for each sale.
Input and Output
| Table | Schema |
|---|---|
Sales | sale_id INT, product_id INT, year INT, quantity INT, price INT |
Product | product_id INT, product_name VARCHAR |
Return a table with product_name, year, price.
Examples
Sales: Product:
+---------+------------+------+ +------------+--------------+
| sale_id | product_id | year | | product_id | product_name |
+---------+------------+------+ +------------+--------------+
| 1 | 100 | 2008 | | 100 | Nokia |
| 2 | 100 | 2009 | | 200 | Apple |
| 7 | 200 | 2011 | | 300 | Samsung |
+---------+------------+------+ +------------+--------------+Answer:
+--------------+------+-------+
| product_name | year | price |
+--------------+------+-------+
| Nokia | 2008 | ... |
| Nokia | 2009 | ... |
| Apple | 2011 | ... |
+--------------+------+-------+Edge Cases
- Match the aggregate to the question: use raw
COUNTorSUMfor rows/amounts, andCOUNT(DISTINCT ...)only for unique entities. - Tie cases should return every qualifying row unless the statement asks for a single row.
- For outer joins, keep filters on the joined table in the
ONclause when unmatched rows must remain visible.
Common Pitfalls
- Do not put aggregate filters in
WHERE; useHAVINGafterGROUP BY. - When the answer needs all tied winners, avoid
LIMIT 1unless the statement explicitly asks for one row.
Implementation
SELECT p.product_name, s.year, s.price
FROM Sales s
JOIN Product p ON s.product_id = p.product_id;Code Explanation
Join Sales with Product on product_id to get the product name for each sale.
Select product_name, year, and price from the joined result.