<?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 Abhishek Manjunath  on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Manjunath  on Medium]]></description>
        <link>https://medium.com/@abhishek.manjunath.1999?source=rss-2bce226f8fcc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VfU1wcSj1_ao89uobuZuaA.png</url>
            <title>Stories by Abhishek Manjunath  on Medium</title>
            <link>https://medium.com/@abhishek.manjunath.1999?source=rss-2bce226f8fcc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:43:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhishek.manjunath.1999/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[Understanding the Model Context Protocol: Tools, Resources, and Prompts]]></title>
            <link>https://medium.com/@abhishek.manjunath.1999/understanding-the-model-context-protocol-tools-resources-and-prompts-f35c34632f62?source=rss-2bce226f8fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f35c34632f62</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <dc:creator><![CDATA[Abhishek Manjunath ]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 00:02:17 GMT</pubDate>
            <atom:updated>2025-12-13T00:02:17.708Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The three primitives that extend Claude’s capabilities</em></p><h3>What is MCP?</h3><p>The Model Context Protocol (MCP) is a standardized way to extend AI assistants like Claude with custom capabilities. Instead of building separate integrations for every AI model and every data source, MCP provides one universal protocol.</p><p>Think of it as <strong>USB for AI</strong> , one standard that connects everything.</p><h3>The Three Primitives: Who Controls What</h3><p>MCP’s elegance comes from recognizing that different capabilities need different control mechanisms. The protocol defines three primitives, each controlled by a different part of your stack:</p><h3>Tools: The AI’s Capabilities</h3><p><strong>Tools are controlled by Claude.</strong> When you expose a tool, you’re telling Claude: “Here’s something you can do, decide when to use it.”</p><h3>How They Work</h3><p>You give Claude a new capability, and Claude autonomously decides when it’s appropriate to use it. When you ask Claude to “calculate the square root of 3 using JavaScript,” Claude recognizes it needs computational power, finds a JavaScript execution tool, and uses it.</p><h3>Example: Document Management</h3><ul><li><strong>Read Document</strong>: Claude can retrieve document contents when needed</li><li><strong>Edit Document</strong>: Claude can modify documents when asked</li><li><strong>Search Documents</strong>: Claude can find relevant documents across a repository</li></ul><p>The key: You don’t script exact sequences. Claude makes intelligent decisions about when to employ these capabilities based on context.</p><h3>Resources: Your Application’s Data</h3><p><strong>Resources are controlled by your application code.</strong> They represent data that your app decides when to fetch and how to use.</p><h3>How They Work</h3><p>Resources are like a structured file system Claude can access. Your application pulls this data on-demand to populate UI elements or enrich conversations.</p><h3>Example: Document Management</h3><ul><li><strong>Document List</strong>: Your app fetches this to show autocomplete options in the UI</li><li><strong>Document Content</strong>: When users click “Add to context,” your app fetches and injects it into the conversation</li></ul><p>Resources use URI addressing (like document://report.pdf or documents://list), making them discoverable and hierarchical.</p><p><strong>Real-world example</strong>: The “Add from Google Drive” feature in Claude’s interface. Your application code determines which documents to show and handles injecting their content — Claude doesn’t decide this.</p><h3>Prompts: User-Triggered Workflows</h3><p><strong>Prompts are controlled by users.</strong> They’re predefined, expert-crafted instruction sets that users can trigger with a single click.</p><h3>How They Work</h3><p>You’ve perfected a way to ask Claude to summarize documents or analyze data. Instead of users typing detailed instructions every time, they click a button or use a slash command.</p><h3>Example: Document Management</h3><ul><li><strong>Summarize Document</strong>: A carefully crafted template that instructs Claude to create structured summaries with main points, key takeaways, and action items</li><li><strong>Convert to Markdown</strong>: A prompt that guides Claude through converting documents with specific formatting standards</li></ul><p><strong>Real-world example</strong>: Those workflow buttons below Claude’s chat input. Click one, and you trigger a sophisticated, pre-optimized interaction pattern.</p><h3>Choosing the Right Primitive</h3><p>The decision is simple:</p><ul><li><strong>Want to give Claude new autonomous capabilities?</strong> → <strong>Tool</strong></li><li><strong>Need data in your app for UI or context?</strong> → <strong>Resource</strong></li><li><strong>Want to create reusable workflows for users?</strong> → <strong>Prompt</strong></li></ul><h3>A Complete Example: Document Server</h3><p>Imagine building a document management system that connects Claude to your internal repository:</p><p><strong>Tools</strong> give Claude the power to:</p><ul><li>Read any document when needed</li><li>Edit documents based on user requests</li><li>Search across all documents</li></ul><p><strong>Resources</strong> let your application:</p><ul><li>Show document lists in autocomplete dropdowns</li><li>Inject document content into conversations</li><li>Display document metadata in the UI</li></ul><p><strong>Prompts</strong> give users:</p><ul><li>One-click document summarization</li><li>Instant markdown conversion</li><li>Consistent analysis workflows</li></ul><p>Three primitives, three controllers, one seamless experience.</p><h3>Why This Matters</h3><p>MCP represents a fundamental shift in AI integration:</p><ul><li><strong>One protocol, infinite possibilities</strong>: Build once, work with any MCP-compatible AI</li><li><strong>Clear separation of concerns</strong>: AI controls tools, apps control resources, users control prompts</li><li><strong>Extensibility without complexity</strong>: Add capabilities by exposing new primitives</li></ul><p>Instead of rigid integrations, you get flexible, composable systems. Instead of rebuilding for every AI model, you build once and it works everywhere.</p><h3>Get Started</h3><p>The complete implementation of a document management MCP server is available on GitHub, demonstrating all three primitives in action.</p><p><a href="https://github.com/manjunath-ab/MCP/tree/main/cli_project"><strong>View the implementation</strong></a></p><p>Start simple: build one tool, test it, use it. Then add resources and prompts. Each iteration teaches you how Claude interprets and uses your capabilities.</p><p><em>MCP is the foundation. What you build on it is limited only by your imagination.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f35c34632f62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Bruno: A Holistic Approach to AI-Powered Mental Health Support]]></title>
            <link>https://medium.com/@abhishek.manjunath.1999/building-bruno-a-holistic-approach-to-ai-powered-mental-health-support-22b62acc5765?source=rss-2bce226f8fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/22b62acc5765</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Abhishek Manjunath ]]></dc:creator>
            <pubDate>Wed, 15 May 2024 17:00:24 GMT</pubDate>
            <atom:updated>2024-05-15T17:00:24.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNBADfPZVKxkTojfStvuYQ.jpeg" /></figure><h3><strong>Introduction</strong></h3><p>In an era marked by heightened awareness of mental health challenges, the demand for accessible and empathetic support systems has never been greater. Bruno emerges as a pioneering solution, leveraging state-of-the-art technology to offer users a supportive and non-judgmental space for fostering emotional well-being and personal introspection. This article delves into the intricacies of Bruno’s development, highlighting the steps involved in harnessing the power of conversation AI based on Retrieval-augmented generation (RAG) to revolutionize mental health support.</p><p>link to github repo: <a href="https://github.com/manjunath-ab/Bruno_Mental_Health_ChatBot">manjunath-ab/Bruno_Mental_Health_ChatBot (github.com)</a></p><h3>Gathering Insights — Web Scraping &amp; Schema Extraction</h3><p>Bruno’s foundation is built upon a rich tapestry of mental health insights sourced from diverse websites and blogs. Leveraging sophisticated web scraping techniques powered by Selenium, Bruno scours the digital landscape to gather a treasure trove of data. To structure this wealth of information, LangChain and OpenAI’s Language Learning Model (LLM) collaborate to generate a schema for structured data extraction, ensuring coherence and relevance in the subsequent processing stages.</p><h3>Streamlining Efficiency — Preprocessing</h3><p>Efficiency is paramount in the preprocessing stage, where raw data undergoes transformation and refinement to prepare it for downstream analysis. Bruno implements threading for parallel processing of scraped data, optimizing throughput and enhancing overall efficiency. Null rows and values are meticulously removed to uphold data quality standards, laying a robust foundation for subsequent data orchestration and analysis.</p><h3>Orchestrating Complexity — Data Orchestration</h3><p>Data orchestration is a symphony of coordination and scheduling, where pipelines converge to consolidate disparate datasets into a harmonious whole. Bruno leverages Dagster, a powerful orchestration framework, to schedule pipelines for data consolidation seamlessly. By orchestrating the flow of data with precision and efficiency, Bruno ensures that insights are derived promptly and accurately, empowering users with timely support and guidance.</p><h3>Optimizing Performance — Snowflake Optimization</h3><p>Snowflake optimization represents the culmination of Bruno’s data engineering journey, where performance meets precision in a symphony of efficiency. Loaded into Snowflake’s staging area, consolidated data awaits its transformation into actionable insights. Executing a copy into subroutines, Bruno prioritizes performance optimization, minimizing latency and maximizing throughput. By aligning staging data with Snowflake’s clustering keys, Bruno optimizes data loading efficiency, surpassing traditional loading methods with unparalleled speed and accuracy.</p><h3>Crafting the Foundation — Knowledge Base Preparation</h3><p>The journey begins with the meticulous curation of Bruno’s knowledge base, a repository teeming with mental health-related insights sourced from diverse sources such as blogs and websites. Employing cutting-edge techniques like OpenAI’s extraction chain, the data undergoes rigorous processing, ensuring relevance, accuracy, and accessibility for users seeking guidance and support.</p><h3>Embedding and Storage — Building a Robust Infrastructure</h3><p>With the knowledge base primed and ready, the next step involves embedding the processed information using OpenAI’s text embedding model. These embeddings are then efficiently stored in a ChromaDB vector database, laying the groundwork for seamless knowledge retrieval based on vector similarity. This robust infrastructure forms the backbone of Bruno’s ability to deliver personalized and contextually relevant responses to user queries.</p><h3>User Interaction and Knowledge Retrieval — Navigating the Conversation Landscape</h3><p>As users engage with Bruno through the chatbot interface, their messages are dynamically embedded using the same OpenAI embedding model. Leveraging the power of ChromaDB, Bruno swiftly sifts through the vast expanse of its knowledge base to retrieve the most pertinent information aligned with the user’s query. Through advanced techniques like reranking using the Cohere reranker, Bruno ensures that the retrieved knowledge chunks are not only relevant but also semantically coherent, enhancing the overall user experience.</p><h3>Language Generation — Fostering Empathy and Understanding</h3><p>At the heart of Bruno’s conversational prowess lies the OpenAI GPT-3.5 language model, a sophisticated tool capable of generating nuanced and empathetic responses that resonate with users on a personal level. By synthesizing the user’s input with the reranked knowledge chunks, Bruno crafts responses imbued with empathy, understanding, and support, fostering meaningful connections and facilitating genuine introspection.</p><h3>From Conversation to Action — Empowering Users Through Appointment Scheduling</h3><p>Beyond offering emotional support, Bruno empowers users to take tangible steps towards their mental well-being through seamless appointment scheduling. Integrating with the Google Calendar API, Bruno guides users through the process of selecting available dates and times, facilitating the creation of calendar events for scheduled appointments. This seamless transition from conversation to action underscores Bruno’s commitment to holistic mental health support.</p><h3><strong>Safeguarding User Well-being — Ensuring Quality and Safety</strong></h3><p>As custodians of user well-being, ensuring the quality and safety of Bruno’s interactions is paramount. Through rigorous evaluation using tools like DeepEval from ConfidentAI, Bruno’s responses are scrutinized across multiple dimensions including hallucination, bias, answer relevancy, and toxicity. This rigorous assessment framework enables continuous refinement and enhancement, reinforcing Bruno’s role as a trusted ally in the journey towards mental well-being.</p><h3>Empowering Administrators — Insights Through Business Analytics Dashboard</h3><p>In addition to user-centric features, Bruno equips administrators with valuable insights through a comprehensive Business Analytics dashboard. This dashboard offers a holistic view of key metrics such as appointment trends, therapist availability, and specialization distribution, empowering administrators to make informed decisions and optimize the platform’s efficacy and reach.</p><h3>Conclusion</h3><p>As we navigate the complexities of mental health support in the digital age, Bruno stands as a beacon of hope and innovation, transcending traditional boundaries to offer users a lifeline of compassion, understanding, and empowerment. By harnessing the power of AI-driven conversation and leveraging a robust infrastructure fortified by cutting-edge technologies, Bruno embodies a holistic approach to mental health support, transforming the landscape of emotional well-being one conversation at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22b62acc5765" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking Down SQL queries part 2]]></title>
            <link>https://medium.com/@abhishek.manjunath.1999/breaking-down-sql-queries-part-2-11611b7ce6e3?source=rss-2bce226f8fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/11611b7ce6e3</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[stratascratch]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Abhishek Manjunath ]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 05:48:52 GMT</pubDate>
            <atom:updated>2023-03-10T05:48:52.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*2zojf1TM8I4mnHB7TUku9A.png" /></figure><h3>Acceptance Rate By Date</h3><h4>Step 1: Understand the Problem</h4><p>The problem we are trying to solve is to find the overall friend acceptance rate by date. We have a table of Facebook friend requests that contains the action taken by the receiver for each request, either ‘sent’ or ‘accepted’. We need to calculate the acceptance rate for each date the request was sent and order the result by the earliest date to latest.</p><h4>Step 2: Analyze the Data To start,</h4><p>we need to understand the structure of our data. The table we are working with is called “fb_friend_requests” and contains the following columns:</p><ul><li>user_id_sender: ID of the user who sent the friend request</li><li>user_id_receiver: ID of the user who received the friend request</li><li>action: the action taken by the receiver, either ‘sent’ or ‘accepted’</li><li>date: the date the friend request was sent</li></ul><h4>Step 3: Write the SQL Query</h4><p>We can use a Common Table Expression (CTE) to simplify the query and break it down into smaller parts. The CTE will also help us to reuse the results of our calculations later in the query.</p><p>Let’s start by creating the first CTE that counts the number of requests sent and accepted for each user pair. We can use the COUNT() function with a CASE statement to count the number of ‘sent’ and ‘accepted’ actions separately. Here is the code:</p><pre>WITH cte AS (<br>  SELECT *,<br>    COUNT(CASE WHEN action = &#39;sent&#39; THEN 1 ELSE NULL END) OVER (PARTITION BY user_id_sender, user_id_receiver) AS ts,<br>    COUNT(CASE WHEN action = &#39;accepted&#39; THEN 1 ELSE NULL END) OVER (PARTITION BY user_id_sender, user_id_receiver) AS ta<br>  FROM fb_friend_requests<br>)</pre><p>In this code, we create a CTE named “cte” that selects all columns from the “fb_friend_requests” table and adds two new columns, “ts” and “ta”. The COUNT() function is used with a CASE statement to count the number of ‘sent’ and ‘accepted’ actions separately for each user pair. We use the OVER() clause to specify the window function partitioned by the sender and receiver IDs.</p><p>Next, let’s create the second CTE that sums the number of requests sent and accepted for each date. We can use the SUM() function to calculate the total number of requests sent and accepted for each date. Here is the code:</p><pre>WITH cte AS (<br>  SELECT *,<br>    COUNT(CASE WHEN action = &#39;sent&#39; THEN 1 ELSE NULL END) OVER (PARTITION BY user_id_sender, user_id_receiver) AS ts,<br>    COUNT(CASE WHEN action = &#39;accepted&#39; THEN 1 ELSE NULL END) OVER (PARTITION BY user_id_sender, user_id_receiver) AS ta<br>  FROM fb_friend_requests<br>),<br>cte1 AS (<br>  SELECT date, ts, ta,<br>    SUM(ts) OVER (PARTITION BY date) AS ts1,<br>    SUM(ta) OVER (PARTITION BY date) AS ta1<br>  FROM cte<br>  WHERE action = &#39;sent&#39;<br>)</pre><h4>Step 4: Retrieve the Results</h4><p>Now that we have created our two CTEs, we can retrieve the results by selecting the “date” and “ta1/ts1” columns from the “cte1” CTE. Here is the final SQL query:</p><pre>WITH cte AS (<br>  SELECT *,<br>    COUNT(CASE WHEN action = &#39;sent&#39; THEN 1 ELSE NULL END) OVER (PARTITION BY user_id_sender, user_id_receiver) AS ts,<br>    COUNT(CASE WHEN action = &#39;accepted&#39; THEN 1 ELSE NULL END) OVER (PARTITION BY user_id_sender, user_id_receiver) AS ta<br>  FROM fb_friend_requests<br>),<br>cte1 AS (<br>  SELECT date, ts, ta,<br>    SUM(ts) OVER (PARTITION BY date) AS ts1,<br>    SUM(ta) OVER (PARTITION BY date) AS ta1<br>  FROM cte<br>  WHERE action = &#39;sent&#39;<br>)<br>SELECT DISTINCT date, ta1/ts1 AS percentage<br>FROM cte1<br>ORDER BY date;</pre><p>In this code, we first define our two CTEs as described earlier. Then, we select the “date” and the acceptance rate calculated as “ta1/ts1” from the “cte1” CTE. We use the DISTINCT keyword to remove any duplicate dates from the result set. Finally, we order the result set by date in ascending order using the ORDER BY clause.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11611b7ce6e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking down a SQL question in Interviews]]></title>
            <link>https://medium.com/@abhishek.manjunath.1999/breaking-down-a-sql-question-in-interviews-298dd6b9f1be?source=rss-2bce226f8fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/298dd6b9f1be</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Abhishek Manjunath ]]></dc:creator>
            <pubDate>Thu, 09 Mar 2023 05:00:00 GMT</pubDate>
            <atom:updated>2023-03-09T05:00:00.435Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*2zojf1TM8I4mnHB7TUku9A.png" /></figure><h3>Premium vs Freemium</h3><p>Find the total number of downloads for paying and non-paying users by date. Include only records where non-paying customers have more downloads than paying customers. The output should be sorted by earliest date first and contain 3 columns date, non-paying downloads, paying downloads.</p><h4>Tables:</h4><h4>ms_user_dimension</h4><p>user_id:int</p><p>acc_id:int</p><h4>ms_acc_dimension</h4><p>acc_id:int</p><p>paying_customer:varchar</p><h4>ms_download_facts</h4><p>date:datetime</p><p>user_id:int</p><p>downloads:int</p><h4>Step 1: Understand the problem statement</h4><p>The problem statement asks us to find the total number of downloads for paying and non-paying users by date. We need to join three tables, namely ms_user_dimension, ms_acc_dimension, and ms_download_facts to get the required data. We also need to filter the records where non-paying customers have more downloads than paying customers. Finally, the output should be sorted by earliest date first and contain 3 columns: date, non-paying downloads, paying downloads.</p><h4><strong>Step 2: Join the necessary tables</strong></h4><p>The first step is to join the three tables: ms_user_dimension, ms_acc_dimension, and ms_download_facts. We can achieve this using the following SQL query:</p><pre>SELECT *<br>FROM ms_user_dimension user<br>INNER JOIN ms_acc_dimension acc ON user.acc_id = acc.acc_id<br>INNER JOIN ms_download_facts facts ON facts.user_id = user.user_id;</pre><p>This query will return all the columns from all three tables joined together.</p><h4>Step 3: Calculate the total number of downloads by date</h4><p>Next, we need to calculate the total number of downloads by date for paying and non-paying customers. We can use the SUM function to calculate the total number of downloads for each customer type and OVER (PARTITION BY date) to group the results by date. Here&#39;s the code for this step:</p><pre>SELECT date,<br>       SUM(CASE WHEN acc.paying_customer = &#39;no&#39; THEN facts.downloads ELSE NULL END) OVER (PARTITION BY date) AS np,<br>       SUM(CASE WHEN acc.paying_customer = &#39;yes&#39; THEN facts.downloads ELSE NULL END) OVER (PARTITION BY date) AS p<br>FROM ms_user_dimension user<br>INNER JOIN ms_acc_dimension acc ON user.acc_id = acc.acc_id<br>INNER JOIN ms_download_facts facts ON facts.user_id = user.user_id;</pre><p>This query will return three columns: date, np (total number of downloads by non-paying customers), and p (total number of downloads by paying customers) grouped by date.</p><h4>Step 4: Filter the records where non-paying customers have more downloads than paying customers</h4><p>Now we need to filter the records where non-paying customers have more downloads than paying customers. We can achieve this using a WHERE clause and comparing the np and p columns. Here&#39;s the SQL code for this step:</p><pre>WITH cte AS (<br>  SELECT date,<br>         SUM(CASE WHEN acc.paying_customer = &#39;no&#39; THEN facts.downloads ELSE NULL END) OVER (PARTITION BY date) AS np,<br>         SUM(CASE WHEN acc.paying_customer = &#39;yes&#39; THEN facts.downloads ELSE NULL END) OVER (PARTITION BY date) AS p<br>  FROM ms_user_dimension user<br>  INNER JOIN ms_acc_dimension acc ON user.acc_id = acc.acc_id<br>  INNER JOIN ms_download_facts facts ON facts.user_id = user.user_id<br>)<br>SELECT DISTINCT date, np, p<br>FROM cte<br>WHERE np &gt; p;</pre><p>This query will return the desired output sorted by the earliest date first, with three columns: date, np, and p.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=298dd6b9f1be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day1:SQL Practice Questions For Interviews]]></title>
            <link>https://medium.com/@abhishek.manjunath.1999/day1-sql-practice-questions-for-interviews-c7fe3a2410f1?source=rss-2bce226f8fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7fe3a2410f1</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[stratascratch]]></category>
            <category><![CDATA[window-functions]]></category>
            <category><![CDATA[cte]]></category>
            <dc:creator><![CDATA[Abhishek Manjunath ]]></dc:creator>
            <pubDate>Tue, 07 Mar 2023 16:03:51 GMT</pubDate>
            <atom:updated>2023-03-07T16:03:51.633Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey guys,Lets go through some SQL questions that appeared in interviews and break them down step-by-step</p><blockquote>1.Find the email activity rank for each user. Email activity rank is defined by the total number of emails sent. The user with the highest number of emails sent will have a rank of 1, and so on. Output the user, total emails, and their activity rank. Order records by the total emails in descending order. Sort users with the same number of emails in alphabetical order. In your rankings, return a unique value (i.e., a unique rank) even if multiple users have the same number of emails.</blockquote><blockquote>id:int</blockquote><blockquote>from_user:varchar</blockquote><blockquote>to_user:varchar</blockquote><blockquote>day:int</blockquote><p>This is how I would break down the problem:</p><p>we know that if we get the count of the from_user then we will know the number of emails sent by that user.So lets first consider this query</p><pre>SELECT from_user, COUNT(from_user) OVER (PARTITION BY from_user) AS c <br>FROM google_gmail_emails</pre><p>This will give us the count for every row.Now we clean up the duplicates by using DISTINCT keyword</p><pre>SELECT DISTINCT from_user, COUNT(from_user) OVER (PARTITION BY from_user) AS c <br>FROM google_gmail_emails</pre><p>Next, we need the rank of each user based on the count of emails, I will wrap the previous snippet of code in a CTE and use the rank() window function to finish it up</p><pre>WITH CTE AS(<br>SELECT DISTINCT from_user, COUNT(from_user) OVER (PARTITION BY from_user) AS c <br>FROM google_gmail_emails<br>)<br>SELECT from_user,c,rank() OVER (order by c DESC,from_user) as rnk from CTE</pre><p>We are ordering it by the count first and then the from_user, this ensures that we will get a unique rank for every user.</p><blockquote>2.Find the 3 most profitable companies in the entire world. Output the result along with the corresponding company name. Sort the result based on profits in descending order.</blockquote><blockquote>company:varchar</blockquote><blockquote>sector:varchar</blockquote><blockquote>industry:varchar</blockquote><blockquote>continent:varchar</blockquote><blockquote>country:varchar</blockquote><blockquote>marketvalue:float</blockquote><blockquote>sales:float</blockquote><blockquote>profits:float</blockquote><blockquote>assets:float</blockquote><blockquote>rank:int</blockquote><blockquote>forbeswebpage:varchar</blockquote><p>For this problem,the solution is rather simple</p><pre>select top 3 company,profits from forbes_global_2010_2014 order by profits desc;</pre><p>Note that “top 3” is an expression to limit the number of rows in SQL Server</p><blockquote>3.You have been asked to find the job titles of the highest-paid employees.</blockquote><blockquote>Your output should include the highest-paid title or multiple titles with the same salary.</blockquote><blockquote>worker(table):</blockquote><blockquote>worker_id:int</blockquote><blockquote>first_name:varchar</blockquote><blockquote>last_name:varchar</blockquote><blockquote>salary:int</blockquote><blockquote>joining_date:datetime</blockquote><blockquote>department:varchar</blockquote><blockquote>title(table):</blockquote><blockquote>worker_ref_id:int</blockquote><blockquote>worker_title:varchar</blockquote><blockquote>affected_from:datetime</blockquote><p>In our solutions we will be avoiding the use of sub queries and using window functions and cte</p><pre>select t.worker_title,rank() over (order by salary desc) as rnk from worker w inner join title t on <br>w.worker_id=t.worker_ref_id</pre><p>we first use this approach to get the top salary using the rank window function.Lets wrap it up in a CTE and select what is needed</p><pre>WITH CTE AS(<br>select t.worker_title,rank() over (order by salary desc) as rnk from worker w inner join title t on <br>w.worker_id=t.worker_ref_id<br>)<br>SELECT worker_title from cte where rnk=1</pre><h4>Edge Cases To Consider:</h4><ul><li><strong>First position tie:</strong> Your solution should account for the possibility that two or more employees have the same salary.</li></ul><p>This solution accounts for the same using the rank function and ordering it only by salary.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7fe3a2410f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design a Database for Flight Booking System from Scratch | by Abhishek Manjunath]]></title>
            <link>https://medium.com/@abhishek.manjunath.1999/design-a-database-for-flight-booking-system-from-scratch-8f0e900ac9df?source=rss-2bce226f8fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f0e900ac9df</guid>
            <category><![CDATA[database-development]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Abhishek Manjunath ]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 23:07:40 GMT</pubDate>
            <atom:updated>2023-07-10T19:03:35.551Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design a Database for Flight Booking System from Scratch</h3><p><strong>Background:</strong></p><p>The procedure of making a flight reservation is a complicated one in today’s society. Airlines require a method of managing everything in order to handle bookings from eager passengers on a continuous basis. The way records are kept has changed significantly over time as a result of technical advancements, such as the introduction of computers, which allowed airlines to abandon manual procedures.</p><p><strong>Objectives:</strong></p><p>a. Keeping track of and securely keeping booking records.<br>b. The database should make it simple to recover and retrieve booking information.<br>c. Data loss will be prevented, and data integrity will be upheld, removing the possibility of data corruption.<br>d. Reducing data entry errors that could have an impact on the data that’s stored in the system.<br>e. Only authorized users will be able to access the information via the automated flight booking system.<br>f. Reduce duplication by keeping a centralized database and only saving data once.<br>g.Reduces paperwork.</p><p><strong>Purpose:</strong></p><p>This project’s main objective is to save paperwork while still giving consumers a straightforward way to look for and book flights. Users can check their tickets and reservations, receive information on ticket prices, and retrieve data on several flights that are available at various times on a given date using this database. It stores all the information needed to plan a trip, including the source, destination, and any layovers.<br>It will store, organize, and manage a sizable amount of data, including a database of multiple flights, in order to maintain a vast scale of data.</p><p><strong>Initial ERD Design:</strong></p><p><strong>Discussed Business Problem :</strong></p><ol><li>A Flight Booking System will keep a track and maintain booking of records efficiently and safely.</li><li>Booking details should be easily recoverable and retrievable from the database.</li><li>Airlines need to constantly process bookings from expectant passengers, they need a means of keeping on top of everything. Therefore, storing the records of flight schedules and passenger details will keep the data organized.</li><li>The automated flight booking system will allow only authorized users to access the information.</li><li>The system reduces redundancy by maintaining a centralized database and storing all information only once.</li></ol><p><strong>Entities Present:</strong></p><ol><li>Airport</li><li>Passenger</li><li>Flight_Details</li><li>Flight_Service</li><li>Seat_Details</li><li>Flight_Cost</li><li>Reservation</li><li>Travel_Class</li><li>Calendar</li><li>Payment</li><li>Payment_Status</li><li>Service_Offering</li></ol><p><strong>Relationships between entities:</strong></p><ol><li>An airport manages multiple flights. An airport may or may not have a flight landing/takeoff. Hence, it’s optional. Whereas for flight details, it is mandatory to have one airport association.</li><li>A flight may offer multiple services and each service may be offered to many flights.</li><li>A flight comprises multiple seats. It is mandatory that the flight consists of a seat. For Seat details to exist, it is mandatory that it is linked to at least one flight.</li><li>A passenger can make multiple reservations for a flight. Passengers may or may not reserve a flight. However, it is mandatory that reservation has to be associated with only one passenger.</li><li>Reservation confirms the Seat Details. It is mandatory that a reservation is linked with a Seat. A seat may or may not be linked with a reservation. One seat can only be linked to one reservation.</li><li>A travel class should consist of multiple seats. A seat should be linked to only one travel class.</li><li>A Payment may consist of multiple payment status. Whereas, a payment status should have a Payment associated with it.</li><li>A Payment Status should have a Reservation. A reservation may consist of multiple payment status.</li><li>The Flight cost should be determined from the Calendar.</li><li>The Seat Details should be associated with a Flight cost. The Flight Cost is calculated based on the Seat Details.</li></ol><p><strong>Key Design:</strong></p><ol><li>Each Airport can have multiple flight details associated with its respective source and destination.</li><li>Each Flight may offer many flight services like Food Service, Entertainment Service, Wifi Service etc. Each Flight_Service may be offered to many flights. Service_Offering is an associative entity which stores Service_ID and Flight_ID.</li><li>Each Flight mandatorily comprises one or many seats and each seat is associated with a particular Travel_Class_ID. A seat can belong to Business class or economy class etc.</li><li>Each passenger may or may not make multiple reservations. If a passenger makes a reservation, a seat of the passenger’s choice will be assigned. The Seat_Details will point to Travel_Class and Flight_Details. For each seat reserved, a passenger may or may not pay to confirm the seat. A passenger can reserve one seat per Reservation_ID.</li><li>Payment_Status is an associative entity which holds the information related to particular Reservation_ID and Payment_ID.</li><li>If the passenger has or hasn’t done the payment it will reflect in payment status and the respective payment due date and amount will be stored in Payment.</li><li>Flight_Cost can be determined on the basis of Seat_Details and Calendar from which a particular seat belongs to a travel class and the date when the seat is booked respectively.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9kjGstLnk7X9RYCC" /></figure><p><strong>Final ERD Design:</strong></p><p>This intial ER Diagram can be improved by removing redundancies and refining the entities</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O38UxlOJYjKDQa8REmA69A.png" /></figure><p>· Airport entity has AirportCity and AirportCountry which provides the airport specifications.</p><p>· Flight_Type attribute has been added to Flight_Details</p><p>· Payment entity has been removed from the ER diagram and its attributes have been listed under Payment_Status.</p><p>· The cardinality between Payment_Status and Reservation has been made optional one to mandatory many. Therefore, Reservation_ID becomes foreign key inside Payment_Status.</p><p>· Service_Offering which is an associative entity has 3 new attributes called Offered_YN , From_Date and To_Date. From_Date and To_Date that would give us the period when certain flight services are provided. Offered_YN would tell us if that service is been offered to a particular travel class.</p><p>· From the previous ER Diagram, we have removed Service_Type from Flight_Service and Class_Type from Travel_Class as it’s not required to enhance it.</p><p><strong>Database Implementation:</strong></p><p>With the Data Model ready,let us implement it using SQL.I have chosen Microsoft SQL server for the implementation</p><p>Here is a configured list of every object used in this project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*rQZz54ukJLOUWiC7JirMIw.png" /></figure><p>let’s look at the DDL script first.</p><p><strong>DDL:</strong></p><pre>go<br>Create Database FBS;<br>go<br>USE FBS<br>--Create Airport table<br>CREATE TABLE Airport<br>(<br>Airport_ID int not null,<br>AirportName varchar(100),<br>AirportCity varchar(100),<br>AirportCountry varchar(100),<br>CONSTRAINT Airport_PK PRIMARY KEY (Airport_ID)<br>);<br><br><br>-- create Passenger table <br>-- new changes<br>create table Passenger <br>(<br>Passenger_ID INT not null,<br>P_FirstName VARCHAR(100),<br>P_LastName VARCHAR(100),<br>P_Email VARCHAR(100) CONSTRAINT email_check CHECK (P_Email LIKE &#39;[a-z,0-9,_,-]%@[a-z]%.[a-z][a-z]%&#39;),<br>P_PhoneNumber BIGINT not null UNIQUE CONSTRAINT Ph_length_check CHECK  (len([P_PhoneNumber])=10),<br>P_Address VARCHAR(100),<br>P_City VARCHAR(100),<br>P_State VARCHAR(100),<br>P_Zipcode VARCHAR(100) CONSTRAINT zip_chk CHECK (LEN(P_Zipcode)=5),<br>P_Country VARCHAR(100)<br>CONSTRAINT Passenger_ID_PK PRIMARY KEY (Passenger_ID)<br>);<br><br>-- create Travel class<br>CREATE TABLE Travel_Class<br>(<br> Travel_Class_ID INT NOT NULL,<br> Travel_Class_Name VARCHAR(100) CONSTRAINT name_list_chk CHECK (Travel_Class_Name IN(&#39;First Class&#39;,&#39;Business Class&#39;,&#39;Premium Economy&#39;,&#39;Economy Class&#39;,&#39;Basic Economy&#39;)),<br> Travel_Class_Capacity BIGINT,<br> CONSTRAINT Travel_Class_PK PRIMARY KEY (Travel_Class_ID)<br>);<br><br>-- create Calendar table<br>CREATE TABLE Calendar<br>(<br> Day_Date Date NOT NULL,<br> Business_Day_YN CHAR(1) Constraint check_character_Business_Day_YN Check(Business_Day_YN In (&#39;Y&#39;,&#39;N&#39;)),<br> CONSTRAINT Calendar_PK PRIMARY KEY (Day_Date)<br>);<br><br>-- create Flight Service table<br>create table Flight_Service<br>(<br>Service_ID INT not null,<br>[Service_Name] VARCHAR(100) CONSTRAINT Service_chk CHECK([Service_Name] in (&#39;Food&#39;,&#39;French Wine&#39;,&#39;Wifi&#39;,&#39;Entertainment&#39;,&#39;Lounge&#39;)),<br>CONSTRAINT Flight_Service_PK PRIMARY KEY (Service_ID)<br>);<br><br>--ALTER TABLE Flight_Service ALTER [Service_Name] CONSTRAINT Service_chk CHECK([Service_Name] in (&#39;Food&#39;,&#39;French Wine&#39;,&#39;Wifi&#39;,&#39;Entertainment&#39;,&#39;Lounge&#39;));<br>-- create Flight Details table<br>CREATE TABLE Flight_Details (<br> Flight_ID INT NOT NULL,<br> Source_Airport_ID INT NOT NULL,<br> Destination_Airport_ID INT NOT NULL ,<br> Departure_Date_Time DateTime,-- CONSTRAINT date_check CHECK (Departure_Date_Time&lt; Arrival_Date_Time),<br> Arrival_Date_time DateTime,<br> Airplane_Type VARCHAR(100) CONSTRAINT airplane_check CHECK(Airplane_Type IN (&#39;Airbus A380&#39;,&#39;Boeing 747&#39;)),<br> CONSTRAINT Flight_Details_PK PRIMARY KEY (Flight_ID),<br> CONSTRAINT Flight_Details_Source_FK1 FOREIGN KEY (Source_Airport_ID) REFERENCES Airport(Airport_ID),<br> CONSTRAINT Flight_Details_Destination_FK2 FOREIGN KEY (Destination_Airport_ID) REFERENCES Airport(Airport_ID),<br> CONSTRAINT Date_check_FD CHECK (Departure_Date_Time&lt; Arrival_Date_Time),<br> CONSTRAINT airport_chk CHECK (Source_Airport_ID != Destination_Airport_ID)<br> );<br><br> -- create Seat Details table<br> CREATE TABLE Seat_Details<br>(<br> Seat_ID VARCHAR(100) NOT NULL,<br> Travel_Class_ID INT NOT NULL, <br> Flight_ID INT NOT NULL,<br> CONSTRAINT Seat_Details_PK PRIMARY KEY (Seat_ID),<br> CONSTRAINT Seat_Details_TravelClassID_FK1 FOREIGN KEY (Travel_Class_ID) REFERENCES Travel_Class(Travel_Class_ID),<br> CONSTRAINT Seat_Details_FlightID_FK2 FOREIGN KEY (Flight_ID) REFERENCES Flight_Details(Flight_ID)<br>)<br><br>-- create Reservation table <br> CREATE TABLE Reservation (<br> Reservation_ID INT NOT NULL,<br> Passenger_ID INT NOT NULL,<br> Seat_ID VARCHAR(100) NOT NULL,<br> --Default Value recorded below<br> Date_Of_Reservation Date DEFAULT(getDate()),<br> CONSTRAINT Reservation_PK PRIMARY KEY (Reservation_ID),<br> CONSTRAINT Reservation_Passenger_ID_FK1 FOREIGN KEY (Passenger_ID) REFERENCES Passenger(Passenger_ID),<br> CONSTRAINT Reservation_Seat_ID_FK2 FOREIGN KEY (Seat_ID) REFERENCES Seat_Details(Seat_ID)<br> );<br><br> -- create Payment Status table<br> --add table again<br>  CREATE TABLE Payment_Status (<br> Payment_ID INT NOT NULL IDENTITY(1,1),<br> Payment_Status_YN CHAR(1) Constraint check_character_Payment_Status_YN Check(Payment_Status_YN In (&#39;Y&#39;,&#39;N&#39;)),<br> Payment_Due_Date Date,<br> Payment_Amount INT,<br> Reservation_ID INT NOT NULL,<br> CONSTRAINT Payment_Status_PK PRIMARY KEY (Payment_ID),<br> CONSTRAINT Payment_Reservation_ID_FK FOREIGN KEY (Reservation_ID) REFERENCES Reservation(Reservation_ID)<br> );<br><br>--create Flight cost table <br>CREATE TABLE Flight_Cost<br>(   <br> Seat_ID VARCHAR(100) NOT NULL,<br> Valid_From_Date Date NOT NULL,<br> Valid_To_Date Date NOT NULL,<br> Cost BIGINT,<br> CONSTRAINT Flight_Cost_PK PRIMARY KEY (Seat_ID,Valid_From_Date),<br> CONSTRAINT Flight_Cost_Seat_ID_FK1 FOREIGN KEY (Seat_ID) REFERENCES Seat_Details(Seat_ID),<br> CONSTRAINT Flight_Cost_Valid_From_Date_FK2 FOREIGN KEY (Valid_From_Date) REFERENCES Calendar(Day_Date),<br> CONSTRAINT Flight_Cost_Valid_To_Date_FK3 FOREIGN KEY (Valid_To_Date) REFERENCES Calendar(Day_Date)<br>);<br><br>--create Service offering table <br>CREATE TABLE Service_Offering<br>(<br> Travel_Class_ID INT NOT NULL,<br> Service_ID  int NOT NULL,<br> Offered_YN CHAR(1) Constraint check_character_Offered_YN Check(Offered_YN In (&#39;Y&#39;,&#39;N&#39;)),<br> From_Month VARCHAR(20),<br> To_Month VARCHAR(20),<br> CONSTRAINT Service_Offering_TCI_FK1 FOREIGN KEY (Travel_Class_ID) REFERENCES Travel_Class(Travel_Class_ID),<br> CONSTRAINT Service_Offering_SID_FK2 FOREIGN KEY (Service_ID) REFERENCES Flight_Service(Service_ID),<br> CONSTRAINT Service_Offering_PK PRIMARY KEY (Travel_Class_ID,Service_ID)<br>);<br><br>--Creating indexes for all primary keys<br>CREATE UNIQUE INDEX SO_Index ON Service_Offering(Travel_Class_ID,Service_ID);<br>CREATE UNIQUE INDEX FC_Index ON Flight_Cost(Seat_ID,Valid_From_Date);<br>CREATE UNIQUE INDEX PS_Index ON Payment_Status(Payment_ID);<br>CREATE UNIQUE INDEX R_Index ON Reservation(Reservation_ID);<br>CREATE UNIQUE INDEX SD_Index ON Seat_Details(Seat_ID);<br>CREATE UNIQUE INDEX FD_Index ON Flight_Details(Flight_ID);<br>CREATE UNIQUE INDEX FS_Index ON Flight_Service(Service_ID);<br>CREATE UNIQUE INDEX Cal_Index ON Calendar(Day_Date);<br>CREATE UNIQUE INDEX T_Index ON Travel_Class(Travel_Class_ID);<br>CREATE UNIQUE INDEX Pass_Index ON Passenger(Passenger_ID);<br>CREATE UNIQUE INDEX Air_Index ON Airport(Airport_ID);<br><br>--Creating non clustered index<br>USE P4_FBS<br>CREATE NONCLUSTERED INDEX email_indx ON Passenger(P_Email);<br>CREATE NONCLUSTERED INDEX dep_indx ON Flight_Details(Departure_Date_Time);<br>CREATE NONCLUSTERED INDEX city_indx ON Airport(AirportCity);<br>go<br>sp_helpindex Airport<br>go<br>sp_helpindex Passenger<br>go<br>sp_helpindex Flight_Details</pre><p>Let us setup triggers and necessary functions to auto insert data and calculate flight costs based on the dates</p><pre>go<br>USE FBS<br>go<br>CREATE TRIGGER Payment_Insert ON Reservation<br>--MAKE IDENTITY FOR PAYMENT ID<br><br>FOR INSERT<br>AS<br>BEGIN<br>   DECLARE @ResId int<br>   DECLARE @Res_date DATE<br>   DECLARE @due_date DATE<br>   DECLARE @Cost bigint<br>   DEClARE @seat VARCHAR(20) <br>   SELECT @ResId = Reservation_ID FROM inserted<br>   SELECT @Res_date = Date_Of_Reservation FROM inserted<br>   SELECT @seat= Reservation.Seat_ID FROM Reservation WHERE Reservation_ID=@ResId<br>   SELECT @Cost=Cost FROM Flight_Cost WHERE Flight_Cost.Seat_ID=@seat AND Flight_Cost.Valid_From_Date=@Res_date<br>   SELECT @due_date=DATEADD(DAY,1,@Res_date)<br>   INSERT INTO Payment_Status(Payment_Status_YN,Payment_Due_Date,Payment_Amount,Reservation_ID)<br>   VALUES (&#39;N&#39;,@due_date,@Cost,@ResId);<br><br><br>END<br><br><br><br>--UDF<br>--OUR UDF WILL TAKE BUSINESS DAY,Departure Date,Travel cLASS id,Deafult price<br>go<br>CREATE FUNCTION Cal_Cost(@Start_Date date,@dep_date date,@travel_id int,@business char(1))<br>RETURNS BIGINT<br>AS<br>BEGIN<br>    DECLARE @Diff int<br> Select @Diff=DateDIFF(day,@Start_Date,@dep_date)<br> RETURN 100+((Select<br> CASE<br>   WHEN @business=&#39;Y&#39; THEN  10<br>   ELSE 0<br> END As Business_Inc)+<br> (Select<br> CASE <br>   WHEN @travel_id=1 THEN 50<br>   WHEN @travel_id=2 THEN 40<br>   WHEN @travel_id=3 THEN 30<br>   WHEN @travel_id=4 THEN 20<br>   ELSE 10<br>    END As Class_Inc)+<br> (Select<br> CASE <br>   WHEN @Diff&gt;20 AND @Diff&lt;=30 THEN 0<br>   WHEN @Diff&gt;10 AND @Diff&lt;=20 THEN 20<br>   ELSE 50<br> END AS Interval_Inc<br> ))<br>  <br>   <br>END<br><br><br>--function body end<br><br>GO<br>CREATE TRIGGER Set_Cost ON Seat_Details<br>FOR INSERT<br>AS<br>BEGIN<br>   Declare @Default_price BIGINT<br>   Set @Default_price=100<br>   DECLARE @Start_date date<br>   DECLARE @Final_Cost BIGINT<br>   Declare @business char(1)<br>   --Declare @default_price bigint<br>   Declare @flight_cost bigint<br>   DECLARE @dep_date date<br>   --set @default_price=100<br>   Declare @S_id varchar(20)<br>   SELECT @S_id = Seat_ID FROM inserted<br>   Declare @travel_id int<br>   SELECT @travel_id= Travel_Class_ID FROM inserted<br>   DECLARE @flight_id int<br>   SELECT @flight_id=Flight_ID FROM inserted<br>   <br>   Select @business=Business_Day_YN FROM Calendar<br>       WHERE Day_Date=<br>    (SELECT CONVERT(Date,Departure_Date_Time) <br>     FROM Flight_Details WHERE Flight_ID=@flight_id<br>  )-- from Flight_Details where Flight_ID=@flight_id<br> SELECT @dep_date=CONVERT(Date,Departure_Date_Time) <br>     FROM Flight_Details WHERE Flight_ID=@flight_id<br><br> SELECT @Start_date=DATEADD(MONTH,-1,@dep_date)<br> DECLARE @last_date date<br> SELECT @last_date=DateADD(day,-1,@dep_date)<br>-- WHILE LOOP<br>   <br>   WHILE @Start_date &lt; @last_date<br>   BEGIN<br><br>      SELECT @Final_Cost=[dbo].[Cal_Cost](@Start_date,@dep_date,@travel_id,@business)<br>   DECLARE @valid_to date<br>   SET @valid_to= DATEADD(Day,1,@Start_date)<br>   INSERT INTO Flight_Cost(Seat_ID,Valid_From_Date,Cost,Valid_To_Date)<br>      VALUES(@S_id,@Start_date,@Final_Cost,@valid_to)<br>      SET @Start_date = DATEADD(Day,1,@Start_date)<br>   END<br><br>END</pre><p>Implementing Stored Procedures to improve functionality of our database and make it easier for developers to access the database and make any changes</p><pre>USE FBS<br>--procedure 1<br>Go<br>CREATE PROCEDURE Flight_Availability<br>@Departure_Date  date,<br>@Arrival_Date date,<br>@available char(1) OUTPUT<br><br>AS<br>IF EXISTS(SELECT Flight_ID FROM Flight_Details<br> WHERE CONVERT(Date,Departure_Date_time) = @Departure_Date<br>    AND CONVERT(Date,Arrival_Date_time) = @Arrival_Date <br>)<br><br>BEGIN<br>    SET @available=&#39;Y&#39;    <br>    SELECT * FROM Flight_Details<br> WHERE CONVERT(Date,Departure_Date_time) = @Departure_Date<br>    AND CONVERT(Date,Arrival_Date_time) = @Arrival_Date<br> <br>END<br>ELSE<br>BEGIN<br><br>Print &#39;Flight Detail Doesnt exist&#39;<br>end<br><br><br><br><br><br><br><br><br>--PROCEDURE 2<br><br>Go<br>CREATE PROCEDURE [dbo].[UpdateFlightDetails] <br>@flag bit output,-- return 0 for fail,1 for success<br>@FlightID INT,<br>@DeptDateTime DATETIME,<br>@ArivalDateTime DATETIME,<br>@AirplaneType VARCHAR(100)<br>AS<br>BEGIN<br> Update Flight_Details set Departure_Date_Time = @DeptDateTime,<br>                           Arrival_Date_time = @ArivalDateTime,<br>                           Airplane_Type = @AirplaneType<br> Where Flight_ID = @FlightID <br> set @flag=1;<br> <br>END<br><br><br><br> --Procedure 3<br><br> Go<br> CREATE PROCEDURE [dbo].[PassengerCRUD] <br>                    @Action VARCHAR(10), <br>                    @Passenger_ID int = NULL, <br>                    @FName VARCHAR(100) = NULL, <br>                    @LName VARCHAR(100) = NULL, <br>                    @Email VARCHAR(100) = NULL,<br>                    @PNumber BIGINT = NULL, <br>                    @Address VARCHAR(100) = NULL,<br>                    @city VARCHAR(100) = NULL,  <br>                    @State VARCHAR(100) = NULL, <br>                    @Zipcode VARCHAR(100) = NULL, <br>                    @Country VARCHAR(100) = NULL<br><br>AS<br>BEGIN<br>      SET NOCOUNT ON;<br> <br>      --SELECT<br>      IF @Action = &#39;SELECT&#39;<br>      BEGIN<br>            SELECT Passenger_ID, P_FirstName,P_LastName,P_Email,P_PhoneNumber,P_Address,P_City,<br>                              P_State,P_Zipcode,P_Country<br>            FROM Passenger<br>      END<br> <br>      --INSERT<br>      IF @Action = &#39;INSERT&#39;<br>      BEGIN<br> INSERT INTO dbo.Passenger([Passenger_ID], [P_FirstName],[P_LastName],[P_Email],[P_PhoneNumber],[P_Address],[P_City],<br>                              [P_State],[P_Zipcode],[P_Country] )<br><br> VALUES (@Passenger_ID, @FName, @LName, @Email, @PNumber, @Address, @city, @State, @Zipcode, @Country)<br>      END<br> <br>      --UPDATE<br>      IF @Action = &#39;UPDATE&#39;<br>      BEGIN<br>            UPDATE Passenger<br>            SET Passenger_ID = @Passenger_ID, P_FirstName = @FName, P_LastName = @LName, P_Email= @Email, P_PhoneNumber = @PNumber, <br>                P_Address = @Address, P_City = @city, P_State = @State, P_Zipcode =  @Zipcode, P_Country = @Country<br>            WHERE Passenger_ID = @Passenger_ID<br>      END<br> <br>      --DELETE<br>      IF @Action = &#39;DELETE&#39;<br>      BEGIN<br>            DELETE FROM Passenger<br>            WHERE Passenger_ID = @Passenger_ID<br>      END<br>END<br><br><br><br>--Procedure 4<br>GO<br>CREATE PROCEDURE UpdatePayment <br>       @paymentID INT,@paid_date date OUTPUT<br>AS<br>  BEGIN<br>  Update Payment_Status<br>  SET Payment_Status_YN=&#39;Y&#39; WHERE Payment_ID=@paymentID<br>  SELECT @paid_date=GETDATE()<br>   <br>END<br><br> <br><br></pre><p>Finally insert valid data using DML to manipulate and get insights</p><p><strong>Execution:</strong></p><p>The right way to set this up is by running DDL,Trigger Script,Stored Procedures and finally your DML script.</p><p><strong>Visualization:</strong></p><p>Finally, with my inserted data I have used Tableau to visualize and infer certain insights</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*FXt9CcZSaqzuCIrb5BkuAA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f0e900ac9df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HackerRank SQL]]></title>
            <link>https://medium.com/@abhishek.manjunath.1999/hackerrank-sql-8221969c4e80?source=rss-2bce226f8fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8221969c4e80</guid>
            <category><![CDATA[hackerrank]]></category>
            <dc:creator><![CDATA[Abhishek Manjunath ]]></dc:creator>
            <pubDate>Wed, 18 Jan 2023 00:28:40 GMT</pubDate>
            <atom:updated>2023-01-18T00:28:40.846Z</atom:updated>
            <content:encoded><![CDATA[<h3>Contest Leaderboard</h3><blockquote><em>Problem:</em></blockquote><p>You did such a great job helping Julia with her last coding contest challenge that she wants you to work on this one, too!</p><p>The total score of a hacker is the sum of their maximum scores for all of the challenges. Write a query to print the hacker_id, name, and total score of the hackers ordered by the descending score. If more than one hacker achieved the same total score, then sort the result by ascending hacker_id. Exclude all hackers with a total score of 0 from your result.</p><p><strong>Input Format</strong></p><p>The following tables contain contest data:</p><ul><li>Hackers: The hacker_id is the id of the hacker, and name is the name of the hacker.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/0*UfiC7zxyB7AuiCz1.png" /></figure><ul><li>Submissions: The submission_id is the id of the submission, hacker_id is the id of the hacker who made the submission, challenge_id is the id of the challenge for which the submission belongs to, and score is the score of the submission.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/0*DUOa62vQXD3vrGQ1.png" /></figure><p><strong>Sample Input</strong></p><p>Hackers Table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/0*svIaBg3I5w809tIt.png" /></figure><p>Submissions Table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*nW7CFMceiPTMPGEI.png" /></figure><p><strong>Sample Output</strong></p><pre>4071 Rose 191<br>74842 Lisa 174<br>84072 Bonnie 100<br>4806 Angela 89<br>26071 Frank 85<br>80305 Kimberly 67<br>49438 Patrick 43</pre><p>To-Do:</p><p>Write a query to print the hacker_id, name, and total score of the hackers ordered by the descending score. If more than one hacker achieved the same total score, then sort the result by ascending hacker_id. Exclude all hackers with a total score of 0 from your result.</p><p>Solution:</p><pre>with cte as(<br>select distinct h.hacker_id,h.name,s.challenge_id,MAX(s.score) over (Partition by h.hacker_id,s.challenge_id) as max_score from hackers h inner join submissions s on h.hacker_id=s.hacker_id<br>)<br>select distinct hacker_id,name,SUM(max_score) from cte group by hacker_id,name having sum(max_score)&gt;0 order by sum(max_score) desc,hacker_id asc </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8221969c4e80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ollivander’s Inventory]]></title>
            <link>https://medium.com/@abhishek.manjunath.1999/ollivanders-inventory-955f5d9c61a?source=rss-2bce226f8fcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/955f5d9c61a</guid>
            <dc:creator><![CDATA[Abhishek Manjunath ]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 22:43:13 GMT</pubDate>
            <atom:updated>2023-01-11T22:43:13.833Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Problem:</em></blockquote><p>Harry Potter and his friends are at Ollivander’s with Ron, finally replacing Charlie’s old broken wand.</p><p>Hermione decides the best way to choose is by determining the minimum number of gold galleons needed to buy each non-evil wand of high power and age. Write a query to print the id, age, coins_needed, and power of the wands that Ron’s interested in, sorted in order of descending power. If more than one wand has same power, sort the result in order of descending age.</p><p><strong>Input Format</strong></p><p>The following tables contain data on the wands in Ollivander’s inventory:</p><ul><li>Wands: The id is the id of the wand, code is the code of the wand, coins_needed is the total number of gold galleons needed to buy the wand, and power denotes the quality of the wand (the higher the power, the better the wand is).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*Pts2YLVGfxsrbrVB.png" /></figure><ul><li>Wands_Property: The code is the code of the wand, age is the age of the wand, and is_evil denotes whether the wand is good for the dark arts. If the value of is_evil is 0, it means that the wand is not evil. The mapping between code and age is one-one, meaning that if there are two pairs, and , then and .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/0*xk55--pewmjhHEY4.png" /></figure><p><strong>Sample Input</strong></p><p>Wands Table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/0*M_TjYO0L_NSYekMs.png" /></figure><p>Wands_Property Table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/0*Fk8lkzO9XN3xSNoZ.png" /></figure><p><strong>Sample Output</strong></p><pre>9 45 1647 10<br>12 17 9897 10<br>1 20 3688 8<br>15 40 6018 7<br>19 20 7651 6<br>11 40 7587 5<br>10 20 504 5<br>18 40 3312 3<br>20 17 5689 3<br>5 45 6020 2<br>14 40 5408 1</pre><p><strong>Logic: </strong>Be aware of the question: ”by determining the minimum number of gold galleons needed to buy each non-evil wand of high power and age”. Hence, we have to create two copies of the Wands and Wands_Property tables to filter the minimum number of coins_needed.</p><p><strong>Solution:</strong></p><p>With cte as(<br>select w.id as id, p.age as age, Min(w.coins_needed) over (partition by p.code,w.power order by power desc) as coins,w.coins_needed,w.power as power from Wands as w join Wands_Property as p <br>on w.code = p.code where p.is_evil=0<br>)<br>Select id,age,coins_needed,power from cte where coins_needed=coins order by power desc,age desc</p><p>This is the same method just with the use of window function and cte to demonstrate some advanced sql concepts</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=955f5d9c61a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>