🗓️ SQL Challenge Day #28: Customers Who Bought All Products 🔹 Find customers who purchased every single product! 🛒 🔹 Problem: Report customers who bought ALL products: ✅ Handle duplicate purchases gracefully ✅ Match total distinct products 🔹 Solution: SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product); ✅ Result: Accepted 💡 Key Takeaway: **COUNT(DISTINCT) + scalar subquery** is the gold standard for "bought all" problems! ⚠️ Why DISTINCT? Customer might buy same product multiple times – we only care about unique products owned. ✅ Subquery `(SELECT COUNT(*) FROM Product)` gives total product universe – clean and maintainable. 👇 Your turn: Have you used this pattern for "completed all courses" or "visited all locations" type problems? Share your use case! #SQL #LeetCode #DataEngineering #ProblemSolving #Coding #LearningInPublic #Database #DataAnalytics
SQL Challenge: Find Customers Who Bought All Products
More Relevant Posts
-
✅ Solved a SQL problem on LeetCode — Day 46 of my SQL Journey 💪 Customers don’t just buy products… They buy patterns together 🛒 Today’s problem was about finding product categories that are frequently bought together — The logic behind “you might also like.” The approach: • Mapped each user to their purchased categories • Used a self-join to create category pairs • Applied category1 < category2 to avoid duplicates • Counted shared users per pair and filtered meaningful ones What I practised: • Self joins to relate data within the same dataset • Using DISTINCT for accurate counting • Applying GROUP BY with HAVING • Translating real behaviour into SQL logic What stood out — Recommendations aren’t random… They’re built on repeated patterns. When enough users repeat the same combination, It becomes a signal. That’s where the real insight lies. SQL doesn’t just store transactions. It uncovers relationships between them. Consistent learning, one query at a time 🚀 #SQL #LeetCode #DataAnalytics #LearningInPublic #SQLPractice
To view or add a comment, sign in
-
-
💡 𝐂𝐓𝐄 𝐦𝐚𝐝𝐞 𝐦𝐲 𝐒𝐐𝐋 𝟏𝟎𝐱 𝐜𝐥𝐞𝐚𝐧𝐞𝐫 Earlier, my SQL queries looked like this: • Nested queries inside nested queries 😵💫 • Hard to read • Even harder to debug Then I discovered CTE (Common Table Expressions)… and everything changed. 👉 Instead of writing one giant messy query, I started breaking it into steps. 𝐋𝐢𝐤𝐞 𝐭𝐡𝐢𝐬: • Step 1: Get base data • Step 2: Apply filters • Step 3: Do aggregations • Step 4: Final output All in a clean, readable flow. 💻 𝐄𝐱𝐚𝐦𝐩𝐥𝐞 𝐦𝐢𝐧𝐝𝐬𝐞𝐭: WITH step1 AS (...), step2 AS (...), step3 AS (...) SELECT * FROM step3; ✨ 𝐖𝐡𝐚𝐭 𝐈 𝐥𝐨𝐯𝐞 𝐚𝐛𝐨𝐮𝐭 𝐂𝐓𝐄: • Makes queries readable • Easy to debug step-by-step • Reusable logic in the same query • Feels like writing code, not chaos 💡 Write SQL in a way that anyone can easily understand. #SQL #DataAnalytics #CTE #DataAnalyst #LearningSQL #TechGrowth 🚀
To view or add a comment, sign in
-
-
✅ Solved a SQL problem on LeetCode — Day 49 of my SQL Journey 💪 Consistency isn’t always visible… But patterns reveal it over time 📈 Today’s problem was about identifying users with persistent behaviour — not just active users, but those who show the same action consistently across days. I worked on analysing behaviour patterns to: • Track user actions across consecutive days • Group continuous activity using ROW_NUMBER() logic • Identify streaks by adjusting date gaps • Filter users with meaningful streak length (≥ 5 days) • Select the strongest pattern per user using RANK() What I practised: • Window functions for streak detection • Handling sequential data with date logic • GROUP BY + HAVING for filtering patterns • Translating consistency into measurable conditions What stood out — Activity can be random… Consistency is never random. When actions repeat over time, They stop being noise and become behaviour. That’s where real insights start. SQL doesn’t just analyse data. It uncovers patterns hidden in time. Consistent learning, one query at a time 🚀 #SQL #LeetCode #SQLPractice #DataAnalytics #LearningInPublic
To view or add a comment, sign in
-
-
✅ Solved a SQL problem on LeetCode — Day 38 of my SQL Journey 💪 Most queries give you answers… But some force you to define the question first.❓ Today’s problem was about identifying loyal customers — not just frequent buyers, but those who show consistent behaviour over time. I worked on analysing customer patterns to: • Ensure at least 3 meaningful purchase actions • Check long-term engagement (30+ days activity) • Filter out unstable behaviour through the refund ratio • Combine all conditions cleanly using GROUP BY + HAVING What stood out to me — loyalty isn’t a single metric. A customer can purchase often, yet still not be reliable. Because behaviour is not about volume… it’s about consistency. That’s where the real insight lies. Also noticed something important — boolean logic inside aggregations (like SUM(condition)) works smoothly in MySQL, but small differences like integer division can break results in other SQL environments. Tiny detail. Big impact. SQL isn’t just about querying data. It’s about defining reality through logic. Consistent learning, one query at a time 🚀 #SQL #LeetCode #SQLPractice #DataAnalytics #LearningInPublic
To view or add a comment, sign in
-
-
🚀 High Performance SQL Query on LeetCode! Just solved “Customer Placing the Largest Number of Orders” and this one felt extra satisfying 😄 📊 Result: ✔️ Accepted ✅ (19/19 test cases passed) ✔️ Runtime: 427 ms ⚡ ✔️ Beats ~80% of submissions 🚀 💡 Problem Insight: The task was to find the customer who placed the maximum number of orders — a great use case of GROUP BY + aggregation + subquery. 🧠 My Approach: Counted orders per customer Compared it with the maximum order count using a subquery Returned the customer with the highest count SELECT customer_number FROM Orders GROUP BY customer_number HAVING COUNT(order_number) = ( SELECT MAX(order_count) FROM ( SELECT COUNT(order_number) AS order_count FROM Orders GROUP BY customer_number ) AS temp ); 🔥 Key Takeaway: Combining aggregation + nested queries helps solve ranking-type problems efficiently. Consistency is paying off — step by step improving both logic and performance 💪 #SQL #LeetCode #CodingJourney #Database #Learning #Tech #PlacementPreparation #Consistency
To view or add a comment, sign in
-
-
✅ Solved a SQL problem on LeetCode — Day 39 of my SQL Journey 💪 Some customers order anytime… But some follow patterns you can actually measure 📊 Today’s problem: identify “Golden Hour Customers” — people who consistently order during peak hours and leave high ratings. I used a single-pass aggregation query to: • Count total orders per customer • Flag orders placed during peak hours ⏰ • Calculate peak-hour percentage • Compute average rating while handling NULLs • Filter customers across all conditions at once What I practised: • CASE WHEN inside aggregations • Applying multiple conditions with HAVING • Time-based filtering using HOUR() • Combining behavioural and quality metrics in one query What stood out — Good customers aren’t just active… they’re consistent in when and how they engage. That’s where the real insight lies. SQL isn’t just about breaking problems into steps. Sometimes it’s about bringing everything together — cleanly. Consistent learning, one query at a time 🚀 #SQL #LeetCode #SQLPractice #DataAnalytics #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Day 41 of My SQL Learning Journey Today I solved a SQL problem involving self joins and missing relationships 🔥 🔹 Problem: Find employees whose managers are no longer in the company 🔗 Problem Link: https://lnkd.in/gwXAzFJm 🔹 Solution: SELECT e1.employee_id FROM Employees e1 LEFT JOIN Employees e2 ON e1.manager_id = e2.employee_id WHERE e1.manager_id IS NOT NULL AND e2.employee_id IS NULL; 🔹 Key Learning: Using self joins to compare records Handling missing relationships using LEFT JOIN Detecting NULL values effectively 💡 SQL helps uncover hidden data relationships! Consistency continues 🚀 #SQL #LeetCode #90DaysOfCode #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 37/100 – LeetCode SQL Challenge Today I solved the problem “Customers Who Bought All Products” 🛒 🔹 Problem Insight: We need to find customers who purchased every product listed in the Product table. 🔹 My Approach: First, I understood that the goal is to compare: Products bought by each customer Total products available I used: GROUP BY customer_id → to analyze each customer COUNT(DISTINCT product_key) → to avoid duplicate entries Subquery → to get total number of products Then I used HAVING to filter only those customers who bought all products 🔹 What I Learned: Importance of DISTINCT when duplicate rows exist How to use GROUP BY + HAVING effectively How to compare aggregated values with a subquery Real-world thinking: checking if a customer completed all required items 🔹 Key Query: SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product); 💡 Key Takeaway: Many SQL problems are about comparing counts and identifying patterns in grouped data. Once the logic is clear, the query becomes simple! #Day37 #100DaysOfCode #LeetCode #SQL #DataAnalytics #DSA #CodingJourney
To view or add a comment, sign in
-
-
📌CTE vs Subquery in SQL I used to think this was just about syntax. But the more I worked with real queries, the more I realized… > it's about how you approach a problem. Both help you break down logic. But they guide your thinking differently. ✏️ Subquery Use it when your thinking is: Let me first get exactly what I need… then use it. 📌 Common use cases: • Filtering data before a join • Getting latest records (e.g., max date per user) • Removing duplicates early • Applying conditions inside another query ✏️ CTE (WITH clause) Use it when your thinking is: "Let me build this step by step…" 📌 Common use cases: • Breaking complex queries into readable steps • Creating intermediate datasets • Reusing the same logic multiple times • Making debugging easier 💡 Example difference in thinking: > Subquery approach (reduce early) "Get only active users first, then join with orders" > CTE approach (structure steps) Step 1: get users Step 2: get orders Step 3: combine and filter Now something I recently noticed : While going through queries written by experienced professionals, I saw subqueries being used very intentionally. Especially when they wanted to: • Reduce rows early • Avoid unnecessary joins • Prevent duplicate results That changed how I think: It's not about CTE vs Subquery. It's about: ▪️ When do you filter? ▪️ How do you structure the logic? Because that decision impacts: • Performance • Readability • Output accuracy #linkedinforcreators #linkedincreators
To view or add a comment, sign in
-
✅ Solved a SQL problem on LeetCode — Day 40 of my SQL Journey 💪 Not every customer leaves suddenly… Some show signs before they churn. ⚠️ Today’s problem was about identifying churn risk customers — users who are still active but showing warning behaviour. I used aggregation and event analysis to: • Track each user’s latest subscription status • Identify downgrade behaviour over time • Compare current spend with historical maximum • Measure total subscription duration • Filter users based on combined risk signals What I practised: • Working with event-based data using GROUP BY • Using CASE WHEN to capture behavioural signals • Extracting latest values with ordered aggregation • Applying multiple conditions to detect patterns What stood out — Churn doesn’t happen instantly… it builds up through small changes. A downgrade here, a drop in spending there. That’s where the real insight lies. SQL isn’t just about analysing what happened. It’s about spotting what might happen next. Consistent learning, one query at a time 🚀 #SQL #LeetCode #SQLPractice #DataAnalytics #LearningInPublic
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development