SQL
Count Distinct Values Per Group with HAVING
Learn to count the number of unique occurrences of a field within different groups using GROUP BY and COUNT(DISTINCT ...), filtering results with HAVING.
SELECT category_id, COUNT(DISTINCT product_id) AS unique_products_count
FROM order_items
GROUP BY category_id
HAVING COUNT(DISTINCT product_id) > 5;
How it works: This snippet groups `order_items` by `category_id` and then counts the number of distinct `product_id`s within each group. The `HAVING` clause filters these groups, showing only those categories where the count of unique products is greater than 5. This is powerful for analyzing unique item distribution across categories.