<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by DataGrad on Medium]]></title>
        <description><![CDATA[Stories by DataGrad on Medium]]></description>
        <link>https://medium.com/@datagrad?source=rss-2e63c0c4e906------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hmhv_b-Ca9LTas62aXi_6g.png</url>
            <title>Stories by DataGrad on Medium</title>
            <link>https://medium.com/@datagrad?source=rss-2e63c0c4e906------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:48:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@datagrad/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Your Attribution Model Is Lying to You]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://datagrad.medium.com/your-attribution-model-is-lying-to-you-b782344716c4?source=rss-2e63c0c4e906------2"><img src="https://cdn-images-1.medium.com/max/1536/1*hsU9I8kGKPVzJ80B6rjxEw.png" width="1536"></a></p><p class="medium-feed-snippet">A practical guide to why last-click fails, what the alternatives actually assume, and how to build a model you can trust instead of just&#x2026;</p><p class="medium-feed-link"><a href="https://datagrad.medium.com/your-attribution-model-is-lying-to-you-b782344716c4?source=rss-2e63c0c4e906------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://datagrad.medium.com/your-attribution-model-is-lying-to-you-b782344716c4?source=rss-2e63c0c4e906------2</link>
            <guid isPermaLink="false">https://medium.com/p/b782344716c4</guid>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[marketing-attribution]]></category>
            <category><![CDATA[marketing-analytics]]></category>
            <category><![CDATA[martech]]></category>
            <category><![CDATA[adtech]]></category>
            <dc:creator><![CDATA[DataGrad]]></dc:creator>
            <pubDate>Sat, 08 Aug 2026 11:37:57 GMT</pubDate>
            <atom:updated>2026-08-08T11:37:57.241Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Google Cloud Generative AI Leader: My Certification Journey]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://datagrad.medium.com/google-cloud-generative-ai-leader-my-certification-journey-b0a1d4aeb732?source=rss-2e63c0c4e906------2"><img src="https://cdn-images-1.medium.com/max/1774/1*8N2FQ0LYvx_vu6d7N381gA.png" width="1774"></a></p><p class="medium-feed-snippet">From understanding AI fundamentals to exploring enterprise AI adoption, this certification helped me view Generative AI through a business&#x2026;</p><p class="medium-feed-link"><a href="https://datagrad.medium.com/google-cloud-generative-ai-leader-my-certification-journey-b0a1d4aeb732?source=rss-2e63c0c4e906------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://datagrad.medium.com/google-cloud-generative-ai-leader-my-certification-journey-b0a1d4aeb732?source=rss-2e63c0c4e906------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0a1d4aeb732</guid>
            <category><![CDATA[ai-certification]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[professional-development]]></category>
            <dc:creator><![CDATA[DataGrad]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 06:16:43 GMT</pubDate>
            <atom:updated>2026-06-17T06:16:43.854Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The AI Horizon: Understanding Google’s Vision for the Future of Work]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://datagrad.medium.com/the-ai-horizon-understanding-googles-vision-for-the-future-of-work-89013978330d?source=rss-2e63c0c4e906------2"><img src="https://cdn-images-1.medium.com/max/1774/1*JUZtPWOlcbIpuqlrUNGLXg.png" width="1774"></a></p><p class="medium-feed-snippet">What every business professional should know about Generative AI, AI Agents, and the evolving enterprise AI landscape.</p><p class="medium-feed-link"><a href="https://datagrad.medium.com/the-ai-horizon-understanding-googles-vision-for-the-future-of-work-89013978330d?source=rss-2e63c0c4e906------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://datagrad.medium.com/the-ai-horizon-understanding-googles-vision-for-the-future-of-work-89013978330d?source=rss-2e63c0c4e906------2</link>
            <guid isPermaLink="false">https://medium.com/p/89013978330d</guid>
            <category><![CDATA[future-of-work]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[DataGrad]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 06:07:44 GMT</pubDate>
            <atom:updated>2026-06-17T06:35:08.143Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The Marketing Funnel: Your Analytics Blueprint]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://datagrad.medium.com/the-marketing-funnel-your-analytics-blueprint-a77d8c4907f9?source=rss-2e63c0c4e906------2"><img src="https://cdn-images-1.medium.com/max/2208/1*_YjJpTRet2DOifS-nWuHEw.png" width="2208"></a></p><p class="medium-feed-snippet">In the modern digital landscape, marketing is rarely a linear path from &#x201C;seeing an ad&#x201D; to &#x201C;buying a product.&#x201D;</p><p class="medium-feed-link"><a href="https://datagrad.medium.com/the-marketing-funnel-your-analytics-blueprint-a77d8c4907f9?source=rss-2e63c0c4e906------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://datagrad.medium.com/the-marketing-funnel-your-analytics-blueprint-a77d8c4907f9?source=rss-2e63c0c4e906------2</link>
            <guid isPermaLink="false">https://medium.com/p/a77d8c4907f9</guid>
            <category><![CDATA[digital-marketing]]></category>
            <category><![CDATA[marketing-analytics]]></category>
            <category><![CDATA[startupş]]></category>
            <category><![CDATA[growth-marketing]]></category>
            <category><![CDATA[data-driven]]></category>
            <dc:creator><![CDATA[DataGrad]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 09:54:28 GMT</pubDate>
            <atom:updated>2025-12-17T09:54:28.716Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Mastering Prompt Design with Vertex AI — My Latest Google Cloud Skill Badge]]></title>
            <link>https://datagrad.medium.com/mastering-prompt-design-with-vertex-ai-my-latest-google-cloud-skill-badge-14935bf26190?source=rss-2e63c0c4e906------2</link>
            <guid isPermaLink="false">https://medium.com/p/14935bf26190</guid>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <dc:creator><![CDATA[DataGrad]]></dc:creator>
            <pubDate>Sat, 03 May 2025 07:52:23 GMT</pubDate>
            <atom:updated>2025-05-03T07:52:23.743Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Prompt Design with Vertex AI — My Latest Google Cloud Skill Badge</h3><p>In today’s AI-powered world, knowing <em>how</em> to talk to AI is just as important as knowing <em>what</em> to ask. That’s why I recently <a href="https://www.credly.com/badges/8b46c01a-b10b-4388-83aa-4a8ca0d1dca1">completed </a>the <strong>“</strong><a href="https://www.cloudskillsboost.google/course_templates/976"><strong>Prompt Design in Vertex AI</strong></a><strong>”</strong> Skill Badge from <a href="https://medium.com/u/be36e94a7e47">Google</a><strong> Cloud Skills Boost</strong> — a focused, hands-on course that dives deep into the art and science of <strong>prompt engineering</strong>, <strong>multimodal AI</strong>, and the <strong>Gemini API</strong>.</p><figure><img alt="Prompt Design in Vertex AI skill badge to demonstrate skills in the following: prompt engineering, image analysis, and multimodal generative techniques, within Vertex AI." src="https://cdn-images-1.medium.com/max/320/1*X728l5D6UsqCLh0KkFAT2g.png" /><figcaption>Prompt Design in Vertex AI skill badge to demonstrate skills in the following: prompt engineering, image analysis, and multimodal generative techniques, within Vertex AI.</figcaption></figure><p>Over the course of four interactive labs and a final challenge, I explored how to guide generative AI to produce smarter, more useful, and context-aware responses — across both text and image-based inputs.</p><h3>🧪 What This Skill Badge Covers</h3><p>This skill badge certifies hands-on proficiency in:</p><ul><li>Writing well-crafted prompts that guide AI output</li><li>Leveraging Gemini for image and video analysis</li><li>Applying few-shot, zero-shot, and system-prompting techniques</li><li>Using the <strong>Vertex AI SDK</strong> to build and integrate Gemini into real-world applications</li></ul><h3>🔍 Lab-by-Lab Breakdown</h3><h4>✅ 1. Prompt Engineering Best Practices with Gemini</h4><p>In this lab, I got a solid foundation in prompt engineering principles:</p><ul><li>How to <strong>be concise, specific, and well-defined</strong> in queries</li><li>Why prompts should <strong>focus on one question at a time</strong></li><li>How to guide output using <strong>examples and context</strong></li></ul><p>By the end, I had experimented with different styles of prompting to see how even subtle changes affect Gemini’s outputs. The key takeaway: small tweaks in phrasing = big differences in results.</p><h4>🎥 2. Multimodal Prompting in Vertex AI Studio</h4><p>This lab took it a step further, tapping into Gemini’s <strong>multimodal capabilities</strong>.</p><p>I explored:</p><ul><li><strong>Zero-shot, one-shot, and few-shot prompting</strong> for tasks like question answering and sentiment analysis</li><li><strong>Image and video analysis</strong> using Gemini’s multi-input functionality</li><li>Using <strong>system instructions</strong> to shape tone, format, and behavior — for example, building a lightweight IT support chatbot</li></ul><p>This was a great example of how AI can interpret visual media <em>and</em> return insightful, human-like responses when guided properly.</p><h4>🧪 3. Working with the Gemini API and Vertex AI SDK</h4><p>Here, the course moved into more technical territory.</p><ul><li>Used the <strong>Vertex AI SDK for Python</strong> to connect to the gemini-2.0-flash model</li><li>Built scripts to pass prompts and receive structured responses</li><li>Learned how to manage inputs, system instructions, and response formats via API</li></ul><p>This lab showed me how easy it is to transition from using Gemini in a no-code interface (like Vertex AI Studio) to <strong>production-level workflows using Python</strong>.</p><h4>💡 4. Challenge Lab: Real-World Marketing Use Case</h4><p>The final lab brought all the concepts together in a simulated workplace scenario.</p><p>I helped a fictional company, <strong>Cymbal Direct</strong>, by:</p><ul><li>Designing tools that generate <strong>creative product descriptions</strong> and <strong>catchy taglines</strong></li><li>Editing and running notebook code that analyzed images and used Gemini to produce content tailored to a marketing context</li><li>Applying prompt best practices to ensure the generated outputs were on-brand, relevant, and engaging</li></ul><p>This challenge lab demonstrated how prompt design, when combined with the right APIs and tools, can <strong>unlock massive creative potential for businesses</strong>.</p><h3>💡 Why This Skill Matters</h3><p>Prompt design isn’t just a technical skill — it’s a <strong>communication superpower</strong>. The better your prompts, the better your AI outputs. And with multi-modal models like <strong>Gemini</strong>, it’s now possible to:</p><ul><li>Understand and generate responses from <strong>text, images, and video</strong></li><li>Build custom <strong>AI-powered tools for marketing, support, analysis, and more</strong></li><li>Guide LLMs to behave in specific ways that suit your goals or brand</li></ul><p>Whether you’re building apps, writing content, or automating workflows, <strong>prompt engineering is foundational</strong> to modern AI usage.</p><h3>📌 Final Thoughts</h3><p>Completing the “Prompt Design in Vertex AI” badge gave me a practical, hands-on edge in one of the fastest-growing areas in tech. Google Cloud’s labs offer <strong>real-world scenarios, API-level integration, and enterprise-ready workflows</strong> — and this badge was no exception.</p><p>If you’re serious about building smarter GenAI-powered applications, I highly recommend adding this to your learning path.</p><h3>🔗 Let’s Connect!</h3><p>Are you working with Data or just curious about where Data is heading next?<br>I’d love to exchange ideas and explore future collaborations.<br>Connect with me on LinkedIn — let’s talk Data, prompts, products, and possibilities!</p><p><a href="https://www.linkedin.com/in/jhakamal/">https://www.linkedin.com/in/jhakamal/</a></p><p><strong>#PromptEngineering #GeminiAI #VertexAI #GoogleCloud #GenerativeAI #AIInMarketing #MultimodalAI #SkillBadge #CloudSkillsBoost #PythonAI #AIForBusiness #LLM #PromptDesign #RealWorldAI</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14935bf26190" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Real-World AI with Gemini and Imagen: My Latest Skill Badge]]></title>
            <link>https://datagrad.medium.com/building-real-world-ai-with-gemini-and-imagen-my-latest-skill-badge-69e4166a3673?source=rss-2e63c0c4e906------2</link>
            <guid isPermaLink="false">https://medium.com/p/69e4166a3673</guid>
            <category><![CDATA[imagen]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[google-cloud-skill-badge]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <dc:creator><![CDATA[DataGrad]]></dc:creator>
            <pubDate>Sat, 03 May 2025 07:34:42 GMT</pubDate>
            <atom:updated>2025-05-03T07:34:42.484Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>I Built Real-World GenAI Apps with Gemini and Imagen - and Even Generated a Bouquet!</strong></p><figure><img alt="Build Real World AI Applications with Gemini and Imagen Skill Badge" src="https://cdn-images-1.medium.com/max/356/1*ZU5W9gJSzRFjdquVnzvBlA.png" /><figcaption>Build Real World AI Applications with Gemini and Imagen Skill Badge</figcaption></figure><p>In the world of AI, learning by doing is the best way to keep up with rapid innovation.</p><p>That’s why I recently completed the <a href="https://www.cloudskillsboost.google/course_templates/1076"><strong>Build Real World AI Applications with Gemini and Imagen</strong></a> <a href="https://www.credly.com/badges/07dc02d0-a2ee-4a94-b41f-63e14b83dae6/linked_in?t=svob5t">Skill Badge</a>(<a href="https://www.credly.com/badges/07dc02d0-a2ee-4a94-b41f-63e14b83dae6/linked_in?t=svob5t">Check my Skill Badge here</a>) from <a href="https://medium.com/u/be36e94a7e47">Google</a> via <a href="https://medium.com/u/4f3f4ee0f977">Google Cloud</a><strong> Skills Boost Labs</strong>. This 75-minute hands-on course offered a practical deep dive into <strong>multi-modal AI</strong>, focusing on building intelligent applications with #<strong>Gemini</strong> (for chat and image analysis) and #<strong>Imagen</strong> (for image generation).</p><h3>🧪 What I Built: Course Modules Recap</h3><p>The complete course was designed in 4 modules:</p><ol><li><strong>Image Recognition with Gemini</strong><br>Upload an image, ask questions, and get insightful text responses — using Gemini’s vision + language capabilities.</li><li><strong>Text-to-Image with Imagen</strong><br>Type a prompt and watch the AI generate high-quality images based on your input : all via the Imagen model.</li><li><strong>Chat Application with Gemini</strong><br>I built a conversational app that delivers streaming and non-streaming responses, showing how Gemini handles real-time interactions.</li><li><strong>Challenge Lab: Combine and Deploy</strong><br>The final lab brought it all together challenging me to put all I learnt into a live model, and here’s where it got really fun.</li></ol><h3>🌻 My Challenge Lab Submission: A Bouquet Generator with Birthday Wishes</h3><p>The lab tasked me with building two Python functions : one to generate an image using <strong>Imagen</strong>, and another to analyze the generated image with <strong>Gemini</strong> and generate a custom birthday message.</p><h4>🖼️ generate_bouquet_image(prompt): Generating an AI-Powered Image</h4><p>To kick things off, I used Google’s <strong>Imagen 3.0 model</strong> via the Vertex AI SDK to generate an image based on a custom prompt. The prompt I used was:<br> <strong>“Create an image containing a bouquet of 2 sunflowers and 3 roses.”</strong></p><p>Here’s what I did:</p><ul><li>Initialized the Vertex AI environment with the correct project and region.</li><li>Loaded the pre-trained Imagen model.</li><li>Supplied the prompt to the model, along with parameters like the number of images, seed, and watermark options.</li><li>Captured the generated image and saved it locally as a .jpeg file.</li></ul><p>This step allowed me to create a <strong>visually rich, AI-generated bouquet image</strong>, ready for further processing using Gemini.</p><h4>🧠 2. analyze_bouquet_image(image_path): Interpreting the Image with Gemini</h4><p>Next, I used <strong>Gemini 2.0 Flash</strong>, a multi-modal generative model from Google, to analyze the bouquet image and generate a <strong>personalized birthday message</strong> based on its contents.</p><p>The process involved:</p><ul><li>Re-initializing Vertex AI to ensure the correct configuration.</li><li>Loading the Gemini model for multi-modal input.</li><li>Creating a message that included both a text instruction and the image itself as input.</li><li>Sending this message to Gemini and receiving a real-time, AI-generated birthday greeting.</li></ul><p>What stood out here was Gemini’s ability to <strong>understand visual context</strong> and generate a human-like response that was relevant, contextual, and personalized — a great example of <strong>vision-language fusion</strong> in action.</p><h3>🚀 Final Thoughts</h3><p>This wasn’t just another course — it was a real-world demonstration of how <strong>Generative AI can be used to build practical applications</strong>, from image generation to intelligent chat interfaces. The hands-on labs were brief but incredibly effective in helping me understand how to:</p><ul><li>Use pre-trained GenAI models through Python</li><li>Interact with Vertex AI via SDK</li><li>Develop end-to-end AI apps in under an hour</li></ul><p>If you’re looking to explore multi-modal AI with minimal overhead and maximum hands-on value, I highly recommend this skill badge.</p><p>Thanks to <strong>Google Cloud Skills Boost</strong> and <strong>Hack2Skill</strong> for this opportunity! Can’t wait to build more GenAI applications with Gemini, Imagen, and beyond.</p><h3>📣 Let’s Connect!</h3><p>If you’re exploring <strong>GenAI, multi-modal applications, or the future of AI-powered creativity</strong>, I’d love to connect and exchange ideas.</p><p>Feel free to reach out or connect with me on <a href="https://www.linkedin.com/in/jhakamal/">LinkedIn </a>— always happy to collaborate or chat AI!</p><p><a href="https://www.linkedin.com/in/jhakamal/">https://www.linkedin.com/in/jhakamal/</a></p><p><strong>#GenAI #GeminiAI #Imagen #GoogleCloud #VertexAI #SkillBadge #Hack2Skill #AIApplications #Python #BirthdayBot #ImageGeneration #MachineLearning #NLP #ContinuousLearning #Upskilling #RealWorldAI</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69e4166a3673" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Indexing: The Secret Gear in a Data Scientist’s Engine]]></title>
            <link>https://datagrad.medium.com/indexing-the-secret-gear-in-a-data-scientists-engine-5dddd9d6c2d4?source=rss-2e63c0c4e906------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dddd9d6c2d4</guid>
            <dc:creator><![CDATA[DataGrad]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 12:02:03 GMT</pubDate>
            <atom:updated>2023-11-07T12:02:03.367Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back to our SQL series, where we unravel the intricacies of database operations for data scientists. After navigating the waters of SQL essentials, advanced techniques, subqueries, window functions, and CTEs, it’s time to shift our focus to a feature that quietly underpins the performance of all these operations - <strong>Indexing</strong>.</p><p>Just as a cricket team strategizes player positions for optimal performance, a data scientist must understand indexing to optimize query efficiency.</p><p><strong>What You’ll Learn:</strong></p><blockquote>The Basics of Database Indexing</blockquote><blockquote>Types of Indexes and Their Uses</blockquote><blockquote>Indexing Strategies for Our Cricket Dataset</blockquote><blockquote>The Impact of Indexing on Data Science Tasks</blockquote><blockquote>Best Practices and Common Pitfalls</blockquote><p><strong>Understanding the Dataset</strong> Our trusted cricket dataset is back on the pitch! It’s comprehensive, with columns for match details, player statistics, and scores. As we’ve used this dataset to illustrate previous SQL concepts, it will serve as a perfect example to show how indexing works and why it matters.</p><h3><strong>Section 1: The Basics of Database Indexing</strong></h3><p>Think of an index like the contents page of a book. It helps you quickly locate the information without flipping through every page. In databases, an index serves a similar purpose: it allows the database engine to find and retrieve specific rows much faster than without an index.</p><p><strong>Syntax for Creating an Index:</strong></p><pre>CREATE INDEX idx_column_name <br>ON table_name (column_name);</pre><h3><strong>Section 2: Types of Indexes and Their Uses</strong></h3><p>There are several types of indexes, each with its own strengths and use cases:</p><ul><li><strong>Single-Column Indexes</strong>: Ideal for queries that filter on one column.</li><li><strong>Composite Indexes</strong>: Useful when queries filter on multiple columns.</li><li><strong>Unique Indexes</strong>: Ensures that all values in a column are distinct.</li><li><strong>Full-Text Indexes</strong>: Used for comprehensive text searches in a column.</li><li><strong>Partial Indexes</strong>: Indexes a subset of rows or columns, which is useful for large tables with frequent queries filtering on the same values.</li></ul><p><strong>Example of Creating a Composite Index:</strong></p><pre>CREATE INDEX idx_striker_runs <br>ON cricket_data (striker, runs);</pre><h3><strong>Section 3: Indexing Strategies</strong></h3><p>Optimizing our cricket dataset involves indexing the columns most frequently used in WHERE clauses, JOIN conditions, or as part of an ORDER BY.</p><p><strong>Example: Improving the Performance of a Frequent Query</strong></p><pre>CREATE INDEX idx_match_runs <br>ON cricket_data (match_id, runs);</pre><p>With this index, queries filtering or sorting by match_id and runs will be significantly faster.</p><h3><strong>Section 4: Impact of Indexing on Data Science Tasks</strong></h3><p>Indexing directly affects the speed of data retrieval, which is critical when dealing with large datasets for:</p><ul><li><strong>Predictive Modeling</strong>: Ensuring quick data fetches for training models.</li><li><strong>Real-time Analytics</strong>: Providing swift query responses for dashboards.</li><li><strong>Data Cleaning</strong>: Speeding up search operations for identifying and rectifying data anomalies.</li></ul><h3><strong>Section 5: Best Practices and Common Pitfalls</strong></h3><p>While indexing is powerful, it’s not without its trade-offs. Here are some best practices and pitfalls to watch for:</p><ul><li><strong>Do not Over-Index</strong>: Every index consumes space and can slow down write operations.</li><li><strong>Monitor Index Usage</strong>: Occasionally review index usage stats to remove unused indexes.</li><li><strong>Index Maintenance</strong>: Rebuild or reorganize indexes periodically to maintain performance.</li><li><strong>Consider the Query Load</strong>: Tailor your indexing strategy to the specific queries that are run most often.</li></ul><h3><strong>Conclusion</strong></h3><p>Indexing is akin to a well-tuned engine in a race car, essential for peak performance but requiring expert tuning and maintenance. A thoughtful indexing strategy, tailored to your specific data access patterns, can turn the tide in data processing, making it an indispensable skill in a data scientist’s arsenal. Remember, though, that indexing is part of a broader optimization narrative that includes schema design, query optimization, and system configuration.</p><p>Ready to share your indexing victories or dilemmas? Let’s exchange insights and experiences on <a href="https://www.linkedin.com/in/jhakamal/">LinkedIn</a>. Together, we can navigate the intricacies of database performance and keep our data science engines running at full throttle.</p><blockquote>Until our next analytical adventure — happy querying and efficient indexing!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dddd9d6c2d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CTEs : A Googly for Data Scientists]]></title>
            <link>https://datagrad.medium.com/ctes-a-googly-for-data-scientists-5a764730d10d?source=rss-2e63c0c4e906------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a764730d10d</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[cte]]></category>
            <dc:creator><![CDATA[DataGrad]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 16:09:26 GMT</pubDate>
            <atom:updated>2023-11-04T16:09:26.417Z</atom:updated>
            <content:encoded><![CDATA[<h3>CTEs : A Googly for Data Scientists</h3><p>Welcome back to our SQL series for data scientists! We’ve journeyed through SQL basics, advanced techniques, subqueries, and window functions. Today, let’s explore Common Table Expressions (CTEs) - a feature pivotal for writing clean, readable, and modular SQL queries.</p><p>I most often call CTE as a googly in cricket which serves as an unexpected but strategic move to outwit the batsman, same way, a CTE in SQL offers a clever and modular way to simplify complex queries, catching data challenges off guard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hVoK-jmbnVTj98tHdFwrQ.png" /></figure><h4>What You’ll Learn</h4><ul><li>What Are Common Table Expressions (CTEs)?</li><li>Syntax and Structure of CTEs</li><li>Real-world Examples with Our Cricket Dataset</li><li>Use-Cases in Data Science</li><li>Performance Tips</li></ul><h4>Understanding the Dataset</h4><p>To maintain consistency, we’ll continue using our cricket dataset, which contains columns like match_id, season, start_date, venue, batting_team, bowling_team, and striker.</p><h3>Section 1: What Are Common Table Expressions (CTEs)?</h3><p>Common Table Expressions (CTEs) provide a way to simplify complex queries by breaking them down into smaller, named sub-queries that you can reference within your main query. Think of CTEs as temporary result sets that are only visible to the query where they are defined.</p><p><strong>Syntax and Structure</strong></p><p>The basic syntax for a CTE is:</p><pre>WITH cte_name (column_name1, column_name2, ...)<br>AS (<br>    -- Subquery<br>)<br>-- Main Query using the CTE</pre><h3>Section 2: Real-world Examples with Our Cricket Dataset</h3><p><strong>Example 1: Finding Top Scorers in a Season</strong></p><p>Let’s find the top 5 scorers in the ‘2007/08’ season using a CTE.</p><pre>WITH TopScorers AS (<br>  SELECT striker, SUM(runs) AS total_runs<br>  FROM cricket_data<br>  WHERE season = &#39;2007/08&#39;<br>  GROUP BY striker<br>)<br>SELECT *<br>FROM TopScorers<br>ORDER BY total_runs DESC<br>LIMIT 5;</pre><p><strong>Example 2: Calculating Average Runs Per Match for Each Player</strong></p><pre>WITH PlayerMatchRuns AS (<br>  SELECT match_id, striker, SUM(runs) AS match_runs<br>  FROM cricket_data<br>  GROUP BY match_id, striker<br>),<br>PlayerAvgRuns AS (<br>  SELECT striker, AVG(match_runs) AS avg_runs<br>  FROM PlayerMatchRuns<br>  GROUP BY striker<br>)<br>SELECT * FROM PlayerAvgRuns<br>ORDER BY avg_runs DESC;</pre><h3>Section 3: Use-Cases in Data Science</h3><ol><li><strong>Data Transformation</strong>: CTEs can be effectively used for transforming your data before performing analytics.</li><li><strong>Hierarchical Data</strong>: CTEs can be used for querying hierarchical data using recursive CTEs.</li><li><strong>Debugging</strong>: They make debugging easier as you can isolate different parts of a complex query.</li></ol><h3>Section 4: Performance Tips</h3><ol><li><strong>Avoid Nesting</strong>: Nested CTEs can result in sub-optimal performance.</li><li><strong>Be Mindful of Recursion</strong>: Recursive CTEs can be CPU-intensive.</li><li><strong>Indexes</strong>: Make sure the fields you’re joining on are indexed.</li></ol><p><strong>The CTEs</strong> are the unsung heroes of SQL, bringing clarity and modularity to your queries. Embracing CTEs can elevate your data wrangling skills, letting you approach complex data tasks with newfound ease.</p><p>Let’s keep the conversation going! If you’re keen to discuss CTEs, SQL, or data science in general, connect with me on <a href="http://linkedin.com/in/jhakamal">LinkedIn</a>. I’m always open to collaborating on exciting projects.</p><p>Until our paths cross again in the SQL universe, happy querying!</p><p>Feel free to connect on Linkedin.com/in/jhakamal to collaborate on projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a764730d10d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Window Functions: A PowerPlay for Data Scientists]]></title>
            <link>https://datagrad.medium.com/sql-window-functions-a-powerplay-for-data-scientists-ac87193ca584?source=rss-2e63c0c4e906------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac87193ca584</guid>
            <category><![CDATA[sports-analytics]]></category>
            <category><![CDATA[sql-data-analysis]]></category>
            <category><![CDATA[sql-for-data-science]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql-window-functions]]></category>
            <dc:creator><![CDATA[DataGrad]]></dc:creator>
            <pubDate>Tue, 24 Oct 2023 13:02:45 GMT</pubDate>
            <atom:updated>2023-10-24T13:02:45.696Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back to our SQL series for data scientists! In the previous blogs, we discussed SQL essentials, advanced SQL techniques, and took a deep dive into subqueries. Today, we will explore another powerful feature of SQL that often comes in handy for complex data analytics tasks: Window Functions. These are incredibly powerful tools for anyone dealing with time series, analytics, or generally any form of ordered data.</p><figure><img alt="SQL Window Functions: A PowerPlay for Data Scientists" src="https://cdn-images-1.medium.com/max/1024/1*RCeS33JFwVhbR1AWDqBT6w.jpeg" /><figcaption>SQL Window Functions: A PowerPlay for Data Scientists</figcaption></figure><h4>What You’ll Learn:</h4><blockquote>Introduction to SQL Window Functions</blockquote><blockquote>Types of Window Functions</blockquote><blockquote>Real-world Examples with a Cricket Dataset</blockquote><blockquote>Common Use-cases in Data Science</blockquote><blockquote>Performance Considerations</blockquote><h4>Understanding the Dataset</h4><p>Before we delve into window functions, let’s familiarize ourselves with the dataset we will use. The dataset contains rich information about cricket matches, including but not limited to season, venue, batting and bowling teams, and runs scored.</p><p>Here is a snapshot of the dataset columns:</p><ul><li>match_id: Unique identifier for the match</li><li>season: The season in which the match occurred</li><li>start_date: The start date of the match</li><li>venue: Where the match was played</li><li>innings: Innings number</li><li>striker: The player who is currently batting</li><li>runs_off_bat: Runs scored off the bat by the striker</li></ul><p>… and many more.</p><h3>Section 1: Introduction to SQL Window Functions</h3><p>SQL window functions allow for more flexible and advanced data manipulation tasks, particularly when you’re dealing with time-series or ordered datasets. In the realm of sports analytics, like our cricket dataset, this capability is invaluable for computing rolling averages, rankings, and running totals, among other calculations.</p><p>Unlike aggregate functions, which compress multiple rows into a single value, window functions operate on a set of rows related to the current row within a result set. This “window” of rows can be defined in various ways — based on a fixed number of rows, or relative to values in one or more columns.</p><p><strong>Syntax Specific to Our Cricket Dataset:</strong></p><p>In SQL, a window function query might generally look like this:</p><pre>SELECT <br>       column,<br>       WINDOW_FUNCTION(column) OVER (<br>                                    PARTITION BY column <br>                                    ORDER BY column ROWS <br>                                    BETWEEN N PRECEDING AND M FOLLOWING<br>                                    ) as Window_Name<br>FROM table;</pre><p>For our cricket dataset, let’s say we want to calculate the running total of runs for each player (striker) in a specific season, ordered by the date (start_date) and ball (ball). The SQL query would be:</p><pre>SELECT start_date,<br>       ball,<br>       striker,<br>       runs,<br>       SUM(runs) OVER (<br>                      PARTITION BY striker <br>                      ORDER BY start_date, ball <br>                      ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW<br>                      ) as running_total_runs<br>FROM cricket_data<br>WHERE season = &#39;2007/08&#39;;</pre><p>In this query:</p><ul><li>SUM(runs) is the window function.</li><li>PARTITION BY striker restarts the running total for each player.</li><li>ORDER BY start_date, ball sorts the data within each partition.</li><li>ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW defines the window frame to include all preceding rows up to the current row for each partition.</li></ul><p>This would give us a running total of runs for each player, which can be extremely helpful for in-depth match analysis, player performance evaluation, and other real-world data science applications.</p><h3>Section 2: Types of Window Functions</h3><p>SQL window functions can be broadly categorized into three types:</p><ul><li>Ranking Functions</li><li>Aggregate Functions</li><li>Navigational Functions</li></ul><p>Each serves unique purposes and is instrumental in solving various kinds of analytical problems. Below, I’ve outlined each type with examples based on our cricket dataset.</p><h4><strong>1. Ranking Functions</strong></h4><p>These functions assign a unique rank to each row within a result set based on one or more columns.</p><ul><li><strong>RANK()</strong>: This function provides a unique rank to each row, leaving gaps between ranks when there are duplicates.</li></ul><pre>SELECT <br>  match_id, <br>  striker, <br>  runs, <br>  RANK() OVER (<br>                PARTITION BY match_id <br>                ORDER BY runs DESC<br>              ) AS player_rank <br>FROM cricket_data <br>WHERE season = &#39;2007/08&#39;;</pre><ul><li><strong>DENSE_RANK()</strong>: Similar to RANK(), but does not leave gaps between ranks when there are duplicates.</li></ul><pre>SELECT <br>  match_id, <br>  striker, <br>  runs, <br>  DENSE_RANK() OVER (<br>                    PARTITION BY match_id <br>                    ORDER BY runs DESC<br>                    ) AS player_dense_rank <br>FROM cricket_data <br>WHERE season = &#39;2007/08&#39;;</pre><ul><li><strong>ROW_NUMBER()</strong>: Assigns a unique number to each row, even if there are duplicates, based on the ordering.</li></ul><pre>SELECT <br>  match_id, <br>  striker, <br>  runs, <br>  ROW_NUMBER() OVER (<br>                      PARTITION BY match_id <br>                      ORDER BY runs DESC<br>                    ) AS row_number <br>FROM cricket_data <br>WHERE season = &#39;2007/08&#39;;</pre><h4>2. Aggregate Functions</h4><p>You can use standard SQL aggregate functions as window functions to perform calculations across a set of table rows related to the current row within an SQL query.</p><ul><li><strong>SUM()</strong>: Calculates the running total of a column.</li></ul><pre>SELECT <br>  striker, <br>  runs, <br>  SUM(runs) OVER (<br>                  PARTITION BY striker <br>                  ORDER BY start_date, ball<br>                  ) AS running_total_runs <br>FROM cricket_data <br>WHERE season = &#39;2007/08&#39;;</pre><ul><li><strong>AVG()</strong>: Calculates the running average of a column.</li></ul><pre>SELECT <br>  striker, <br>  runs, <br>  AVG(runs) OVER (<br>                  PARTITION BY striker <br>                  ORDER BY start_date, ball<br>                  ) AS running_avg_runs <br>FROM cricket_data <br>WHERE season = &#39;2007/08&#39;;</pre><h4>3. Navigational Functions</h4><p>Navigational functions allow you to fetch data from a different row than the current row without changing the layout of the result set.</p><ul><li><strong>FIRST_VALUE()</strong>, <strong>LAST_VALUE()</strong>: Fetch the first or last value in a window frame.</li></ul><pre>SELECT <br>  match_id, <br>  striker, <br>  runs, <br>  FIRST_VALUE(runs) OVER (<br>                          PARTITION BY match_id <br>                          ORDER BY ball<br>                          ) AS first_ball_runs, <br>  LAST_VALUE(runs) OVER (<br>                        PARTITION BY match_id <br>                        ORDER BY ball <br>                        ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING<br>                        ) AS last_ball_runs <br>FROM cricket_data <br>WHERE season = &#39;2007/08&#39;;</pre><ul><li><strong>LEAD()</strong>, <strong>LAG()</strong>: Access data in a subsequent or preceding row without a self-join.</li></ul><pre>SELECT <br>    match_id, <br>    striker, <br>    runs, <br>    LAG(runs) OVER (<br>                    PARTITION BY match_id, striker <br>                    ORDER BY ball<br>                    ) AS prev_ball_runs, <br>    LEAD(runs) OVER (<br>                    PARTITION BY match_id, striker <br>                    ORDER BY ball<br>                    ) AS next_ball_runs <br>FROM cricket_data <br>WHERE season = &#39;2007/08&#39;;</pre><p>By mastering these window functions, you’ll be well-equipped to tackle complex analytical questions related to time-series data, rankings, or any scenario requiring calculations over a specific window of rows in a dataset.</p><h3>Section 3: Real-world Examples with a Cricket Dataset</h3><p>Let’s walk through some additional examples using our cricket dataset to understand how these functions can be useful in real-world analytics.</p><p><strong>Example 1: Finding the Cumulative Sum of Runs for Each Player in a Season</strong></p><pre>SELECT striker,<br>       season,<br>       SUM(runs_off_bat) OVER (<br>                              PARTITION BY striker, season <br>                              ORDER BY start_date<br>                              ) AS cum_runs<br>FROM cricket_data;</pre><p><strong>Example 2: Calculating the Running Average of Each Player</strong></p><pre>SELECT striker,<br>       AVG(runs_off_bat) OVER (<br>                               PARTITION BY striker <br>                               ORDER BY start_date <br>                               ROWS BETWEEN 5 PRECEDING AND CURRENT ROW<br>                              ) AS running_avg<br>FROM cricket_data;</pre><h3>Section 4: Common Use-cases in Data Science</h3><p>SQL window functions are versatile and can solve a multitude of problems in data analysis and data manipulation. Here are some of the typical scenarios where they are incredibly useful:</p><h4><strong>1. Time Series Analysis</strong></h4><p>In time series data, you often need to perform calculations that consider a certain “window” of time. For example, you might want to calculate a moving average of stock prices or running totals of monthly sales.</p><ul><li><strong>Moving Average</strong>: Calculating the average over a specified period helps in smoothing out the time-series data.</li></ul><pre>SELECT <br>  start_date, <br>  runs, <br>  AVG(runs) OVER (<br>                  ORDER BY start_date <br>                  ROWS BETWEEN 6 PRECEDING AND CURRENT ROW<br>                  ) AS moving_avg_7day <br>FROM cricket_data <br>WHERE striker = &#39;Player_Name&#39;;</pre><ul><li><strong>Running Total</strong>: Useful for understanding the accumulated value of a variable over time.</li></ul><pre>SELECT <br>  start_date, <br>  runs, <br>  SUM(runs) OVER (<br>                  ORDER BY start_date<br>                  ) AS running_total <br>FROM cricket_data <br>WHERE striker = &#39;Player_Name&#39;;</pre><h4>2. Ranking and Percentile Calculation</h4><p>Whether you’re creating leaderboards for games, analyzing customer engagement, or assessing sales performance, ranking and percentile calculations are crucial.</p><ul><li><strong>Leaderboard</strong>: Ranking players based on their performance in a cricket match.</li></ul><pre>SELECT <br>  match_id,<br>  striker,   <br>  runs, <br>  RANK() OVER (<br>               PARTITION BY match_id <br>               ORDER BY runs DESC<br>              ) AS player_rank <br>FROM cricket_data;</pre><ul><li><strong>Sales Performance</strong>: Finding the top 10% of salespeople in a company.</li></ul><pre>SELECT <br>  salesperson, <br>  revenue, <br>  NTILE(10) OVER (<br>                  ORDER BY revenue DESC<br>                  ) AS percentile <br>FROM sales_data <br>WHERE year = 2023;</pre><h4>3. Data Imputation</h4><p>Missing data is a common issue in real-world data sets. Window functions can be instrumental in filling in the gaps based on surrounding data.</p><ul><li><strong>Forward Fill</strong>: Filling missing values with the next available value.</li></ul><pre>SELECT <br>  date,  <br>  temperature, <br>  COALESCE(temperature, LEAD(temperature) OVER (ORDER BY date)) <br>                                            AS forward_filled_temperature <br>FROM weather_data;</pre><ul><li><strong>Backward Fill</strong>: Filling missing values with the previous available value.</li></ul><pre>SELECT <br>  date, <br>  temperature, <br>  COALESCE(temperature, LAG(temperature) OVER (ORDER BY date)) <br>                                          AS backward_filled_temperature <br>FROM weather_data;</pre><p>By leveraging window functions, data scientists can effectively deal with a range of analytical problems, from simple calculations to complex analytical queries. These functions enable you to produce robust, clean, and insightful datasets ready for advanced analytics.</p><h3>Section 5: Performance Considerations</h3><p>Window functions are immensely powerful, but this power comes at a cost; these operations can be resource-intensive and may lead to performance bottlenecks if not used judiciously. Below are some key considerations to optimize the performance of your queries involving window functions.</p><h4>1. Understanding Query Execution Plan</h4><p>The SQL query execution plan gives you a roadmap of how your query gets executed and what steps the database engine takes to retrieve the required data. Being familiar with the execution plan can help you understand how your window function is affecting query performance.</p><ul><li><strong>Spool Operations</strong>: Look for spool operations in your query plan, as they indicate temporary storage usage, which can be costly.</li><li><strong>Parallelism</strong>: Window functions might prevent parallel execution plans. Be aware of this if you’re running queries on multi-core database systems.</li></ul><h4>2. Indexing Strategy</h4><p>The effectiveness of window functions can be significantly influenced by how well the underlying data is indexed.</p><ul><li><strong>Ordered Index</strong>: Having an index on columns used in the ORDER BY clause of the window function can improve performance.</li><li><strong>Partition Index</strong>: An index on the columns used in the PARTITION BY clause can also expedite data retrieval.</li></ul><h4>3. Limit the Scope</h4><p>Avoid running window functions over the entire dataset if you only need a subset of the data.</p><ul><li><strong>Row Preceding/Following</strong>: Be specific about the window frame by using ROWS BETWEEN N PRECEDING AND M FOLLOWING to limit the rows considered in calculations.</li></ul><pre>SELECT <br>  runs, <br>AVG(runs) OVER (<br>                ORDER BY start_date <br>                ROWS BETWEEN 6 PRECEDING AND CURRENT ROW<br>                ) <br>FROM cricket_data <br>WHERE season = &#39;2021&#39;;</pre><h4>4. Filter Early</h4><p>Apply filters as early as possible to reduce the size of the result set over which the window function operates.</p><ul><li><strong>Subqueries or CTEs</strong>: Use subqueries or Common Table Expressions (CTEs) to filter data before applying window functions.</li></ul><pre>WITH FilteredData AS (<br>    SELECT * <br>    FROM cricket_data <br>    WHERE season = &#39;2021&#39;<br>    ) SELECT <br>          striker, <br>          AVG(runs) OVER (PARTITION BY striker) <br>      FROM FilteredData;</pre><h4>5. Batch Processing</h4><p>For extremely large datasets, consider breaking the operation into smaller batches to improve performance.</p><ul><li><strong>Row Limits</strong>: Use LIMIT and OFFSET to process data in chunks, though be cautious as this might require additional logic for aggregating the final result.</li></ul><p>By keeping these considerations in mind, you can run window functions more efficiently, ensuring that your data pipelines are both robust and performant.</p><h3>Conclusion</h3><p>SQL Window Functions are an advanced feature that can make your data analytics tasks simpler and more expressive. Whether you are working on complex data transformation pipelines or real-time analytics dashboards, mastering window functions will definitely up your SQL game.</p><p>Stay tuned for our next blog, where we will explore another advanced SQL topic: Common Table Expressions (CTEs).</p><blockquote>As always, keep querying and keep exploring!</blockquote><blockquote>Please read the other blogs of this series:</blockquote><blockquote><a href="https://datagrad.medium.com/sql-essentials-for-future-data-scientists-69265e2d09fc"><strong>1. </strong>SQL Essentials for Future Data Scientists</a>,</blockquote><blockquote><a href="https://datagrad.medium.com/advanced-sql-techniques-for-data-scientists-a-deep-dive-6371f9378d30">2. Advanced SQL Techniques for Data Scientists: A Deep Dive</a></blockquote><blockquote>Let’s connect on <a href="https://www.linkedin.com/in/jhakamal/">Linkedin.com/in/jhakamal</a> to collaborate on projects!</blockquote><figure><img alt="https://www.linkedin.com/in/jhakamal/" src="https://cdn-images-1.medium.com/max/992/1*ukePShdhWntBu9-IqlAefg.png" /><figcaption><a href="https://www.linkedin.com/in/jhakamal/">https://www.linkedin.com/in/jhakamal/</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac87193ca584" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Anatomy of SQL Subqueries: A Data Scientist’s Guide]]></title>
            <link>https://datagrad.medium.com/the-anatomy-of-sql-subqueries-a-data-scientists-guide-1d5410736029?source=rss-2e63c0c4e906------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d5410736029</guid>
            <category><![CDATA[sql-subquery]]></category>
            <category><![CDATA[sports-analytics]]></category>
            <category><![CDATA[sql-data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-scientist-skills]]></category>
            <dc:creator><![CDATA[DataGrad]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 13:32:35 GMT</pubDate>
            <atom:updated>2023-10-22T13:32:35.382Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous blogs in this SQL series, we’ve covered <a href="https://datagrad.medium.com/sql-essentials-for-future-data-scientists-69265e2d09fc"><strong><em>SQL essentials</em></strong></a> and <a href="https://datagrad.medium.com/advanced-sql-techniques-for-data-scientists-a-deep-dive-6371f9378d30"><strong><em>Advanced techniques for data scientists</em></strong></a>. Today, we’re going to deep dive into a topic that often intimidates beginners but is extremely powerful once understood — <strong><em>SQL Subqueries</em></strong>. Subqueries allow for more complex operations and can simplify your SQL statements, all while making them more efficient and maintainable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y-ahAfkVIjAj0V6pw_ChXA.jpeg" /><figcaption>The Anatomy of SQL Subqueries: A Data Scientist’s Guide</figcaption></figure><p><strong>What you will learn:</strong></p><blockquote>What is a SQL Subquery?</blockquote><blockquote>When to Use Subqueries?</blockquote><blockquote>Correlated Subqueries</blockquote><blockquote>Common Pitfalls and How to Avoid Them</blockquote><blockquote>Subqueries vs Joins</blockquote><h3>Understanding the Dataset</h3><p>Before we dig into the world of subqueries, let’s get familiar with the dataset we are using for this learning. This dataset contains cricket match data, including details like match ID, season, start date, venue, batting team, bowling team, and so on.</p><p>Here is a sample from our dataset:</p><figure><img alt="Cricket Data Snapshot" src="https://cdn-images-1.medium.com/max/1024/1*kWPYZdgSYF79ZxsR7ujx8g.png" /><figcaption>Cricket Data Snapshot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQ2-PsaYcAktiZY0Ozcigg.png" /><figcaption>Cricket Data Snapshot</figcaption></figure><p><strong>Note</strong>: The table is truncated to show only a subset of columns and rows.</p><h3>Section 1: What is a SQL Subquery?</h3><p>A SQL Subquery, also known as a nested or inner query, is a query within another SQL query. Subqueries enable you to perform more complex tasks and answer multi-layered questions, all within a single SQL command. Let’s start by classifying subqueries into different types based on their use-cases and the kind of data they return.</p><h4>Types of Subqueries</h4><ol><li><strong>Scalar Subqueries</strong>: Returns a single value.</li><li><strong>Row Subqueries</strong>: Returns a single row with multiple columns.</li><li><strong>Column Subqueries</strong>: Returns a single column but with multiple rows.</li><li><strong>Table Subqueries</strong>: Returns entire tables.</li></ol><h4>Scalar Subqueries</h4><p>Suppose you want to find out who scored the most runs in a particular season from our sample cricket dataset. A scalar subquery can help you find this information in a single SQL command.</p><pre>SELECT striker, MAX(runs)<br>FROM cricket_data<br>WHERE season = &#39;2007/08&#39;<br>AND runs = <br>          (<br>            SELECT MAX(runs)<br>            FROM cricket_data<br>            WHERE season = &#39;2007/08&#39;<br>          );</pre><h4>Row Subqueries</h4><p>Let’s say you want to find out which players scored more than the average runs in the ‘2007/08’ season.</p><pre>SELECT striker, runs<br>FROM cricket_data<br>WHERE season = &#39;2007/08&#39; <br>  AND runs &gt; <br>            (<br>              SELECT AVG(runs)<br>              FROM cricket_data<br>              WHERE season = &#39;2007/08&#39;<br>            );</pre><h4>Column Subqueries</h4><p>What if you want to find out all the matches where players from ‘Kolkata Knight Riders’ participated?</p><pre>SELECT match_id, season<br>FROM cricket_data<br>WHERE striker IN <br>                (<br>                  SELECT striker<br>                  FROM cricket_data<br>                  WHERE batting_team = &#39;Kolkata Knight Riders&#39;<br>                );</pre><h4>Table Subqueries</h4><p>If you want to find the average runs scored in matches involving ‘Kolkata Knight Riders’, you might use a table subquery in the FROM clause.</p><pre>SELECT AVG(runs)<br>FROM <br>    (<br>      SELECT runs<br>      FROM cricket_data<br>      WHERE striker IN <br>                      (<br>                        SELECT striker<br>                        FROM cricket_data<br>                        WHERE batting_team = &#39;Kolkata Knight Riders&#39;<br>                      )<br>    ) AS KKR_Matches;</pre><h3>Section 2: When to Use Subqueries?</h3><p>In SQL, there are often multiple ways to achieve the same result. Subqueries are most effective when:</p><ol><li><strong>You need to retrieve a single value for further calculations</strong>: Scalar subqueries are perfect for this.</li><li><strong>You are dealing with hierarchical or relational data</strong>: Subqueries can simplify complex joins.</li><li><strong>You want to perform calculations that involve multiple steps</strong>: Subqueries can break down the problem into smaller, more manageable tasks.</li></ol><p><strong>Example:</strong></p><ul><li><strong>Finding the Top Scorer’s Average Runs in a Season</strong></li></ul><p>Here, we first find out who the top scorer in the ‘2007/08’ season is and then calculate their average runs. We’ll use a scalar subquery to find the top scorer and a main query to find their average runs.</p><pre>SELECT striker, AVG(runs)<br>FROM cricket_data<br>WHERE season = &#39;2007/08&#39; <br>    AND striker = <br>                 (<br>                   SELECT striker<br>                   FROM cricket_data<br>                   WHERE season = &#39;2007/08&#39;<br>                   GROUP BY striker<br>                   ORDER BY SUM(runs) DESC<br>                   LIMIT 1<br>                  );</pre><h3>Section 3: Correlated Subqueries</h3><p>A correlated subquery is a subquery that uses values from the outer query. Essentially, the inner query depends on the outer query.</p><p><strong>Example:</strong></p><ul><li>Finding Players Who Scored More Than Their Team’s Average</li></ul><p>In this example, we want to find out the players who have scored more than the average runs scored by their team in the ‘2007/08’ season.</p><pre>SELECT striker, runs, batting_team<br>FROM cricket_data AS outer_query<br>WHERE season = &#39;2007/08&#39;<br>AND runs &gt; <br>          (<br>            SELECT AVG(runs)<br>            FROM cricket_data AS inner_query<br>            WHERE inner_query.batting_team = outer_query.batting_team<br>            AND inner_query.season = &#39;2007/08&#39;<br>          );</pre><p>In this case, the inner query is correlated with the outer query, as it uses batting_team from the outer query to calculate the team&#39;s average runs.</p><h3>Section 4: Common Pitfalls and How to Avoid Them</h3><p>Subqueries can be powerful but also tricky. Here are some common pitfalls:</p><ol><li><strong>Nesting too Deep</strong>: The deeper you nest your subqueries, the harder they are to read and maintain. Try to limit the nesting levels.</li><li><strong>Performance</strong>: Subqueries can sometimes lead to inefficient queries. Always test the performance of your queries.</li><li><strong>Debugging</strong>: Debugging nested subqueries can be difficult. It’s a good practice to test each subquery individually.</li></ol><p><strong>Example:</strong></p><ul><li>Debugging a Complex Subquery</li></ul><p>If you encounter issues with a complex subquery, you can isolate each subquery and run it independently to verify its output. For instance, in the correlated subquery example above, you could first run the inner query to ensure it gives you the average runs for a specific team.</p><h3>Section 5: Subqueries vs Joins</h3><p>Subqueries and joins often serve similar purposes, but they aren’t always interchangeable. Here’s how to decide when to use which:</p><p><strong>Use Subqueries When</strong>:</p><ul><li>You need to perform a calculation before the main query.</li><li>You want to pull data from multiple tables that aren’t directly related.</li></ul><p><strong>Use Joins When</strong>:</p><ul><li>You’re combining rows from different tables based on a related column.</li><li>You don’t need to perform calculations before the main query.</li></ul><p><strong>Example: </strong>Using a Join Instead of a Subquery</p><ul><li>Here’s how you could find players who scored more than their team’s average runs in the ‘2007/08’ season using a JOIN:</li></ul><pre>SELECT o.striker, o.runs, o.batting_team<br>FROM cricket_data AS o<br>JOIN <br>    (<br>      SELECT batting_team, AVG(runs) AS team_avg<br>      FROM cricket_data<br>      WHERE season = &#39;2007/08&#39;<br>      GROUP BY batting_team<br>    ) AS i<br>ON o.batting_team = i.batting_team<br>WHERE o.runs &gt; i.team_avg<br>AND o.season = &#39;2007/08&#39;;</pre><h3>Conclusion</h3><p>Subqueries are an essential tool for data scientists who aim to write versatile, efficient, and clean SQL code. Mastering subqueries can significantly streamline your data manipulation and extraction tasks, making you more proficient in dealing with complex datasets like our cricket series example. Whether you’re calculating aggregates, filtering data, or dealing with hierarchical data, subqueries offer a robust way to simplify your SQL queries while also making them more powerful.</p><p>As always, keep querying and keep exploring!</p><blockquote>#datascience #datascientist #SportsAnalytics #SQL</blockquote><blockquote>Please read the other blogs of this series:</blockquote><blockquote><a href="https://datagrad.medium.com/sql-essentials-for-future-data-scientists-69265e2d09fc"><strong>1. </strong>SQL Essentials for Future Data Scientists</a>,</blockquote><blockquote><a href="https://datagrad.medium.com/advanced-sql-techniques-for-data-scientists-a-deep-dive-6371f9378d30">2. Advanced SQL Techniques for Data Scientists: A Deep Dive</a></blockquote><blockquote>Let’s connect on <a href="https://www.linkedin.com/in/jhakamal/">Linkedin.com/in/jhakamal</a> to collaborate on projects!</blockquote><figure><img alt="https://www.linkedin.com/in/jhakamal/" src="https://cdn-images-1.medium.com/max/992/1*ukePShdhWntBu9-IqlAefg.png" /><figcaption><a href="https://www.linkedin.com/in/jhakamal/">https://www.linkedin.com/in/jhakamal/</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d5410736029" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>