🗓️ SQL Challenge Day #21: Immediate Food Delivery II 🔹 Calculate percentage of immediate first orders! 🚚 🔹 Problem: Find percentage of immediate orders in first orders: ✅ Immediate = order_date = customer_pref_delivery_date ✅ First order = earliest order per customer ✅ Round to 2 decimal places 🔹 Solution: SELECT ROUND(AVG(CASE WHEN order_date = customer_pref_delivery_date THEN 1 ELSE 0 END) * 100.0, 2) AS immediate_percentage FROM ( SELECT MIN(order_date) AS order_date, MIN(customer_pref_delivery_date) AS customer_pref_delivery_date FROM delivery GROUP BY customer_id ) t; ✅ Result: Accepted 💡 Key Takeaway: **MIN() in subquery + AVG(CASE)** is perfect for "first occurrence" problems! The subquery isolates first orders, while AVG(CASE) elegantly calculates the percentage without separate counts. 👇 Your turn: What's the most interesting real-world metric you've calculated using window functions or subqueries? #SQL #LeetCode #DataEngineering #ProblemSolving #Coding #LearningInPublic #Database #DataAnalytics
SQL Challenge: Calculate Immediate First Orders Percentage
More Relevant Posts
-
SQL Challenge of the Day Problem: A retailer wants to analyze their product inventory to find "gaps" in product pricing. Given a table of products, each with a unique product_id and a price, identify all ranges of consecutive missing price points (assume integer prices from the minimum to the maximum price in the table, inclusive) where no product exists with that price. For each gap, return the start and end price of the gap (inclusive). If there are no gaps, return an empty result. Sample Tables (CREATE + INSERT): CREATE TABLE products ( product_id INT PRIMARY KEY, product_name VARCHAR(100), price INT ); INSERT INTO products (product_id, product_name, price) VALUES (1, 'Laptop', 900), (2, 'Tablet', 903), (3, 'Monitor', 904), (4, 'Keyboard', 901), (5, 'Mouse', 906); Query: -- Write a query to output columns: gap_start INT, gap_end INT -- Each row is a missing consecutive price range, inclusive, where no product exists Explanation: The challenge requires you to detect gaps in an integer sequence (product prices). Use SQL techniques such as generating sequences, anti-joins, and grouping to find the start and end of each missing price interval. The output should list each gap as a pair of consecutive missing price points between the minimum and maximum existing price, with no overlap or omission.#SQLChallenge #PriceGapAnalysis #SQLQuery #DataAnalysis #DatabaseManagement #CodingChallenge #SQLTips #DataScience #TechChallenge #SQLPractice
To view or add a comment, sign in
-
𝗖𝗼𝗺𝗺𝗼𝗻 𝗦𝗤𝗟 𝗠𝗶𝘀𝘁𝗮𝗸𝗲𝘀 (𝗮𝗻𝗱 𝗛𝗼𝘄 𝘁𝗼 𝗙𝗶𝘅 𝗧𝗵𝗲𝗺) Over time, I’ve seen a few SQL mistakes that can silently break logic or performance. Here are some common ones and how to avoid them: 1. 𝗙𝗼𝗿𝗴𝗲𝘁𝘁𝗶𝗻𝗴 𝘁𝗵𝗲 𝗪𝗛𝗘𝗥𝗘 𝗖𝗹𝗮𝘂𝘀𝗲 Running 𝗗𝗘𝗟𝗘𝗧𝗘 or 𝗨𝗣𝗗𝗔𝗧𝗘 without a 𝗪𝗛𝗘𝗥𝗘 clause can wipe out entire tables. Always double-check your conditions and use transactions when working with critical data. One small miss can lead to massive data loss. 2. 𝗢𝘃𝗲𝗿𝘂𝘀𝗶𝗻𝗴 𝗦𝗘𝗟𝗘𝗖𝗧 * Using 𝗦𝗘𝗟𝗘𝗖𝗧 * fetches unnecessary columns, slows down queries, and makes code less readable. Instead, select only the columns you need—it improves performance and keeps queries future-proof. 3. 𝗖𝗼𝗺𝗽𝗮𝗿𝗶𝗻𝗴 𝘄𝗶𝘁𝗵 𝗡𝗨𝗟𝗟 𝗜𝗻𝗰𝗼𝗿𝗿𝗲𝗰𝘁𝗹𝘆 𝗡𝗨𝗟𝗟 is not a value, so = 𝗡𝗨𝗟𝗟 won’t work. Always use 𝗜𝗦 𝗡𝗨𝗟𝗟 or 𝗜𝗦 𝗡𝗢𝗧 𝗡𝗨𝗟𝗟. This ensures correct filtering and avoids unexpected empty results. 4. 𝗚𝗿𝗼𝘂𝗽𝗶𝗻𝗴 𝗜𝘀𝘀𝘂𝗲𝘀 𝗶𝗻 𝗦𝗘𝗟𝗘𝗖𝗧 Every non-aggregated column in your 𝗦𝗘𝗟𝗘𝗖𝗧 must be in the 𝗚𝗥𝗢𝗨𝗣 𝗕𝗬. Ignoring this leads to errors or incorrect results. Follow SQL standards for clean and accurate aggregation. 5. 𝗜𝗻𝗰𝗼𝗿𝗿𝗲𝗰𝘁 𝗚𝗥𝗢𝗨𝗣 𝗕𝗬 𝗨𝘀𝗮𝗴𝗲 Grouping without proper structure can make your results confusing. Use meaningful groupings and ensure your query clearly reflects the business logic behind the data. 6. 𝗠𝗶𝘀𝘀𝗶𝗻𝗴 𝗣𝗮𝗿𝗲𝗻𝘁𝗵𝗲𝘀𝗲𝘀 𝗶𝗻 𝗖𝗼𝗺𝗽𝗹𝗲𝘅 𝗟𝗼𝗴𝗶𝗰 When combining 𝗔𝗡𝗗 and 𝗢𝗥, operator precedence can change results. Always use parentheses to define logic explicitly; it improves readability and prevents logical bugs. 💡 𝗙𝗶𝗻𝗮𝗹 𝗧𝗵𝗼𝘂𝗴𝗵𝘁: Small SQL mistakes can lead to big data issues. Writing clean, intentional queries is just as important as getting the result. If you’ve faced similar issues, I would love to hear your experiences 👇 Follow Aman Gambhir for more content like this. #SQL #sqltips #sqlquery #query #sqlmistakes #optimization
To view or add a comment, sign in
-
-
SQL window functions changed how I think about data. Before I learned them, I was writing subqueries for everything. Clunky. Repetitive. Hard to read. Then I discovered window functions, and the same logic became cleaner, faster, and easier for anyone to follow. The one I kept reaching for: ROW_NUMBER() It assigns a unique rank to each row within a group. Simple idea. Powerful in practice. Real example: find the most recent order per customer. Without window functions: → Write a subquery to get max date per customer → Join it back to the original table → Hope nothing breaks With ROW_NUMBER(): → Partition by customer → Order by date descending → Filter where row = 1 Same result. Half the code. Much easier to explain to a colleague. I used this constantly when building SQL pipelines, pulling the latest record per entity from multi-source business data. It saved time and made my queries reviewable. If you're writing SQL regularly and haven't touched window functions yet, ROW_NUMBER() is where I'd start. Small function. Big shift in how you think. Which SQL concept clicked everything into place for you? Drop it below 👇 #SQL #DataAnalytics #DataScience #LearningInPublic
To view or add a comment, sign in
-
-
🚨 Common SQL Mistakes That CRASH Production (And How to Fix Them) 🚨 As a Data Analyst with 5+ years optimizing queries at scale, I've seen these SQL blunders cause prod failures, slow dashboards, and endless firefighting. Here's my top 7 that bite hardest – with fixes to bulletproof your code. 1. SELECT * Everywhere Pulls unnecessary columns, bloating memory and breaking when schemas change. ✅ Fix: SELECT order_id, customer_name FROM orders; – explicit columns only. 2. Missing WHERE in UPDATE/DELETE The ultimate prod killer – wipes entire tables accidentally. ✅ Fix: Always test with SELECT first, then add WHERE. Use transactions: BEGIN TRANSACTION; 3. Functions on Indexed Columns WHERE YEAR(order_date) = 2025 kills indexes, forces full scans. ✅ Fix: WHERE order_date >= '2025-01-01' AND order_date < '2026-01-01' 4. NOT IN with NULLs Subquery has NULL? Entire result vanishes silently. ✅ Fix: Use NOT EXISTS or LEFT JOIN WHERE alias.col IS NULL 5. No Indexes on JOIN/WHERE Columns Fine in dev, crawls in prod with real data. ✅ Fix: Index foreign keys, frequent filters: CREATE INDEX idx_order_date ON orders(date); 6. Subqueries vs JOINs Correlated subs run per row – N+1 hell. ✅ Fix: Rewrite as JOINs for massive speedups. 7. DISTINCT Overuse Masks dupes but sorts everything, tanks perf. ✅ Fix: Fix root cause with proper GROUP BY or DISTINCT ON (Postgres). Pro Tip: Always check execution plans before prod. What's your worst SQL war story? 👇 #SQL #DataEngineering #Database #PowerBI #DataAnalytics #TechTips
To view or add a comment, sign in
-
A SQL feature I don’t see used often: LATERAL (but very useful) While exploring some advanced SQL patterns, I came across LATERAL. It’s simple in idea, but powerful when dealing with row-wise logic. 🔹 What it does LATERAL lets a subquery refer to columns from the current row of the main query. 🔹 Example use case Get the latest order for each customer: SELECT c.customer_id, o.order_id, o.order_date FROM customers c CROSS APPLY ( SELECT order_id, order_date FROM orders o WHERE o.customer_id = c.customer_id ORDER BY order_date DESC FETCH FIRST 1 ROW ONLY ) o; 🔹 Why not a normal join? We can solve this using analytic functions or joins, but LATERAL makes it more direct for row-by-row dependent queries. 💡 What I found useful It simplifies queries where the inner logic depends on each row of the outer query — especially for “top N per group” type problems. Still exploring more use cases — Have you used LATERAL in your queries? #OracleSQL #SQL #DataEngineering #AdvancedSQL #DatabaseDevelopment
To view or add a comment, sign in
-
🚀 LeetCode SQL Practice: Problem #1581 – Customer Who Visited but Did Not Make Any Transactions 💡 Problem: We’re given two tables – Visits and Transactions. The task is to find customers who visited the mall but never made a transaction. 🛠️ Approach: Use a LEFT JOIN between Visits and Transactions on visit_id. Filter rows where transaction_id IS NULL (meaning no transaction was recorded). Group by customer_id to count how many times each customer visited without making a purchase. ✅ Solution Query: sql SELECT customer_id, COUNT(v.visit_id) AS count_no_trans FROM Visits v LEFT JOIN Transactions t ON v.visit_id = t.visit_id WHERE transaction_id IS NULL GROUP BY customer_id; 📊 Takeaway: This problem is a great example of how JOINs + NULL filtering can help uncover hidden insights in data. It’s not just about writing queries—it’s about thinking like an analyst and asking the right questions. #sql #leetcode #dataanalysis #Practice
To view or add a comment, sign in
-
-
One SQL mistake that can silently break your results: 👉 NOT IN vs NOT EXISTS Looks similar. But behaves very differently. Example: SELECT * FROM orders WHERE customer_id NOT IN (SELECT customer_id FROM customers); 💡 Seems correct, right? But here’s the problem 👇 👉 If the subquery contains even one NULL → The entire result becomes empty ❌ You get no rows Even when data exists 💡 Why? SQL doesn’t know how to compare NULL → Result becomes UNKNOWN 💡 Better approach: SELECT * FROM orders o WHERE NOT EXISTS ( SELECT 1 FROM customers c WHERE o.customer_id = c.customer_id ); 👉 NOT EXISTS handles NULLs safely 💡 Real-world impact: Missing data in reports Incorrect filtering Hard-to-debug issues Lesson: 👉 Similar-looking queries ≠ same behavior 👉 Always think about NULLs If you understand this, you’re already ahead of many developers. Follow for more practical SQL insights. 🙂 #SQL #DataEngineering #Learning #Analytics
To view or add a comment, sign in
-
-
This SQL query runs perfectly. No errors. Clean logic. Looks correct. But the result is completely wrong. Look at the query in the image. It tries to calculate total revenue per customer. And at first glance, everything seems fine. But there’s a subtle mistake in the aggregation logic that completely distorts the output. This is exactly how production dashboards get incorrect numbers — not because queries fail, but because they silently return misleading results. Your challenge: What is wrong with this query? Write the correct SQL in the comments. Follow Data Rejected for real-world SQL challenges. Repost if this could help someone preparing for interviews or debugging production queries. Subscribe on YouTube for full SQL breakdowns. #SQL #DataEngineering #AnalyticsEngineering #DataAnalytics #Database #LearnSQL #SQLTips #TechCareers #QueryOptimization #BusinessIntelligence #DataRejected
To view or add a comment, sign in
-
-
🚀 Day 35/100 – SQL Practice (LeetCode) Today I solved “1795. Rearrange Products Table” problem. 🔹 Problem Summary: Given a table with product prices in different stores (store1, store2, store3), the goal is to transform the data so that: Each row contains → product_id, store, price Ignore stores where the product is not available (NULL) 🔹 My Approach: First, I understood that the data is in column format We need to convert it into row format So, I used: UNION ALL → to combine results from multiple queries WHERE → to remove NULL values Extracted each store separately and merged them 🔹 Query I Used: SELECT product_id, 'store1' AS store, store1 AS price FROM Products WHERE store1 IS NOT NULL UNION ALL SELECT product_id, 'store2' AS store, store2 AS price FROM Products WHERE store2 IS NOT NULL UNION ALL SELECT product_id, 'store3' AS store, store3 AS price FROM Products WHERE store3 IS NOT NULL; 🔹 What I Learned Today: Concept of Unpivoting (Columns → Rows) Practical use of UNION ALL Handling missing values using NULL How to restructure data for better analysis Improved SQL thinking for real-world scenarios 🔹 Key Takeaway: Understanding how to transform data structure is very important in SQL, especially for analytics and reporting. 💡 Consistency is key — learning something new every day! #Day35 #100DaysOfCode #SQL #LeetCode #DataAnalytics #LearningJourney
To view or add a comment, sign in
-
-
SQL is the language of data, but are you using its "hidden" logic? 🔍 Writing queries is one thing; understanding the engine is another. Here are 4 things about SQL that changed how I think about data: - The Execution Order Lie: We write SELECT first, but SQL executes it almost last. It starts with FROM and WHERE. This is why you can’t use a column alias in your filter—the engine hasn't "seen" the alias yet! - The NULL Trap: In SQL, NULL = NULL is False (technically Unknown). NULL is a state, not a value. If you use NOT IN on a list containing a NULL, your whole query might return zero results. - SARGable Queries: If you use a function on a column in your WHERE clause (like WHERE YEAR(date) = 2025), you might be killing your performance. It prevents the database from using indexes. Use a date range instead. - Window Functions > Group By: SUM() OVER() is often more powerful than a standard GROUP BY. It allows you to keep your row-level detail while adding aggregate context in the same view. SQL isn't just about getting the data; it’s about getting it efficiently. 🚀 What’s one SQL "gotcha" that caught you off guard when you first started? ⬇️ #SQL #DataAnalytics #DataEngineering #CodingTips #Database #PowerBI
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