<?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 Nishant Gaurav on Medium]]></title>
        <description><![CDATA[Stories by Nishant Gaurav on Medium]]></description>
        <link>https://medium.com/@im_nishant?source=rss-cebe471cee83------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bFgDp_OnJ00MCZTH7d4Bmg.jpeg</url>
            <title>Stories by Nishant Gaurav on Medium</title>
            <link>https://medium.com/@im_nishant?source=rss-cebe471cee83------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:54:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@im_nishant/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[Model Context Protocol (MCP) Part 2: How MCP Works, Explained with a Hospital]]></title>
            <link>https://medium.com/@im_nishant/model-context-protocol-mcp-part-2-how-mcp-works-explained-with-a-hospital-64b76221cc32?source=rss-cebe471cee83------2</link>
            <guid isPermaLink="false">https://medium.com/p/64b76221cc32</guid>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[mcps]]></category>
            <dc:creator><![CDATA[Nishant Gaurav]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 13:31:01 GMT</pubDate>
            <atom:updated>2026-12-01T13:31:01.846Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 1 covered why MCP exists, what the name means, and what it gives you. This part shows how it works: what a “tool” is, the three components of the architecture, the step-by-step flow of a request, why MCP became stateless, and who builds the servers.</p><p>The running example is still <strong>CampusBuddy</strong>, the AI assistant for college students. To make the moving parts easy to picture, this part uses a <strong>hospital</strong> as the everyday comparison. Each topic ends with a “Remember for the test” box, and the article finishes with common confusions, a quick reference table, and practice questions with answers.</p><h3>Part A: What a Tool Is in MCP</h3><p>In MCP, the word <strong>tool</strong> has a specific meaning. A tool is an <strong>executable function</strong> that your LLM or AI application can invoke.</p><p>Take a <strong>GitHub MCP server</strong>. It can expose functions such as:</p><ul><li>Create a repository</li><li>Delete a repository</li><li>Read an issue</li><li>Write an issue</li></ul><p>Two properties define these tools:</p><ul><li>They accept <strong>JSON input</strong> and return <strong>JSON output</strong>.</li><li>They are <strong>invocable functions</strong>: the LLM or application uses them to execute specific tasks.</li></ul><h3>Why Tools Are Useful: An Abstraction Layer</h3><p>Tools give the LLM an <strong>abstraction layer</strong>. When the LLM needs to do something with an external system, it does <strong>not</strong> need to know the exact API endpoint. It only needs to know that these functions exist and that it can invoke them.</p><p>Think of a hospital’s list of available tests: blood test, X-ray, ECG. A doctor orders “X-ray, left wrist.” The doctor does not need to know which buttons to press on the X-ray machine. The test is a ready-made function that takes clear inputs (which patient, which body part) and returns a clear output (the report).</p><p><strong>Remember for the test (Part A)</strong></p><ul><li>A tool is an executable function the LLM or application can invoke.</li><li>Tools take JSON input and return JSON output.</li><li>Example: a GitHub MCP server can expose create repository, delete repository, read issue, and write issue.</li><li>Tools are an abstraction layer. The LLM does not need to know the API endpoint.</li></ul><h3>Part B: The Three Core Components</h3><p>MCP architecture has three components: the <strong>host</strong>, the <strong>MCP client</strong>, and the <strong>MCP server</strong>.</p><h3>The Hospital Map</h3><p>Here is how the pieces line up before looking at each one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hiwu7G6BxJ2ug_oj5a8yQw.png" /></figure><h3>1. Host</h3><p>The host is an <strong>LLM-powered application</strong>. It is the AI application that contains the AI features and uses an LLM, and it is the application the <strong>end user actually interacts with</strong>.</p><p>In CampusBuddy, the <strong>backend of the app</strong>, which handles the overall application logic and performs the operations, is the host. A host can be written in <strong>any language or framework</strong>, for example, <strong>Node.js</strong> or <strong>Django</strong>. Tools such as <strong>Claude Code</strong> and <strong>Codex</strong> can also act as hosts in the MCP architecture.</p><h3>2. MCP Client</h3><p>In most MCP architectures, the MCP client <strong>lives inside the host application</strong>. Its job is to <strong>send requests to the MCP server</strong> and to <strong>coordinate and orchestrate</strong> the work between the LLM and the MCP server. Like the runner, it carries requests in a standard format and brings the results back.</p><p>Technically, an MCP client is a component that <strong>maintains a connection with an MCP server</strong>. That lets it retrieve relevant context from the server and hand it to the host application or LLM for use.</p><h3>3. MCP Server</h3><p>The MCP server is best thought of as a <strong>translator</strong>. Suppose the LLM needs a tool such as MySQL. You install or configure an <strong>appropriate MCP server for MySQL</strong>. When a student asks “What classes do I have tomorrow?”, the LLM decides it needs the timetable database. The request travels to the MCP server, whose job is to <strong>execute the required command and fetch the data from the external tool</strong>, just as the lab technician runs the test on the machine.</p><p>The server returns that data to the MCP client. The client passes it back to the LLM through the host. The LLM then turns the raw result into a <strong>human-friendly response</strong> the student can easily read, the way a doctor explains a lab report in plain words.</p><p>Technically, an MCP server is a <strong>program whose job is to serve context and data to the host application</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1UTl0xoyouZR6XS0dxOWng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ag8MbgO4UW4jXKdQrZ7cbw.png" /></figure><p><strong>Remember for the test (Part B)</strong></p><ul><li>Three components: Host, MCP client, MCP server.</li><li>Host: the LLM-powered application the end user interacts with. Written in any language or framework. Claude Code and Codex can act as hosts.</li><li>MCP client: usually lives inside the host, sends requests to the server, maintains the connection, retrieves context, and orchestrates between the LLM and the server.</li><li>MCP server: a translator that executes commands on the external tool and serves context and data to the host.</li></ul><h3>Part C: The Complete Flow of a CampusBuddy Request</h3><p>Now put all the pieces together. A student uses CampusBuddy, and everything is built with MCP.</p><h3>Step 1: Tool Discovery</h3><p>This is like the runner collecting the <strong>test catalogue</strong> when the hospital opens for the day. When CampusBuddy <strong>starts</strong>, the <strong>MCP client asks the MCP server</strong>: “What tools are available?” The server responds with the <strong>list of tools</strong> and, importantly, the <strong>input schema for each tool</strong>, meaning what information each tool needs. The host stores this list. As a result, the LLM knows every available tool and what it can do, <strong>without anything being hardcoded</strong>.</p><h3>Step 2: User Query</h3><p>The student asks: <strong>“What classes do I have tomorrow?”</strong> The host forwards the query to the LLM.</p><h3>Step 3: LLM Decision</h3><p>The LLM, like the doctor, reads the question and decides which tool is needed: the timetable lookup. A crucial point: <strong>the LLM does not execute anything itself</strong>. It only <strong>decides the intent</strong>, meaning what needs to be done. The doctor writes the test order, but does not operate the machine.</p><h3>Step 4: Host Execution</h3><p>The <strong>host application</strong> takes the LLM’s decision and identifies the tool to invoke. The host <strong>instructs the MCP client</strong>; the client <strong>sends the request to the MCP server</strong>, and the server <strong>executes it</strong> against the timetable database and returns the response to the host. The host then gives the response to the LLM. In the hospital, this is the runner carrying the order to the lab technician and bringing the report back.</p><h3>Step 5: The LLM Generates a Response</h3><p>The LLM processes the tool’s result and writes a <strong>human-friendly answer</strong>: “Tomorrow you have Data Structures at 9, then Networks at 11.” This is displayed to the student.</p><h3>Step 6: Follow-up Queries</h3><p>The student may ask something else, for example, <strong>“Pay my exam fee.”</strong> The LLM already knows the available tools, so it can directly decide to use <strong>Razorpay</strong>. The <strong>same flow repeats</strong>: the host executes through the client and server, the result returns, and the LLM replies. A tool like <strong>Slack</strong> can be used the same way for “Let my class group know I’ll be late.”</p><pre>Tool discovery -&gt; User query -&gt; LLM decision -&gt; Host execution -&gt; LLM response -&gt; Follow ups<br>(client asks      (host sends     (intent only,   (host tells       (human friendly    (same flow<br> server for        to LLM)         no execution)   client, client    answer shown)      repeats)<br> tools + schemas)                                  calls server)</pre><h3>A Note on Who Does What</h3><p>An earlier simplified description says the LLM “sends the request” to the MCP client. The workflow clarifies the true division of labor:</p><ul><li>The <strong>LLM decides</strong> (intent).</li><li>The <strong>host executes</strong>, using the <strong>MCP client</strong> to talk to the <strong>MCP server</strong>.</li><li>The <strong>MCP server</strong> talks to the external tool.</li></ul><p>For test questions, remember that <strong>the LLM never runs the tool directly</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bw2rvgLu1e4mKqWJbEMH2Q.png" /></figure><p><strong>Remember for the test (Part C)</strong></p><ul><li>Six steps: tool discovery, user query, LLM decision, host execution, LLM response, follow-up queries.</li><li>Discovery happens at startup. The client asks the server for tools, and the server returns the tool list plus each tool’s input schema. The host stores it. Nothing is hardcoded.</li><li>The LLM only decides the intent. It does not execute anything.</li><li>The host executes: it instructs the MCP client, the client calls the MCP server, and the server runs the tool and returns the response.</li><li>Follow-up queries repeat the same workflow with other tools such as Razorpay and Slack.</li></ul><h3>Part D: Stateful Versus Stateless MCP</h3><p>When MCP was first introduced, it was a <strong>stateful protocol</strong>. That made it different from <strong>HTTP, which is stateless</strong>.</p><p>According to the video, MCP later became <strong>stateless in July 2026</strong>. Stateless means the MCP server can <strong>treat every incoming request independently</strong> instead of treating each one as part of the same session.</p><h3>The Hospital Version</h3><ul><li><strong>Stateful</strong> is like needing <strong>one particular lab technician</strong> because only that person remembers your earlier visit and what was said. If that technician is busy, you wait, and the hospital must keep sending you back to the same person. This is called <strong>session pinning</strong>.</li><li><strong>Stateless</strong> is like a request form that carries <strong>everything needed</strong> (patient ID, which test). Any technician on duty can pick it up and complete it. Patients can be sent to whoever is free, in turn. This is <strong>round-robin</strong> distribution.</li></ul><h3>Why Stateless Is Better</h3><ul><li><strong>Easier scaling.</strong> It is simpler to scale AI applications that use MCP, especially <strong>horizontally</strong> (adding more server instances).</li><li><strong>Round-robin load balancing without session pinning.</strong> Because any server can handle any request, a load balancer can spread requests evenly, with no need to stick one client to one server.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQXjDy7CJW6_POQMx9Mn3A.png" /></figure><blockquote><strong><em>Beyond the transcript.</em></strong><em> I checked the July 2026 claim against current sources. It is accurate: the MCP specification version </em><strong><em>2026–07–28</em></strong><em> made the protocol core stateless, removing the initialization handshake and the session header so that any request can land on any server instance. Removing protocol level sessions does not force your application to be stateless. If a server needs to carry state across calls, it can create an explicit handle and have the model pass it back. The exam level takeaway from the transcript is unchanged: stateless means independent requests, easier horizontal scaling, and round robin load balancing without session pinning.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gSlAG-oyAVHMmE6rJ8u1Fg.png" /></figure><p><strong>Remember for the test (Part D)</strong></p><ul><li>MCP started as a stateful protocol, unlike stateless HTTP.</li><li>MCP became stateless in July 2026 (specification version 2026–07–28).</li><li>Stateless: each request is treated independently.</li><li>Benefits: easier horizontal scaling and round-robin load balancing without session pinning.</li></ul><h3>Part E: Who Builds the MCP Server</h3><p>As the developer, you build the <strong>host</strong>, and the <strong>MCP client</strong> sits inside it. So who builds the <strong>MCP server</strong>? There are <strong>three types</strong>, built by different parties.</p><h3>1. Enterprise MCP Servers</h3><p><strong>Official servers built by the organizations themselves.</strong> For example, <strong>GitHub</strong> has built its own MCP servers. In the hospital picture, this is the <strong>machine maker’s own trained engineer</strong> running the machine: nobody knows it better. GitHub knows how its APIs work and what it wants to expose, and the responsibility for <strong>keeping the server updated</strong> belongs to GitHub too, so you get the most relevant, up-to-date information. For production systems, <strong>try an official enterprise server first</strong> if one exists.</p><h3>2. Open-Source MCP Servers</h3><p><strong>Community-driven servers.</strong> A popular example is the MCP server built by <strong>Anthropic</strong>. They are a <strong>good starting point</strong> but may have <strong>limited features</strong>. If no official enterprise server exists, an open-source one is a good option.</p><h3>3. Custom MCP Servers</h3><p><strong>Servers you build yourself</strong>, like a hospital’s own in-house lab. Advantages:</p><ul><li><strong>Easier to secure</strong> to your requirements.</li><li><strong>Easier to manage</strong> to your business needs.</li><li>You can implement your <strong>own custom business logic</strong>.</li><li>You can <strong>expose only the capabilities your organization needs</strong>.</li></ul><p>Custom servers suit organizations and enterprises that need customized solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yaFVMNnZhgfmhV-ocD3aJw.png" /></figure><h3>Individual Servers Versus Aggregators</h3><p>You can use <strong>one MCP server per tool</strong>, or an <strong>MCP server aggregator</strong>: a <strong>single MCP server that connects to multiple tools</strong>. Popular aggregators include <strong>Pipedream</strong>, <strong>Make</strong>, and <strong>Zapier</strong>, which let you connect to <strong>thousands of tools</strong>.</p><p>The hospital version: instead of visiting a separate lab for every test, you go to <strong>one diagnostic centre</strong> that offers many tests at a single counter. You can use the same idea when building your own: instead of one server per custom tool, build <strong>one aggregator</strong> that connects to several of your custom tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGgl0VMpyUe378JyndUutw.png" /></figure><p><strong>Remember for the test (Part E)</strong></p><ul><li>Three server types: enterprise (official, built by the organization, such as GitHub), open source (community, such as Anthropic’s server), custom (built by you).</li><li>For production, try an official enterprise server first.</li><li>Open source servers are a good starting point but may have limited features.</li><li>Custom servers are easier to secure and manage, allow custom business logic, and let you expose only what is needed.</li><li>An aggregator is a single MCP server connecting to multiple tools. Examples: Pipedream, Make, Zapier.</li></ul><h3>Common Confusions to Avoid</h3><ul><li><strong>Host versus MCP client.</strong> The host is the application. The client usually lives inside it and manages the connection to the server.</li><li><strong>MCP client versus MCP server.</strong> The client sends requests. The server executes them on the external tool.</li><li><strong>Who executes the tool?</strong> Not the LLM. The LLM decides; the host executes through the client and server.</li><li><strong>Tool versus tool definition.</strong> A tool is an executable function. Tool definitions are part of the context passed to the application.</li><li><strong>Discovery timing.</strong> It happens at startup, before any user query.</li><li><strong>Stateful versus stateless.</strong> Stateless means each request is independent. It does not mean your application can never keep state.</li><li><strong>Enterprise versus open source.</strong> Enterprise is built by the tool’s own organization. Open source is community-driven.</li><li><strong>Individual server versus aggregator.</strong> One tool per server, versus one server for many tools.</li></ul><h3>Quick Reference</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jtMgRvT6Ox33jljzxhwhA.png" /></figure><h3>Practice Questions</h3><p><strong>1. What is a tool in MCP?</strong> An executable function that the LLM or AI application can invoke.</p><p><strong>2. What format do tools use for input and output?</strong> JSON.</p><p><strong>3. Give examples of tools a GitHub MCP server can expose.</strong> Create a repository, delete a repository, read an issue, and write an issue.</p><p><strong>4. Why are tools called an abstraction layer?</strong> The LLM does not need to know the exact API endpoint, only that the functions exist and can be invoked.</p><p><strong>5. Name the three components of MCP architecture.</strong> Host, MCP client, and MCP server.</p><p><strong>6. What is the host?</strong> The LLM-powered application the end user interacts with, such as the CampusBuddy backend.</p><p><strong>7. Can Claude Code or Codex act as a host?</strong> Yes.</p><p><strong>8. Where does the MCP client usually live?</strong> Inside the host application.</p><p><strong>9. What is the MCP client’s job?</strong> To send requests to the MCP server, maintain the connection, retrieve context, and coordinate between the LLM and the server.</p><p><strong>10. What is the MCP server’s job?</strong> To execute the required command on the external tool and serve data and context back to the host.</p><p><strong>11. Which component acts like a translator?</strong> The MCP server.</p><p><strong>12. What happens at tool discovery?</strong> The MCP client asks the MCP server for the available tools, and the server returns the list along with each tool’s input schema.</p><p><strong>13. When does tool discovery happen?</strong> When the application starts.</p><p><strong>14. Does the LLM execute tools itself?</strong> No. It only decides the intent. The host application executes.</p><p><strong>15. Describe the execution path of a tool call.</strong> The host instructs the MCP client; the client sends the request to the MCP server; the server executes it and returns the response to the host, and the host gives it to the LLM.</p><p><strong>16. What does the LLM do after receiving the tool result?</strong> It generates a human-friendly answer for the user.</p><p><strong>17. How is a follow-up such as paying a fee handled?</strong> The LLM already knows the tools, so it decides to use Razorpay, and the same flow repeats.</p><p><strong>18. Was MCP originally stateful or stateless?</strong> Stateful. It later became stateless in July 2026.</p><p><strong>19. What does stateless mean for an MCP server?</strong> Each incoming request can be treated independently, not as part of one session.</p><p><strong>20. Name two benefits of stateless MCP.</strong> Easier horizontal scaling and round-robin load balancing without session pinning.</p><p><strong>21. Name the three types of MCP servers.</strong> Enterprise, open source, and custom.</p><p><strong>22. Why are enterprise MCP servers usually the best option?</strong> They are official, built, and kept up to date by the organization that owns the tool.</p><p><strong>23. What is a limitation of open source MCP servers?</strong> They may have limited features.</p><p><strong>24. Name two advantages of custom MCP servers.</strong> Easier to secure and manage, and they allow custom business logic and exposing only needed capabilities.</p><p><strong>25. What is an MCP server aggregator, and name examples?</strong> A single MCP server that connects to multiple tools. Examples: Pipedream, Make, and Zapier.</p><h3>Where This Series Leaves You</h3><p>Across the two parts, you now have the whole picture. MCP exists to solve the N × M integration problem by giving AI models one standard way to use tools, the way UPI gives payment apps one standard way to reach banks. It brings context into the application, and it brings four advantages: simpler integrations, lower maintenance, dynamic tool discovery, and better security. Architecturally, a <strong>host</strong> holds the LLM and an <strong>MCP client;</strong> the client talks to an <strong>MCP server</strong>, and the server runs <strong>tools</strong> against external systems, just as a hospital’s doctor decides, its runner carries the order, and its lab technician operates the machine. A request moves through discovery, the LLM’s decision, the host’s execution, and the LLM’s final answer. Since July 2026, the protocol is stateless, which makes it easier to scale, and the servers you connect to can be enterprise, open source, or custom, individually or through an aggregator.</p><p>If you can explain the N × M problem, draw the host, client, and server, and walk through the six flow steps without notes, you are well prepared for interviews on this topic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64b76221cc32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Context Protocol (MCP) Part 1: Why It Exists and What It Really Is]]></title>
            <link>https://medium.com/@im_nishant/model-context-protocol-mcp-part-1-why-it-exists-and-what-it-really-is-9523c0b1f6b4?source=rss-cebe471cee83------2</link>
            <guid isPermaLink="false">https://medium.com/p/9523c0b1f6b4</guid>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <dc:creator><![CDATA[Nishant Gaurav]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 13:31:02 GMT</pubDate>
            <atom:updated>2026-11-24T13:31:02.323Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have used Claude Code, Cursor, or Codex, you have already used MCP, because these tools rely on it behind the scenes. If you plan to build any AI application, MCP is worth knowing, since it is used in many production systems today.</p><p>This is a two-part series. <strong>Part 1</strong> (this article) explains the problem MCP solves, what the idea is, what the name means, and why it is worth using. <strong>Part 2</strong> covers the architecture, how a request flows through it, stateful versus stateless MCP, and who builds MCP servers.</p><p>Two things run through both parts so that everything stays concrete:</p><ul><li><strong>A running example:</strong> <em>CampusBuddy</em>, an AI assistant app that helps college students.</li><li><strong>An everyday comparison:</strong> <strong>UPI</strong>, the payment system most of us use daily. In Part 2, a hospital is used to explain the moving parts.</li></ul><p>Each topic ends with a “Remember for the test” box, and the article finishes with common confusions and practice questions with answers.</p><h3>Part A: The Problem MCP Solves</h3><p>MCP was introduced by Anthropic in 2024. To see what problem it solves, imagine you are on a small team building <strong>CampusBuddy</strong>, an AI assistant for students in your college.</p><p>Every AI application has two major parts:</p><ul><li>The <strong>development part</strong>: your own application code.</li><li>An <strong>LLM</strong> that thinks could be GPT, Gemini, Claude, or another model.</li></ul><h3>What the Assistant Has to Do</h3><p>A student opens CampusBuddy and asks: <strong>“What classes do I have tomorrow?”</strong></p><p>You send the question to the LLM. The LLM is good at language and reasoning, but it does not know your college’s timetable. That information sits in a <strong>database</strong> such as MySQL or PostgreSQL. So the LLM needs a <strong>tool</strong> to look it up.</p><p>Next, the student says: <strong>“Pay my exam fee.”</strong> Now the LLM needs a <strong>payment gateway</strong> such as Razorpay or Stripe.</p><p>Then: <strong>“Let my class group know I’ll be late.”</strong> Now it needs <strong>Slack</strong> (or a similar messaging tool). Behind the scenes, the app might also store documents on <strong>AWS</strong>.</p><p>The pattern is simple. To help real users with real tasks, an LLM needs access to <strong>many tools</strong>: databases, payment gateways, messaging apps, cloud services, and more.</p><h3>Life Without MCP</h3><p>Without MCP, you write <strong>custom integration logic</strong> to connect your LLM to every tool. For the timetable database, for example, you would:</p><ol><li>Write code that sends requests to whatever API endpoint the database provides.</li><li>Write code that processes the response and hands it to the LLM.</li><li>Update all of that whenever the database API changes: change the parser, change the integration logic, and <strong>redeploy</strong> the application.</li></ol><p>Now count the work:</p><ul><li><strong>Five tools</strong> means <strong>five custom integrations</strong>.</li><li>If your app uses <strong>three different LLMs</strong>, each of the five tools may need an integration per LLM, so you may need <strong>15 integrations</strong>.</li></ul><p>This is a classic software problem called the <strong>N × M integration problem</strong>: N tools multiplied by M models. It is hard to build, hard to maintain, and fragile. If you replace GPT with DeepSeek tomorrow, or replace MySQL with PostgreSQL, you may have to rewrite integrations all over again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zDQWJXl5UyoQ2ECC-Mz00g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J1sXzRtNofuEwaDF7LAO4A.png" /></figure><p><strong>Remember for the test (Part A)</strong></p><ul><li>An AI app has a development part and an LLM. The LLM needs tools (databases, payment gateways, Slack, AWS) to solve real tasks.</li><li>Without MCP, every tool needs its own custom integration logic, which must be updated and redeployed whenever an API changes.</li><li>5 tools need 5 integrations. 5 tools across 3 LLMs may need 15. This is the N × M integration problem.</li><li>Switching an LLM or a tool can force a rewrite.</li></ul><h3>Part B: What MCP Is, Explained Through UPI</h3><p><strong>MCP is a middleman</strong> that sits between your AI application, your LLM, and the tools you need. You write your logic <strong>once</strong>, and it stays the same even when the LLM or the tools change later.</p><p>The easiest way to feel why that matters is to think about <strong>UPI</strong>.</p><h3>The UPI Comparison</h3><p>Imagine, as a thought experiment, that UPI did not exist. Every payment app would need a <strong>separate arrangement with every bank</strong>. With 4 apps and 5 banks, that is 20 separate connections, and every time a bank changed something, every app would need to adapt.</p><p>UPI fixes this with <strong>one common standard</strong>. Each payment app connects to the standard <strong>once</strong>. Each bank connects to the standard <strong>once</strong>. After that, any app can pay any bank, and no one needs a special deal with anyone else.</p><p>MCP plays exactly this role for AI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2YzN6mnVqUAnm_2j7iC7Q.png" /></figure><p>Counted this way, CampusBuddy would need roughly <strong>3 + 5 = 8 connections</strong> to the standard instead of <strong>15 custom integrations</strong>. And if you swap one LLM for another, you may only need to change <strong>a single line of code</strong>, because the standard connection stays the same.</p><h3>Traditional APIs Versus MCP</h3><ul><li><strong>Traditional APIs</strong> were designed mainly for <strong>human developers</strong>. They let developers and applications interact with different systems.</li><li><strong>MCP</strong> is designed specifically to <strong>standardize how AI models and AI-based applications interact with external tools</strong>.</li></ul><p>In short, MCP lets AI models connect to external tools, databases, and applications through a <strong>single protocol</strong> rather than custom integrations for each one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dO3WiDOxukOS2gXqsqjMXA.png" /></figure><p><strong>Remember for the test (Part B)</strong></p><ul><li>MCP is a middleman between the AI application, the LLM, and the tools. Write the logic once.</li><li>Comparison: UPI. Apps and banks each connect to one standard instead of to each other.</li><li>Switching an LLM may take a single line of code.</li><li>Traditional APIs were designed for human developers. MCP standardizes how AI models interact with external tools.</li></ul><h3>Part C: What the Name Means</h3><p>MCP stands for <strong>Model Context Protocol</strong>. Each word carries meaning, and the most important one is <strong>Protocol</strong>.</p><h3>1. Protocol</h3><p>A protocol is a <strong>set of rules that define how communication and interaction take place</strong>. You already know one: <strong>HTTP</strong>, the Hypertext Transfer Protocol, defines the rules for how a browser talks to a web server. UPI is another kind of standard: it defines how apps and banks talk. In the same spirit, <strong>MCP defines the rules for how an AI application talks to tools, databases, and other applications</strong>.</p><p>This leads to a <strong>misconception worth clearing up</strong>. MCP does <strong>not</strong> create brand new capabilities that were impossible through API calls. UPI does not let you spend money you do not have. It only standardizes how the payment request travels. MCP is the same: suppose you connect to GitHub, and GitHub’s APIs do not allow external parties to edit or delete certain repositories. Using MCP will not magically make that possible.</p><blockquote><strong><em>MCP is a standardization of the interaction process, not a source of new capabilities.</em></strong><em> It defines a common set of rules for how your application or LLM interacts with external tools.</em></blockquote><h3>2. Context</h3><p>The job of MCP is to <strong>bring relevant context into the AI application</strong>. That context can include:</p><ul><li><strong>Tool definitions</strong></li><li><strong>Database schemas</strong></li><li><strong>Enterprise data</strong></li><li>Other relevant information the application needs</li></ul><h3>3. Model</h3><p>MCP is built for <strong>AI models</strong>. It is <strong>not</strong> designed for traditional web applications or mobile applications. The reason is that the way an AI model uses tools differs from the way human written code or a human developed application uses them. Because LLMs interact with external tools differently, the process needed standardizing, and that is why MCP exists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ord6zyHwtcS45ZqogFgfvQ.png" /></figure><p><strong>Remember for the test (Part C)</strong></p><ul><li>A protocol is a set of rules for communication. HTTP is the familiar example.</li><li>MCP does not introduce new capabilities. If an API does not allow an operation, MCP will not make it possible.</li><li>Context includes tool definitions, database schemas, and enterprise data.</li><li>MCP is for AI models, not traditional web or mobile apps, because LLMs interact with tools differently.</li></ul><h3>Part D: The Advantages of MCP</h3><h3>1. It Solves the N × M Integration Problem</h3><p>You no longer write numerous custom integrations or extra glue code. You need only the MCP middleman, which simplifies a large number of integrations.</p><h3>2. Reduced Maintenance Cost</h3><p>Because integrations are standardized, you do <strong>not</strong> repeatedly modify custom integration logic whenever an LLM or an external tool changes. The whole application becomes easier to maintain.</p><h3>3. Dynamic Tool Discovery</h3><p>Think of a restaurant <strong>menu board</strong>. You do not memorize the dishes in advance. You read what is available today, and when the menu changes, you simply read the new one.</p><p>MCP works the same way. The interaction <strong>starts with a discovery step</strong>: the <strong>MCP client asks the MCP server, “What tools are available?”</strong> The server answers with the available tools and their capabilities, for example MySQL, Razorpay, and Slack. That information reaches the LLM through the host application, so the LLM knows which tools exist and can <strong>decide which ones to use</strong> for a task.</p><p>This also handles change gracefully. If the API behind a tool changes tomorrow, the <strong>MCP server</strong> absorbs the change and exposes the updated capabilities through the standard interface. Your application discovers what is available <strong>dynamically, at runtime</strong>, with no hardcoding.</p><h3>4. Better Security and Access Control</h3><p>Go back to UPI. When you pay a shopkeeper, the shopkeeper never sees your banking password or your UPI PIN. The shop only says “charge this amount,” and the secure payment system does the rest. (The comparison is not exact, but the idea carries over.)</p><p>Now suppose you skip MCP and connect your LLM directly to tools over HTTP APIs. With five tools you may need <strong>five separate API keys</strong>, and because the LLM is directly connected, you might end up <strong>exposing all of those keys to the LLM</strong>. That is not reliable for a production system, especially in an organization.</p><p>With MCP:</p><ul><li>All <strong>API keys, secrets, and tokens are stored inside the MCP server</strong>.</li><li>The responsibility for making the <strong>actual API calls</strong> belongs to the <strong>MCP server</strong>, not the LLM.</li><li>The LLM simply <strong>invokes the available functions or tools</strong>.</li></ul><p>So the LLM gets every capability it needs <strong>without ever seeing the sensitive credentials</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGAjsO__aelUqsX2VrC8gw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojkLvzBNLrRZDFM_IOd5Cg.png" /></figure><p><strong>Remember for the test (Part D)</strong></p><ul><li>Four advantages: solves N × M, reduced maintenance cost, dynamic tool discovery, better security and access control.</li><li>Discovery: the MCP client asks the MCP server which tools are available. The server returns tools and capabilities. The LLM learns about them through the host application.</li><li>If a tool’s API changes, the MCP server absorbs it and exposes updated capabilities. Applications discover capabilities dynamically at runtime.</li><li>Security: keys, secrets, and tokens stay in the MCP server. The MCP server makes the API calls. The LLM only invokes functions or tools.</li></ul><h3>Common Confusions to Avoid</h3><ul><li><strong>MCP versus new capabilities.</strong> MCP standardizes how tools are accessed. It does not unlock operations an API forbids, just as UPI does not create money.</li><li><strong>Protocol versus API.</strong> An API is a specific interface to a system. A protocol is the set of rules for communication. MCP is a protocol for how AI models use tools.</li><li><strong>MCP versus traditional APIs.</strong> Traditional APIs were designed for human developers and applications. MCP is designed for AI models.</li><li><strong>N × M versus N + M.</strong> Without MCP, every tool needs an integration for every model. With MCP, each side connects to the standard once.</li><li><strong>Who holds the credentials.</strong> With MCP the MCP server holds them. The LLM does not.</li><li><strong>Who makes the API calls.</strong> The MCP server, not the LLM.</li><li><strong>Discovery versus hardcoding.</strong> The client asks the server for available tools at runtime instead of hardcoding them.</li></ul><h3>Practice Questions</h3><p><strong>1. Who introduced MCP, and when?</strong> Anthropic, in 2024.</p><p><strong>2. What problem does MCP solve?</strong> The N × M integration problem: custom integrations for every combination of LLM and tool.</p><p><strong>3. If an app uses 5 tools and 3 LLMs, how many custom integrations might it need without MCP?</strong> 15.</p><p><strong>4. Why can switching from GPT to DeepSeek be painful without MCP?</strong> Custom integrations may need to be rewritten.</p><p><strong>5. What does MCP stand for?</strong> Model Context Protocol.</p><p><strong>6. What is a protocol?</strong> A set of rules that define how communication and interaction take place. HTTP is an example.</p><p><strong>7. Does MCP add new capabilities that an API did not allow?</strong> No. It standardizes the interaction. If GitHub does not allow an operation through its APIs, MCP will not make it possible.</p><p><strong>8. What kinds of information does “context” include?</strong> Tool definitions, database schemas, enterprise data, and other relevant information.</p><p><strong>9. Is MCP designed for traditional web and mobile applications?</strong> No. It is designed for AI models, since LLMs interact with tools differently.</p><p><strong>10. In the UPI comparison, what do the banks and the payment apps correspond to?</strong> Banks correspond to tools. Payment apps correspond to AI applications and LLMs. UPI corresponds to MCP.</p><p><strong>11. Traditional APIs were designed mainly for whom?</strong> Human developers and applications.</p><p><strong>12. What may you need to change to use a different LLM with MCP?</strong> Possibly just a single line of code.</p><p><strong>13. Name the four advantages of MCP.</strong> Solves the N × M integration problem, reduced maintenance cost, dynamic tool discovery, and better security and access control.</p><p><strong>14. How does dynamic discovery start?</strong> The MCP client asks the MCP server what tools are available, and the server returns the tools and their capabilities.</p><p><strong>15. What happens when a tool’s API changes under MCP?</strong> The MCP server absorbs the change and exposes the updated capabilities through the standard interface, so the app discovers them at runtime.</p><p><strong>16. Where are API keys, secrets, and tokens stored with MCP?</strong> Inside the MCP server.</p><p><strong>17. Who makes the actual API calls under MCP?</strong> The MCP server. The LLM simply invokes the available functions or tools.</p><p><strong>18. Why is connecting an LLM directly to five tools risky?</strong> You may need five API keys and might expose them to the LLM, which is unreliable for production systems.</p><h3>Where This Leaves You</h3><p>MCP exists because AI applications need many tools, and wiring each tool to each model by hand does not scale. Like UPI, it works by giving everyone one standard to connect to, so you write your logic once, keep credentials in one safe place, and let your application discover tools at runtime. It does not make impossible things possible. It makes the possible things consistent.</p><p><strong>Part 2</strong> opens up the machinery using a hospital as the comparison: what a “tool” is in MCP, the three core components (host, client, and server), the full step by step flow of a CampusBuddy request, stateful versus stateless MCP, and who builds MCP servers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9523c0b1f6b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Longest Common Subsequence: A New Pattern, the Same Thinking]]></title>
            <link>https://medium.com/@im_nishant/longest-common-subsequence-a-new-pattern-the-same-thinking-f06cad5ce652?source=rss-cebe471cee83------2</link>
            <guid isPermaLink="false">https://medium.com/p/f06cad5ce652</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[knapsack-problem]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Nishant Gaurav]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 15:31:01 GMT</pubDate>
            <atom:updated>2026-11-01T15:31:01.673Z</atom:updated>
            <content:encoded><![CDATA[<p>This chapter covers the first two steps: recursion and memoization. Tabulation comes next.</p><h3>What Is a Subsequence?</h3><p>Before anything else, this needs to be clear.</p><p>A subsequence is formed by deleting zero or more characters from a string without changing the order of the remaining characters. The selected characters don’t have to be adjacent.</p><pre>String: A B C D E<br><br>Valid subsequences:<br>  ACE    (positions 1, 3, 5)<br>  ABD    (positions 1, 2, 4)<br>  BDE    (positions 2, 4, 5)<br>  ABCDE  (the whole string)<br>  A      (just the first character)<br>  &quot;&quot;     (empty - valid)<br>Not a valid subsequence:<br>  CA     (order is reversed)</pre><p>The key point: gaps are allowed, but order is not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozWVLfGJ4zDnU2LJGjbKIQ.png" /></figure><h3>What Is the Longest Common Subsequence?</h3><p>Given two strings, find the longest subsequence that appears in both.</p><pre>X = ABCDGH<br>Y = ABEDFW</pre><p>Some common subsequences: A, AB, ABD, ABDH</p><p>The longest one is ABDH with length 4. That&#39;s the LCS.</p><p>The characters must appear in the same relative order in both strings, but they don’t need to be adjacent in either.</p><h3>Why This Is a DP Problem</h3><p>Look at the last characters of both strings.</p><pre>X = A B C D G H   → last character: H<br>Y = A B E D F W   → last character: W</pre><p>Two cases arise.</p><p><strong>Case 1: Last characters match.</strong></p><p>If X[m-1] == Y[n-1], that character is part of the LCS. Include it and reduce both strings by one.</p><pre>LCS(X, Y, m, n) = 1 + LCS(X, Y, m-1, n-1)</pre><p><strong>Case 2: Last characters don’t match.</strong></p><p>If X[m-1] != Y[n-1], you don&#39;t know which one to drop. So you try both and take the better result.</p><pre>LCS(X, Y, m, n) = max(<br>    LCS(X, Y, m-1, n),    # drop last char of X<br>    LCS(X, Y, m, n-1)     # drop last char of Y<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rIAZ9RhMfpMi22HfzlwkJQ.png" /></figure><p>These two cases completely define the recursive structure.</p><h3>Base Case</h3><p>The smallest valid input is when either string runs out of characters.</p><pre>X = &quot;&quot;         or        Y = &quot;&quot;</pre><p>An empty string has no characters to share. The LCS is zero.</p><pre>if m == 0 or n == 0:<br>    return 0</pre><p>Always design the base case first. Ask: what is the smallest input where the answer is obvious?</p><h3>The Recursive Solution</h3><p>The base case plus choice diagram gives you the full recursion directly.</p><pre>class Solution:<br><br>def lcs(self, X, Y, m, n):<br>        # Base case: one string is empty, no common subsequence<br>        if m == 0 or n == 0:<br>            return 0<br>        # Last characters match - include and shrink both<br>        if X[m - 1] == Y[n - 1]:<br>            return 1 + self.lcs(X, Y, m - 1, n - 1)<br>        # Last characters don&#39;t match - try dropping from either side<br>        else:<br>            return max(<br>                self.lcs(X, Y, m - 1, n),<br>                self.lcs(X, Y, m, n - 1)<br>            )<br>    def longestCommonSubsequence(self, X, Y):<br>        m = len(X)<br>        n = len(Y)<br>        return self.lcs(X, Y, m, n)</pre><p>The code is a direct translation of the choice diagram. Nothing is added beyond the base case and two cases.</p><h3>Why the Recursive Solution Gets Slow</h3><p>When characters don’t match, two recursive calls are made. Each of those makes two more. The tree grows exponentially.</p><p>Worse, the same state appears multiple times through different paths.</p><pre>LCS(m, n)<br>├── LCS(m-1, n)<br>│   ├── LCS(m-2, n)<br>│   └── LCS(m-1, n-1)  ← appears here<br>└── LCS(m, n-1)<br>    ├── LCS(m-1, n-1)  ← and here again<br>    └── LCS(m, n-2)</pre><p>LCS(m-1, n-1) is calculated twice from the top level alone. Deeper in the tree, the overlap gets worse. For long strings, this becomes too slow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abK0KryZi6iRzd5cIUIoig.png" /></figure><p>The fix is the same as it was in the Knapsack series: store the answer the first time, reuse it every time after.</p><h3>Memoization</h3><p>The state is defined by two values: m and n. So the cache is a 2D table of size (m+1) × (n+1).</p><p>The +1 on each dimension is because m and n range from 0 to their respective lengths. Zero is a valid state (it&#39;s the base case), so it needs a slot in the table.</p><h3>Why initialise with -1 and not 0</h3><p>0 is a valid LCS answer. For example:</p><pre>X = ABC<br>Y = XYZ</pre><p>These strings share no characters. LCS = 0. If the table is initialised to zero, you can’t tell whether a cell holds a computed answer of zero or an unvisited state. So we use -1 as the sentinel.</p><pre>-1 → not computed yet<br> 0 → computed, answer is 0<br>&gt;0 → computed, answer is this value</pre><p>This is the same reasoning as using None in Count of Subsets (Chapter 4), where False was a valid answer and couldn&#39;t serve as the placeholder.</p><p><strong>Common mistake:</strong> initialising with 0 and then checking if T[m][n] != 0. This skips recomputing incorrectly when the real answer is zero.</p><pre># WRONG<br>if T[m][n] != 0:<br>    return T[m][n]<br><br># CORRECT<br>if T[m][n] != -1:<br>    return T[m][n]</pre><h3>The Memoized Solution</h3><pre>class Solution:<br><br>def lcs(self, X, Y, m, n):<br>        # Base case<br>        if m == 0 or n == 0:<br>            return 0<br>        # Return stored answer if already computed<br>        if self.T[m][n] != -1:<br>            return self.T[m][n]<br>        # Match: include character, shrink both strings<br>        if X[m - 1] == Y[n - 1]:<br>            self.T[m][n] = 1 + self.lcs(X, Y, m - 1, n - 1)<br>        # No match: try both options, take the better one<br>        else:<br>            self.T[m][n] = max(<br>                self.lcs(X, Y, m - 1, n),<br>                self.lcs(X, Y, m, n - 1)<br>            )<br>        return self.T[m][n]<br>    def longestCommonSubsequence(self, X, Y):<br>        m = len(X)<br>        n = len(Y)<br>        # -1 means not yet computed<br>        self.T = [[-1] * (n + 1) for _ in range(m + 1)]<br>        return self.lcs(X, Y, m, n)</pre><p>The recursive logic is unchanged. Two lines added: the cache check at the top, the store before returning. That’s memoization.</p><p>[IMAGE SUGGESTION] Placement: The Memoized Solution Purpose: Show the memoization flow — check cache first, compute if missing, store and return Type: Flow diagram AI prompt: Vertical flow diagram titled “Memoization Flow.” Step 1: “Call LCS(m, n).” Step 2 diamond: “Is T[m][n] != -1?” Yes branch → “Return T[m][n] immediately.” No branch continues. Step 3: “Apply base case or choice diagram.” Step 4: “Store result in T[m][n].” Step 5: “Return T[m][n].” Each step in a rounded box. Yes branch in green (cache hit). No branch in blue (compute path). Flat minimal design, clean arrows, clear labels.</p><h3>The LCS Pattern to Remember</h3><pre>Base case:<br>  m == 0 or n == 0 → return 0<br><br>Choice:<br>  X[m-1] == Y[n-1] → 1 + LCS(m-1, n-1)<br>  X[m-1] != Y[n-1] → max(LCS(m-1, n), LCS(m, n-1))<br>Memoization:<br>  Table size: (m+1) × (n+1)<br>  Initialise with -1<br>  Check before computing, store after</pre><h3>What You Now Understand</h3><p>LCS is not Knapsack. The inputs are two strings, not an array and a capacity. The table is indexed by string lengths, not items and weight. The choice is match-or-no-match, not take-or-skip.</p><p>But the process is the same. Base case first. Choices second. Recursion from those two. Repeated states observed. Memoization added with two lines.</p><p>The next chapter converts this recursion into a bottom-up tabulation. Once you see how m-1 and n-1 in the recursion map to i-1 and j-1 in the table, the entire LCS family of problems becomes much easier to build.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f06cad5ce652" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GROUP BY In PostgreSQL]]></title>
            <link>https://medium.com/@im_nishant/group-by-in-postgresql-ad6cfaa56fc1?source=rss-cebe471cee83------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad6cfaa56fc1</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Nishant Gaurav]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 16:31:01 GMT</pubDate>
            <atom:updated>2026-10-22T16:31:01.683Z</atom:updated>
            <content:encoded><![CDATA[<p>For a while, GROUP BY was basically the ceiling of what I knew how to do with aggregation. Total per city, count per venue, that kind of thing. Then I ran into a task — rank venues within their own city by latitude, but keep every single venue row in the result, not collapse them into one row per city — and GROUP BY just couldn&#39;t do it. That&#39;s the gap window functions fill, and once it clicked, a bunch of queries that used to feel awkward got a lot simpler.</p><h3>What GROUP BY can’t do</h3><p>GROUP BY collapses rows. If you group venues by city and count them, you get one row per city — the individual venues are gone from the result, folded into that count. That&#39;s exactly what you want sometimes. It&#39;s exactly the problem other times, like when you want to know each venue&#39;s rank within its city, but still want every venue listed individually, not just a per-city summary.</p><h3>Window functions keep every row</h3><pre>SELECT<br>    name,<br>    city,<br>    RANK() OVER (PARTITION BY city ORDER BY latitude DESC) AS rank_in_city<br>FROM venues;</pre><p>This returns one row per venue — nothing gets collapsed. Each row also gets a computed value attached to it, rank_in_city, based on how that venue compares to others in the same city. PARTITION BY city is doing something similar to what GROUP BY does conceptually, splitting the data into per-city buckets, but instead of collapsing each bucket into a single summary row, the window function computes something within each bucket and attaches it back onto every original row.</p><p>That’s really the core difference worth holding onto: GROUP BY reduces row count, window functions don&#39;t.</p><h3>The ones that come up most</h3><p>ROW_NUMBER(), RANK(), and DENSE_RANK() all number rows within a partition, but they handle ties differently. ROW_NUMBER() gives every row a distinct number regardless of ties, arbitrarily breaking them. RANK() gives tied rows the same number, then skips ahead — two venues tied for rank 1 means the next one is rank 3, not 2. DENSE_RANK() also gives tied rows the same number, but doesn&#39;t skip — the next distinct value after a tie at 1 is 2, not 3.</p><p>LAG() and LEAD() compare a row to the row before or after it, within the same ordering:</p><pre>SELECT venue_id, closed_on,<br>       LAG(closed_on) OVER (PARTITION BY venue_id ORDER BY closed_on) AS previous_closure<br>FROM closures;</pre><p>This pulls, for each closure record, the date of that same venue’s previous closure, sitting right there in the same row. Useful for things like “days since last closure” style calculations, where you need to compare a row to the one before it without writing a self join to do it.</p><p>SUM() OVER (...) gives you running totals — the same idea as a regular SUM, but computed cumulatively per row instead of collapsed into a single number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XvJX_gQUtIw0_fwNnBDS2g.png" /></figure><h3>Where this actually gets used</h3><p>A common real request is “top N per category” — for this project, maybe “the two highest-latitude venues in each city.” GROUP BY genuinely can&#39;t answer this on its own, because it would need to keep multiple rows per city, which defeats the whole point of grouping. The window function version:</p><pre>SELECT name, city, latitude<br>FROM (<br>    SELECT name, city, latitude,<br>           ROW_NUMBER() OVER (PARTITION BY city ORDER BY latitude DESC) AS rn<br>    FROM venues<br>) ranked<br>WHERE rn &lt;= 2;</pre><p>The inner query attaches a row number to every venue, restarting at 1 for each new city, ordered by latitude descending. The outer query then just filters down to rn &lt;= 2. This pattern — window function inside, filter outside — is worth recognizing on sight, because &quot;top N per group&quot; comes up often enough that it&#39;s basically a template once you&#39;ve seen it once.</p><h3>Where this leaves you</h3><p>Window functions solve a specific gap that GROUP BY leaves open: computing something per group while still keeping every individual row in the result, rather than collapsing down to one row per group. If a query needs a ranking, a comparison to a neighboring row, or a running total, and you catch yourself reaching for GROUP BY and getting frustrated that it&#39;s throwing away rows you actually needed, that&#39;s usually the signal a window function is what you actually want.</p><p>Next up: JSONB in practice — querying and indexing semi-structured data, which comes up constantly once you’re syncing data from external sources.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad6cfaa56fc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Views vs Materialized Views In PostgreSQL]]></title>
            <link>https://medium.com/@im_nishant/views-vs-materialized-views-in-postgresql-a86188aba480?source=rss-cebe471cee83------2</link>
            <guid isPermaLink="false">https://medium.com/p/a86188aba480</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Nishant Gaurav]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 16:31:01 GMT</pubDate>
            <atom:updated>2026-10-21T16:31:01.657Z</atom:updated>
            <content:encoded><![CDATA[<p>This one’s short compared to some of the earlier topics in this series, but it’s also one of those things that’s easy to get backwards if you only skim the definitions once. A view and a materialized view sound like variations on the same idea, and syntactically they’re not far apart, but they behave in genuinely different ways once you actually use them.</p><h3>Where the confusion comes from</h3><p>Say you’ve got a dashboard summary showing total venues per city, and it’s built on a GROUP BY query that&#39;s a bit expensive — maybe it&#39;s joining against closures too, computing a few aggregates at once. Someone suggests &quot;just make it a view,&quot; and that&#39;s reasonable advice, except it doesn&#39;t actually solve the performance problem people usually mean when they say that. A regular view doesn&#39;t cache anything. It just saves you from retyping the query.</p><h3>The two, side by side</h3><pre>CREATE VIEW active_venues AS<br>SELECT * FROM venues WHERE is_closed = FALSE;<br><br>CREATE MATERIALIZED VIEW venue_stats AS<br>SELECT city, COUNT(*) AS total FROM venues GROUP BY city;<br>REFRESH MATERIALIZED VIEW venue_stats;</pre><p>A regular VIEW is really just a stored query, nothing more. Every time you SELECT * FROM active_venues, Postgres runs the underlying query against venues again, live, right then. It&#39;s always current, because it&#39;s not storing anything — it&#39;s just a name attached to a query definition that gets substituted in and executed fresh each time.</p><p>A MATERIALIZED VIEW actually stores the result physically, like a real table. Reading from venue_stats is fast, because it&#39;s just reading stored rows, not recomputing anything. The trade-off is that it goes stale the moment the underlying data changes, and it stays stale until you explicitly run REFRESH MATERIALIZED VIEW to recompute and re-store the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dmcT5uiba3Ung_PhPVoUgA.png" /></figure><h3>Picking one</h3><p>Use a regular VIEW when the underlying query is cheap enough that running it live isn&#39;t a real cost, and when the data behind it absolutely needs to be current every time someone reads it. active_venues above is a good fit — filtering on a boolean is trivial for Postgres, there&#39;s no real performance reason to cache it, and you&#39;d generally want to know immediately if a venue&#39;s status changed.</p><p>Use a MATERIALIZED VIEW when the query is genuinely expensive — heavy aggregation, several joins, something that takes real time to compute — and when the consumers of that data can tolerate it being slightly stale in exchange for speed. A dashboard&#39;s summary stats are the classic case: nobody&#39;s checking venue_stats expecting it to reflect a venue that closed thirty seconds ago, and recomputing that aggregation on every single page load for every user would be wasteful when refreshing it once every few minutes, or on some schedule, is perfectly acceptable.</p><h3>Where this leaves you</h3><p>The names sound similar, but the behavior isn’t — a VIEW is a saved query that always runs live, a MATERIALIZED VIEW is a saved result that needs an explicit REFRESH to stay current. Picking between them comes down to one question: does this need to be live every time, or is a periodically refreshed snapshot good enough for what it&#39;s being used for.</p><p>Next up: window functions — a step past GROUP BY that lets you compute things like running totals and per-group rankings without collapsing your rows down to one per group.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a86188aba480" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transactions, ACID, and MVCC In PostgreSQL]]></title>
            <link>https://medium.com/@im_nishant/transactions-acid-and-mvcc-in-postgresql-3f3791280ee8?source=rss-cebe471cee83------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f3791280ee8</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Nishant Gaurav]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 16:31:01 GMT</pubDate>
            <atom:updated>2026-10-20T16:31:01.680Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the chapter that finally connected a bunch of things I’d been treating as separate facts — why UPDATE doesn&#39;t it edit rows in place, why table files keep growing even after you delete data, why VACUUM exists at all. It turns out all of it comes back to one mechanism, MVCC, and once that clicked, a handful of previously mysterious Postgres behaviors stopped being mysterious.</p><h3>What transactions actually give you</h3><pre>BEGIN;<br>UPDATE venues SET is_closed = TRUE WHERE id = 5;<br>UPDATE closures SET closed_on = NOW() WHERE venue_id = 5;<br>COMMIT;   -- or ROLLBACK;</pre><p>Everything between BEGIN and COMMIT either all happens, or none of it does. If something goes wrong partway through — an error, a constraint violation, or you just decide to ROLLBACK yourself — neither update takes effect. This matters here specifically because marking a venue closed and logging when it closed are really two halves of one action. Without a transaction wrapping both, you could end up with a venue marked closed but no closure record, or a closure record for a venue that&#39;s still marked open, if something failed between the two statements.</p><h3>ACID, without the textbook phrasing</h3><ul><li><strong>Atomicity</strong> — the whole transaction is one unit. No partial, half-applied state where some of it went through and some didn’t.</li><li><strong>Consistency</strong> — the database moves from one valid state to another. Constraints never get violated in the committed result, even if intermediate steps inside the transaction technically would have violated them on their own.</li><li><strong>Isolation</strong> — concurrent transactions don’t see each other’s uncommitted changes. What “see” actually means here depends on the isolation level, which is worth its own section.</li><li><strong>Durability</strong> — once committed, it survives a crash. It’s written to disk, specifically to something called the write-ahead log (WAL), before Postgres considers the commit successful.</li></ul><p>These four letters get recited a lot without much explanation of what they’re actually protecting against. Atomicity is what stops the venue/closure scenario above from going half-done. Durability is what means a COMMIT isn&#39;t a lie — if the server crashes one second after it returns success, that data is still there when it comes back up.</p><h3>Isolation levels</h3><p>Level Prevents Postgres default? Read Uncommitted (Postgres treats this the same as Read Committed — it doesn’t actually implement dirty reads) no Read Committed dirty reads yes, this is the default Repeatable Read dirty + non-repeatable reads no Serializable all anomalies, including phantom reads no</p><p>Read Committed being the default means each individual statement inside a transaction sees whatever was committed at the moment that specific statement started — not the moment the whole transaction began. That distinction matters more than it sounds like it should: two statements in the same transaction, run a few seconds apart, could see different data if something else committed in between, because each statement takes its own fresh look at what’s currently committed.</p><p>Serializable is the strongest guarantee — it behaves as though transactions ran one at a time, in some order, with no interleaving at all. The trade-off is that Postgres has to detect conflicts between concurrent Serializable transactions and abort one of them if it can’t guarantee that “as if run one at a time” property, which means application code using Serializable transactions generally needs retry logic built in for when that happens.</p><p>For anything genuinely financial-grade, Serializable is the safer default despite that extra complexity. For most everyday application logic, Read Committed is fine, and it’s what you get unless you explicitly ask for something stronger.</p><h3>MVCC — the actual mechanism underneath all of this</h3><p>Here’s the part that reframed a bunch of things for me. Postgres doesn’t lock rows for reads the way you might picture from a simpler mental model of “one person edits, everyone else waits.” Instead, it keeps multiple <strong>versions</strong> of a row.</p><p>When you run an UPDATE, Postgres doesn&#39;t modify the existing row in place. It writes an entirely new row version with the updated values, and marks the old version as expired — not deleted yet, just no longer the current version. Readers who started their query before the update still see the old version, consistently, without being blocked by the write happening concurrently. Writers, likewise, aren&#39;t blocked by ongoing reads. This is why Postgres handles a mix of concurrent reads and writes well without needing to lock everything constantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HNMsCYmc3aNNHfzXm1TUig.png" /></figure><p>This also connects directly back to something from the CRUD article earlier in this series — every INSERT creates a new row version, and now the reason that phrasing matters is clearer: Postgres genuinely never edits a row&#39;s storage in place. It&#39;s always writing new versions and marking old ones as no longer current.</p><h3>Why VACUUM exists</h3><p>Those old, expired row versions don’t just disappear the moment they stop being current — they sit there, taking up space, until something cleans them up. That’s what VACUUM does.</p><pre>VACUUM ANALYZE venues;</pre><p>If you’ve ever deleted a bunch of rows from a table and noticed the file on disk didn’t shrink the way you’d expect, this is the explanation — the dead row versions are still physically there until VACUUM reclaims that space. AUTOVACUUM runs by default in the background specifically so you don&#39;t normally have to think about this, but it&#39;s worth knowing it exists and understanding why, rather than just trusting it silently.</p><p>This is a genuinely good question to know the answer to, mostly because a lot of people who’ve used Postgres casually have never actually encountered it — they’ve never had a table grow large enough, or gone deep enough into how updates work, to run into it. Knowing why VACUUM exists is less about the command itself and more a decent signal that you&#39;ve thought about what&#39;s actually happening underneath an UPDATE, not just what syntax makes one run.</p><h3>Putting it together with the venue/closure example</h3><p>Back to the transaction from the start of this article:</p><pre>BEGIN;<br>UPDATE venues SET is_closed = TRUE WHERE id = 5;<br>UPDATE closures SET closed_on = NOW() WHERE venue_id = 5;<br>COMMIT;</pre><p>Under the hood, both UPDATEs create new row versions rather than editing in place. Until COMMIT runs, another transaction reading venues at Read Committed isolation still sees the old, pre-update version of that row — the change genuinely isn&#39;t visible yet. Once COMMIT happens, the new versions become the current ones, and the old versions become eligible for cleanup, eventually, by VACUUM. If something failed between the two UPDATE statements and the transaction rolled back instead, both new row versions would just be discarded, and the original rows would remain the current version, as if none of this had happened at all.</p><h3>Where this leaves you</h3><p>MVCC is the reason Postgres handles concurrent reads and writes gracefully without heavy locking, and it’s also the reason a handful of things that might otherwise seem unrelated — why updates don’t happen in place, why deleted data doesn’t immediately shrink a table, why VACUUM exists — actually connect to one underlying idea. Transactions and isolation levels sit on top of this, controlling exactly what a given piece of code is allowed to see while other things are happening concurrently.</p><p>Next up: views and materialized views — the difference between a query that re-runs live every time versus one that’s actually stored and needs to be refreshed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f3791280ee8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Indexes in PostgreSQL]]></title>
            <link>https://medium.com/@im_nishant/indexes-in-postgresql-3049b26f8f1b?source=rss-cebe471cee83------2</link>
            <guid isPermaLink="false">https://medium.com/p/3049b26f8f1b</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Nishant Gaurav]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 16:31:01 GMT</pubDate>
            <atom:updated>2026-10-20T16:31:01.609Z</atom:updated>
            <content:encoded><![CDATA[<p>I added my first index thinking it was basically a free speedup — like flipping a switch. Nobody had told me indexes cost anything, so it didn’t occur to me they might not always be worth it. It took looking at a genuinely slow write path, and eventually tracing it back to a table with five indexes on columns nobody actually queried by, to understand that an index is a trade-off, not a strict upgrade.</p><h3>The problem indexes actually solve</h3><p>Without an index, finding rows that match a WHERE condition means Postgres reads every single row in the table and checks each one — a sequential scan. On a table with a few hundred rows, that&#39;s basically instant, not worth worrying about. On a table with millions of rows, it&#39;s the difference between a query that returns in milliseconds and one that takes seconds, every single time it runs.</p><p>That’s the entire motivation. An index gives Postgres a shortcut — a separate structure it can search instead of scanning the whole table — for columns you filter, join, or sort by often enough that the sequential scan actually becomes a problem.</p><h3>Creating one</h3><pre>CREATE INDEX idx_venues_city ON venues(city);<br>CREATE UNIQUE INDEX idx_venues_name ON venues(name);</pre><p>Nothing exotic in the syntax itself. The UNIQUE version does double duty — it speeds up lookups on name and enforces that no two rows can share the same value, functioning as a constraint as well as a performance tool.</p><p>The columns worth indexing are the ones that actually show up in your WHERE clauses, your join conditions, or your ORDER BY — not every column &quot;just in case it&#39;s useful someday.&quot; That instinct, indexing defensively, is exactly what leads to the situation I mentioned above.</p><h3>When an index doesn’t actually help</h3><p>This is the part that gets skipped in a lot of explanations, and it’s arguably more useful to know than when <em>to</em> index, since the “when to” case is fairly intuitive once you understand sequential scans.</p><p><strong>Small tables.</strong> A sequential scan on a few hundred rows is genuinely faster than using an index, once you account for the overhead of looking the index up and then jumping back to the table to fetch the actual row. The index doesn’t help; it’s just extra bookkeeping.</p><p><strong>Columns that are rarely queried.</strong> An index that never gets used in a WHERE or join condition is pure cost with no corresponding benefit — it still has to be maintained on every write, for nothing.</p><p><strong>Columns updated extremely often.</strong> Every INSERT or UPDATE that touches an indexed column also has to update the index itself, not just the table row. On a write-heavy table, having several indexes on frequently updated columns adds up to real overhead, and it&#39;s the kind of thing that&#39;s easy to not notice until write latency creeps up over time.</p><p><strong>Low-cardinality columns.</strong> Something like a boolean is_closed column only has two possible values. A plain B-tree index on it doesn&#39;t narrow things down much, since roughly half the table matches either value — the index isn&#39;t selective enough to be worth using over a sequential scan in most cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9maDzQt0rYM6XsYM-qoUyw.png" /></figure><h3>The index types worth being able to name</h3><p>Type Best for B-tree (default) equality and range queries — the default 90% of the time GIN JSONB, arrays, full-text search GiST geospatial data (what PostGIS relies on), also full-text BRIN huge tables with naturally sequential data, like timestamps in an append-only log Hash pure equality lookups only, rarely used over B-tree in practice</p><p>You’ll mostly use B-tree without ever thinking about it, since it’s the default CREATE INDEX gives you. The others matter once you&#39;re dealing with specific data shapes. For a geospatial project, this is worth knowing specifically: PostGIS relies on GiST indexes, which support things like &quot;nearest neighbor&quot; and bounding-box style queries efficiently. A plain B-tree fundamentally can&#39;t do that kind of spatial lookup — it&#39;s built for ordering along a single dimension, not for two-dimensional proximity.</p><h3>Actually checking if your query is using an index</h3><pre>EXPLAIN ANALYZE SELECT * FROM venues WHERE city = &#39;Bhopal&#39;;</pre><p>EXPLAIN on its own shows you the <em>planned</em> execution — what Postgres intends to do, without actually running the query. EXPLAIN ANALYZE actually executes it and shows real timing alongside the plan. The thing to look for in the output is whether it says Seq Scan or Index Scan. A sequential scan on a large, filtered table is usually a sign something&#39;s missing — either the index doesn&#39;t exist yet, or it exists but isn&#39;t being used for some reason, which is its own separate rabbit hole worth investigating if it happens.</p><p>This is genuinely one of the highest-value habits to build early. Before assuming a slow query is “just how Postgres is” or reaching for some other fix, checking EXPLAIN ANALYZE first tells you whether the problem is actually about indexing, or something else entirely — a bad join order, an unnecessary sort, or something else the plan reveals if you know what to look for.</p><h3>Why OFFSET gets slow, and what to use instead</h3><pre>SELECT * FROM venues ORDER BY id LIMIT 20 OFFSET 10000;</pre><p>This looks harmless — you’re only asking for 20 rows. But Postgres still has to scan through and discard the first 10,000 rows before it can return the 20 you actually wanted. As the offset grows, the query gets slower, even though the result set size never changes. On a table that only ever has a few pages, nobody notices. On a table with deep pagination — page 500 of search results, say — it becomes a real problem.</p><p>The alternative is keyset pagination:</p><pre>SELECT * FROM venues WHERE id &gt; 10000 ORDER BY id LIMIT 20;</pre><p>Instead of counting through rows to skip, this jumps directly to where the last page left off, using the last seen id as the starting point. With an index on id — which a primary key already has by default — this is fast regardless of how deep into the results you are, because it&#39;s not scanning and discarding anything.</p><h3>Deciding what to index on a real table</h3><p>Say the venues table from earlier in this series is now getting queried in a few different ways: filtering by city, checking is_closed, and occasionally sorting by created_at.</p><p>city is a solid candidate — it&#39;s a genuine filter condition, likely used often, and has enough distinct values to actually be selective. is_closed is the low-cardinality case from above — a boolean with two values, and indexing it alone probably doesn&#39;t help much on its own. created_at, if the table grows into millions of rows and queries often sort by recency, is a reasonable candidate too, potentially even a BRIN index specifically, since timestamps in a table like this tend to be naturally close to sequential as new rows get inserted.</p><p>The way I’d actually verify any of this, rather than guessing, is running the real queries through EXPLAIN ANALYZE before and after adding a candidate index, and comparing the plan and the timing directly instead of assuming.</p><h3>Where this leaves you</h3><p>An index isn’t a free performance upgrade — it’s a genuine trade, faster reads for slower writes and more storage, and it’s only worth making on columns that are actually queried often enough for the sequential scan to be a real cost. EXPLAIN ANALYZE is the tool that turns this from guesswork into something you can actually verify, and it&#39;s worth reaching for before adding or removing any index, not just when something&#39;s already obviously slow.</p><p>Next up: transactions, ACID, and MVCC — the part of Postgres that explains why concurrent reads and writes mostly don’t get in each other’s way, and why VACUUM exists at all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3049b26f8f1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GROUP BY, HAVING, and Subqueries In PostgreSQL]]></title>
            <link>https://medium.com/@im_nishant/group-by-having-and-subqueries-in-postgresql-09e2f0898af5?source=rss-cebe471cee83------2</link>
            <guid isPermaLink="false">https://medium.com/p/09e2f0898af5</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Nishant Gaurav]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 16:31:01 GMT</pubDate>
            <atom:updated>2026-10-18T16:31:01.747Z</atom:updated>
            <content:encoded><![CDATA[<p>There’s a point in almost every project where you stop just retrieving rows and start actually asking questions — how many venues per city, which cities have more than a handful, which venues are above average latitude. That’s the shift this article is about. The syntax for aggregation isn’t complicated on its own. What takes a bit longer to get comfortable with is the order things actually happen in, especially once WHERE and HAVING are both in the same query and doing different jobs.</p><h3>Where it gets confusing</h3><p>Say you want cities with more than three venues. The instinct, especially early on, is to write:</p><pre>SELECT city, COUNT(*) AS venue_count<br>FROM venues<br>WHERE COUNT(*) &gt; 3<br>GROUP BY city;</pre><p>This fails. Not silently, at least — Postgres will give you an error about aggregate functions not being allowed in WHERE. But the reason it fails is worth actually understanding rather than just memorizing &quot;use HAVING instead.&quot; WHERE filters individual rows, and it runs before any grouping happens. At the point WHERE is being evaluated, there&#39;s no such thing as &quot;the count for this city&quot; yet, because the rows haven&#39;t been grouped into cities at all — they&#39;re still just individual venue rows. You can&#39;t filter on something that doesn&#39;t exist yet.</p><h3>Aggregate functions and GROUP BY</h3><pre>SELECT COUNT(*) FROM venues;<br>SELECT AVG(latitude) FROM venues;<br>SELECT city, COUNT(*) AS venue_count<br>FROM venues<br>GROUP BY city;</pre><p>GROUP BY city collapses all the rows sharing the same city value into a single row per city, and the aggregate functions — COUNT, AVG, and similar — operate on each group rather than the whole table. Fairly intuitive once you&#39;ve written a few of these.</p><h3>HAVING, and why it exists at all</h3><pre>SELECT city, COUNT(*) AS venue_count<br>FROM venues<br>GROUP BY city<br>HAVING COUNT(*) &gt; 3;</pre><p>HAVING is what WHERE would be if it ran after grouping instead of before. It filters groups, not individual rows, and by the time it runs, the counts and averages actually exist as real values you can compare against. That&#39;s the whole reason it&#39;s a separate keyword rather than Postgres just letting you use aggregates inside WHERE — the two clauses run at genuinely different stages of query execution, filtering different things.</p><p>A decent way to remember which is which: WHERE happens before grouping, so it can&#39;t see aggregate results yet. HAVING happens after, so it can.</p><h3>Subqueries — a query inside a query</h3><pre>-- scalar subquery<br>SELECT name FROM venues<br>WHERE latitude &gt; (SELECT AVG(latitude) FROM venues);</pre><p>Here the inner query runs first, computes a single number — the average latitude across all venues — and the outer query uses that number as a comparison value. This is called a scalar subquery because it returns exactly one value.</p><pre>-- subquery in FROM (a derived table)<br>SELECT city, avg_lat FROM (<br>    SELECT city, AVG(latitude) AS avg_lat<br>    FROM venues GROUP BY city<br>) AS city_stats<br>WHERE avg_lat &gt; 23;</pre><p>This one’s a bit different — the subquery in the FROM clause produces an entire table-like result (city-level averages), which the outer query then filters and selects from, as though it were a real table. It needs an alias (city_stats here) because Postgres requires every table-like thing in a FROM clause to have a name, even a temporary computed one.</p><pre>-- correlated subquery — references the outer query, runs per row<br>SELECT v.name FROM venues v<br>WHERE EXISTS (<br>    SELECT 1 FROM closures c WHERE c.venue_id = v.id<br>);</pre><p>This last one is genuinely different from the first two. It’s called “correlated” because the inner query references v.id from the outer query — it&#39;s not a standalone query you could run on its own, it depends on which outer row is currently being evaluated. Conceptually, Postgres runs this subquery once per row of the outer query, checking &quot;does at least one closure exist for this specific venue.&quot; Worth being careful with these on large tables, since running a subquery per row can get expensive if it&#39;s not written efficiently.</p><h3>EXISTS vs IN</h3><p>EXISTS stops as soon as it finds a single matching row — it doesn&#39;t need to know how many matches there are, just whether at least one exists, which also means it handles nulls in the subquery result more predictably. IN builds out the entire subquery result first and then checks membership against it. For &quot;does at least one related row exist&quot; type questions, EXISTS is usually the better fit, both for performance and for correctness around nulls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wraZOIVpNHct5HH83QZwaw.png" /></figure><h3>CTEs: naming your intermediate steps</h3><pre>WITH closed_venues AS (<br>    SELECT venue_id FROM closures<br>)<br>SELECT * FROM venues<br>WHERE id IN (SELECT venue_id FROM closed_venues);</pre><p>A CTE — the WITH clause — lets you name a piece of a query and reference it later in the same statement, instead of nesting subqueries inside each other until the query becomes hard to read top to bottom. This particular example is simple enough that it wouldn&#39;t really need a CTE, but the value becomes obvious once a query has three or four logical steps chained together — each one gets a name, and the final query reads almost like a short paragraph instead of a wall of nested parentheses.</p><p>CTEs are also how you handle recursive queries, using WITH RECURSIVE, which is the standard way to deal with hierarchical data — something like a category tree, where categories can have subcategories that have their own subcategories. That&#39;s a bigger topic on its own and probably deserves its own explanation somewhere down the line rather than a paragraph here.</p><p>One historical detail worth knowing if it comes up: older versions of Postgres treated CTEs as what’s called an “optimization fence” — meaning the planner would essentially compute the whole CTE first, in isolation, before using it in the rest of the query, even if that wasn’t the most efficient approach. Since Postgres 12, CTEs are generally optimized more like subqueries, folded into the overall query plan rather than treated as a hard boundary. If someone asks why you’d use a CTE instead of a subquery, readability and reusability within the same query are the main reasons now — the performance difference that used to matter mostly doesn’t anymore, on current versions.</p><h3>Putting a few of these together</h3><p>Say you want cities where the average venue latitude is unusually high, but only among cities that actually have a meaningful number of venues — filtering out cities with just one or two entries that could skew the average:</p><pre>WITH city_stats AS (<br>    SELECT city, AVG(latitude) AS avg_lat, COUNT(*) AS venue_count<br>    FROM venues<br>    GROUP BY city<br>)<br>SELECT city, avg_lat, venue_count<br>FROM city_stats<br>WHERE venue_count &gt;= 5<br>ORDER BY avg_lat DESC;</pre><p>The CTE computes both the average and the count per city in one pass, and the outer query then filters on venue_count, which at this point is just a regular column value, not an aggregate anymore — so it goes in WHERE, not HAVING, since the grouping already happened inside the CTE. This is a good example of how naming an intermediate result makes the logic of a query clearer than trying to cram the same thing into one query with HAVING doing double duty.</p><h3>Where this leaves you</h3><p>WHERE filters rows, HAVING filters groups, and the reason for the split comes down to when each one actually runs relative to GROUP BY. Subqueries let you use the result of one query inside another, and CTEs let you name those intermediate steps instead of nesting them — mostly for readability at this point, less so for performance on modern Postgres versions.</p><p>Next up: indexes — how to actually make these queries fast, and just as importantly, when adding an index doesn’t help at all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09e2f0898af5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Joins in PostgreSQL]]></title>
            <link>https://medium.com/@im_nishant/joins-in-postgresql-652a5a063883?source=rss-cebe471cee83------2</link>
            <guid isPermaLink="false">https://medium.com/p/652a5a063883</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Nishant Gaurav]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 16:31:01 GMT</pubDate>
            <atom:updated>2026-10-17T16:31:01.817Z</atom:updated>
            <content:encoded><![CDATA[<p>Joins are one of those topics where everyone nods along when you explain them, then freezes up the moment they have to write one on the spot, in front of someone, without being able to run it first and check. I think that’s mostly because the four main types genuinely blur together if you’ve only half-memorized their definitions instead of actually understanding what each one is doing to the result set. This article is my attempt at explaining them the way I eventually understood them, not the way they’re usually first presented.</p><h3>Why this is the part people freeze on</h3><p>The syntax for a join isn’t hard. SELECT ... FROM a JOIN b ON a.x = b.y — that&#39;s most of it. What actually trips people up is reasoning about what rows come back, especially when the two tables don&#39;t match up perfectly. A venue with no closures. A closure somehow pointing at a venue that doesn&#39;t exist. These edge cases are exactly what separates the four join types, and if you&#39;ve only memorized &quot;LEFT JOIN keeps everything on the left,&quot; without really internalizing why, you&#39;ll get it backwards the first time you&#39;re asked to write one under any pressure.</p><h3>Working through all four, using the same two tables</h3><p>Assume venues and closures, where closures.venue_id references venues.id.</p><pre>-- INNER JOIN: only rows that match in both tables<br>SELECT v.name, c.closed_on<br>FROM venues v<br>INNER JOIN closures c ON v.id = c.venue_id;</pre><p>This gives you venues that actually have at least one closure recorded. A venue with zero closures just doesn’t show up at all — not as a row with nulls, it’s simply absent from the result.</p><pre>-- LEFT JOIN: all venues, even ones with no closures<br>SELECT v.name, c.closed_on<br>FROM venues v<br>LEFT JOIN closures c ON v.id = c.venue_id;</pre><p>Every venue shows up here, whether or not it has closures. For venues with no matching closure row, c.closed_on just comes back as null. This is probably the join you&#39;ll reach for most often in practice, since &quot;show me all of X, along with whatever related Y exists&quot; is an extremely common shape of question.</p><pre>-- RIGHT JOIN: all closures, even orphaned ones<br>SELECT v.name, c.closed_on<br>FROM venues v<br>RIGHT JOIN closures c ON v.id = c.venue_id;</pre><p>The mirror image of LEFT JOIN — every closure shows up, even if somehow its venue_id doesn&#39;t match any real venue. In practice this is rare to actually use, since you can just swap the table order and use LEFT JOIN instead, which is why most people default to always writing LEFT JOIN and almost never reach for RIGHT JOIN even though it exists.</p><pre>-- FULL OUTER JOIN: everything from both sides<br>SELECT v.name, c.closed_on<br>FROM venues v<br>FULL OUTER JOIN closures c ON v.id = c.venue_id;</pre><p>Everything from both tables, matched where possible, with nulls filling in on whichever side doesn’t have a match. Less common day to day, but genuinely useful when you need to audit both directions at once — venues with no closures, and closures pointing at venues that no longer exist.</p><p>A simpler way I ended up explaining these to myself: INNER only wants pairs that actually match. LEFT wants everything from the left table no matter what, filling in gaps with null. RIGHT is the same idea flipped. FULL OUTER wants everything from both, period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdvkj-y64vhkfoF6jCHjgg.png" /></figure><h3>Self joins, and the thing that goes wrong without an ON clause</h3><pre>-- venues in the same city, paired against each other<br>SELECT a.name, b.name<br>FROM venues a<br>JOIN venues b ON a.city = b.city AND a.id &lt; b.id;</pre><p>This is a self join — the same table joined against itself, using two aliases (a and b) so Postgres can tell which &quot;copy&quot; of the table a given column reference belongs to. The classic real-world case is an employee-manager table, where each row references another row in the same table. Here it&#39;s a more contrived example — pairing up venues that share a city — but the mechanics are identical. The a.id &lt; b.id part matters too: without it, you&#39;d get every pair twice, once in each order, plus every venue paired with itself.</p><p>The mistake that catches almost everyone at least once: forgetting the ON condition entirely, or getting it wrong in a way that matches everything. That gives you a CROSS JOIN by accident — every row from one table matched with every row from the other, a full Cartesian product. If a join query comes back with a suspiciously huge row count, way more than you&#39;d expect, this is almost always why. It&#39;s usually pretty obvious once you see it, but it&#39;s an easy thing to miss for a minute if you&#39;re staring at a query that looks syntactically fine.</p><p>A real CROSS JOIN does have legitimate uses — generating every combination of two sets, like all dates crossed with all venues for a reporting calendar that needs a row for every date-venue pair regardless of whether anything happened. It&#39;s rare, but it&#39;s worth knowing it&#39;s an intentional tool sometimes, not just a mistake that happens to have a name.</p><h3>Working through a real query</h3><p>Say you want a report: every venue, and how many times it’s been closed, including venues that have never been closed at all, showing zero rather than being left out.</p><pre>SELECT v.name, COUNT(c.id) AS closure_count<br>FROM venues v<br>LEFT JOIN closures c ON v.id = c.venue_id<br>GROUP BY v.name<br>ORDER BY closure_count DESC;</pre><p>The LEFT JOIN is doing the actual work here — it&#39;s what makes sure venues with zero closures still show up, instead of silently vanishing the way they would with an INNER JOIN. COUNT(c.id) matters more than it looks like it should: for a venue with no closures, the joined c.id value is null, and COUNT() doesn&#39;t count nulls, so it correctly comes back as zero. If you&#39;d written COUNT(*) instead, every row would count as one regardless of whether c.id was null, and a venue with no closures would incorrectly show a count of one instead of zero, because the LEFT JOIN still produces exactly one row for it, just with null values in it.</p><p>That’s a small detail, but it’s exactly the kind of thing that produces a report with numbers that are subtly wrong in a way that’s easy to miss during a quick review.</p><h3>Where this leaves you</h3><p>The four join types aren’t really four different things to memorize — they’re one idea (match rows between two tables based on a condition) with different rules about what happens when a match doesn’t exist on one side or the other. If you can explain, out loud, what happens to an unmatched row in each of the four cases, you understand joins. If you’re just recalling which keyword goes with which definition, that’s worth practicing out loud a few times before it comes up somewhere that actually matters.</p><p>Next up: aggregations — GROUP BY, HAVING, and the subquery patterns that come up constantly once you start asking more complex questions of your data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=652a5a063883" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The WHERE Clause In PostgreSQL]]></title>
            <link>https://medium.com/@im_nishant/the-where-clause-in-postgresql-c33d77bda8b4?source=rss-cebe471cee83------2</link>
            <guid isPermaLink="false">https://medium.com/p/c33d77bda8b4</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Nishant Gaurav]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 16:31:01 GMT</pubDate>
            <atom:updated>2026-10-16T16:31:01.819Z</atom:updated>
            <content:encoded><![CDATA[<p>WHERE is one of the first things you learn in SQL, and it&#39;s also one of the things people stop paying attention to too early. It feels solved — you know the syntax, you&#39;ve written a hundred of these; why would there be more to say about it. But there are a few Postgres-specific details in here that genuinely surprised me, and a habit around combining conditions that I only picked up after seeing it go wrong once.</p><h3>Where this quietly causes bugs</h3><p>Say you’ve got a query filtering venues that are open, and either in Bhopal or have no city set yet:</p><pre>SELECT * FROM venues<br>WHERE is_closed = FALSE<br>  AND city = &#39;Bhopal&#39; OR city IS NULL;</pre><p>This looks reasonable at a glance. It’s wrong. Without parentheses, AND binds tighter than OR, so this actually reads as &quot;give me rows where (closed is false and city is Bhopal), or (city is null) — regardless of whether they&#39;re closed.&quot; You&#39;d get back closed venues with no city set, which almost certainly isn&#39;t what you meant.</p><p>This is the kind of bug that doesn’t announce itself. The query runs, it returns rows, nothing errors — it’s just quietly including data it shouldn’t. You usually catch it because a number looks off in a report, not because anything crashed.</p><h3>The basics, and the Postgres-specific one</h3><pre>SELECT * FROM venues WHERE latitude &gt; 23.2;<br>SELECT * FROM venues WHERE name IN (&#39;DB Mall&#39;, &#39;Upper Lake&#39;);<br>SELECT * FROM venues WHERE name LIKE &#39;Van%&#39;;        -- case-sensitive pattern match<br>SELECT * FROM venues WHERE name ILIKE &#39;van%&#39;;       -- case-insensitive<br>SELECT * FROM venues WHERE created_at BETWEEN &#39;2026-01-01&#39; AND &#39;2026-12-31&#39;;<br>SELECT * FROM venues WHERE city IS NULL;</pre><p>Most of this is standard SQL and probably familiar already. ILIKE is the one worth calling out specifically, because it&#39;s Postgres-specific — MySQL&#39;s LIKE happens to behave case-insensitively by default depending on the collation setting, which is its own small gotcha if you&#39;re used to that behavior and then move to Postgres and suddenly your pattern matches stop working the way you expect. In Postgres, LIKE is case-sensitive, full stop, and ILIKE is the explicit case-insensitive version. If someone asks about this in an interview, it&#39;s usually less about the syntax and more about whether you&#39;ve actually worked with Postgres specifically rather than SQL in the abstract.</p><p>IN versus a chain of OR conditions is mostly a readability choice at this scale — WHERE name IN (&#39;DB Mall&#39;, &#39;Upper Lake&#39;) says the same thing as WHERE name = &#39;DB Mall&#39; OR name = &#39;Upper Lake&#39;, just more compactly once you&#39;re checking against more than two or three values.</p><h3>Combining conditions without shooting yourself</h3><pre>SELECT * FROM venues<br>WHERE is_closed = FALSE<br>  AND (city = &#39;Bhopal&#39; OR city IS NULL);</pre><p>The fix for the earlier bug is just parentheses, grouping the OR explicitly. The bigger point isn&#39;t the specific bug — it&#39;s that relying on memorized operator precedence rules, and getting them right every time under pressure, isn&#39;t a great strategy. Parenthesizing mixed AND/OR conditions costs nothing and means the query reads correctly on its own, without anyone needing to recall precedence rules to verify it during a code review.</p><p>I started doing this by default after the bug above, not because someone told me to as a rule. It’s one of those habits that feels unnecessary right up until it isn’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPoqJCg-WOthEwZroagQEA.png" /></figure><h3>Sorting and limiting</h3><pre>SELECT * FROM venues ORDER BY created_at DESC LIMIT 5;</pre><p>Not much complexity here on its own — ORDER BY sorts, LIMIT caps how many rows come back. The thing worth knowing now, even though it&#39;s really a topic for the indexing article later in this series, is that ORDER BY on a large table without a supporting index means Postgres has to sort the entire result set before it can hand back even a LIMIT 5. It works fine on a few thousand rows. It gets noticeably slower as a table grows, which is part of why indexing decisions and query patterns end up tied together more than they look at first.</p><h3>Putting a few of these together</h3><p>Say you’re building the “nearby open venues in my city, or venues where we don’t know the city yet” view for the dashboard — a genuinely realistic filter, since city data synced from an external API is exactly the kind of field that sometimes comes back empty:</p><pre>SELECT name, latitude, longitude, city<br>FROM venues<br>WHERE is_closed = FALSE<br>  AND (city ILIKE &#39;bhopal&#39; OR city IS NULL)<br>ORDER BY name ASC<br>LIMIT 20;</pre><p>This uses ILIKE instead of = for the city comparison, since city names synced from an external source aren&#39;t always consistently capitalized — Bhopal versus bhopal versus BHOPAL depending on which upstream feed the data came from. The parentheses around the OR keep the null-handling correct. And LIMIT caps it to a reasonable page size instead of pulling back everything at once. None of these individually is complicated, but stacking them correctly, in the right order and with the right grouping, is really what filtering well in practice comes down to.</p><h3>Where this leaves you</h3><p>WHERE clauses feel basic enough that it&#39;s easy to stop thinking carefully about them once you know the syntax. The two things actually worth carrying forward: parenthesize mixed AND/OR conditions every time, even when you&#39;re fairly sure you have precedence right, and remember that ILIKE is a Postgres-specific tool, not something you can assume exists everywhere.</p><p>Next up: joins — which is where a lot of the real anxiety around SQL interviews tends to live, and honestly for good reason, since it’s easy to get subtly wrong in a way that still returns results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c33d77bda8b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>