More efficient alternative to using IN Subqueries 🚀
Did you find this helpful? If so, Please let me a 👍IntuitionTo solve this problem, we need to find, for each product, the first year it was sold and return its
**Did you find this helpful?** If so, Please let me a 👍

---

# Intuition
To solve this problem, we need to find, for each product, the first year it was sold and return its corresponding sale details — specifically, the quantity and price. Our goal is to match each product with its earliest year of sale and retrieve the relevant data for that specific record.

# Approach
We first use a subquery to calculate the minimum year of sale `(MIN(year))` for each `product_id` using `GROUP BY`. This gives us the first year of sale for every product.
Then, we `JOIN` this result with the original `Sales` table on both `product_id` and `year` to retrieve the full sale record (including `quantity` and `price`) that occurred in that earliest year.

# Code
```mssql []
/* Write your T-SQL query statement below */
SELECT
    s.product_id,
    s.year AS first_year,
    s.quantity,
    s.price
FROM Sales s
JOIN (
    SELECT product_id, MIN(year) AS first_year
    FROM Sales
    GROUP BY product_id
) first_sale
    ON s.product_id = first_sale.product_id AND s.year = first_sale.first_year;
```
['MS SQL Server']