<?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 Varsha Vishwakarma on Medium]]></title>
        <description><![CDATA[Stories by Varsha Vishwakarma on Medium]]></description>
        <link>https://medium.com/@chikuv2205?source=rss-b0c08ff5343d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8R0FLdp2xJ4Zl0INVd1_xA.png</url>
            <title>Stories by Varsha Vishwakarma on Medium</title>
            <link>https://medium.com/@chikuv2205?source=rss-b0c08ff5343d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 09:29:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chikuv2205/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[SQL Window Functions — Explained Simply | SQL Interview Series #6]]></title>
            <link>https://medium.com/@chikuv2205/sql-window-functions-explained-simply-sql-interview-series-6-c1172634d724?source=rss-b0c08ff5343d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1172634d724</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Varsha Vishwakarma]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 16:48:12 GMT</pubDate>
            <atom:updated>2026-09-23T16:48:12.414Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL Window Functions — Explained Simply | SQL Interview Series #6</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*viNJL6_f3HL57Ray484nXQ@2x.jpeg" /></figure><p>If you have been working with SQL, you may have used GROUP BY to calculate things like SUM(), AVG(), COUNT(), and MAX().</p><p>But there is one problem with GROUP BY.</p><p>It <strong>combines multiple rows into one row</strong>.</p><p>What if we want to calculate something across multiple rows but still want to see <strong>every individual row</strong>?</p><p>That’s where <strong>Window Functions</strong> come in. 🚀</p><h3>What is a Window Function?</h3><p>A Window Function performs a calculation using a group of related rows, but <strong>it does not remove the individual rows</strong>.</p><p>Let’s understand this with a simple example.</p><p>Suppose we have an Employees table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*-lYn35j_2o1fbHKXXzEK9Q.png" /><figcaption>Table: Employees</figcaption></figure><p>Now suppose we want to find the <strong>average salary of each department</strong>.</p><p>With GROUP BY:</p><pre>SELECT <br>    Department,<br>    AVG(Salary) AS AvgSalary<br>FROM Employees<br>GROUP BY Department;</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*52O2v-VyfvgvIfvxeyPgLg.png" /><figcaption>Output</figcaption></figure><p>This works.</p><p>But notice something.</p><p>We lost the individual employee details.</p><p>What if we want this instead?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*9B1TDCyQRdy19eXEWRujYw.png" /></figure><p>This is where a <strong>Window Function</strong> is useful.</p><pre>SELECT <br>    Employee,<br>    Department,<br>    Salary,<br>    AVG(Salary) OVER(PARTITION BY Department) AS AvgSalary<br>FROM Employees;</pre><p>Now we get the average salary while keeping <strong>every employee row</strong>.</p><p>That’s the main idea behind Window Functions.</p><h3>Why do we use Window Functions?</h3><p>Window Functions are very useful when we want to:</p><ul><li>Give a number to each row</li><li>Rank employees or products</li><li>Find the previous or next row</li><li>Compare one row with another</li><li>Calculate running totals</li><li>Calculate averages without grouping the rows</li></ul><p>Some commonly used Window Functions are:</p><pre>ROW_NUMBER()<br>RANK()<br>DENSE_RANK()<br>LAG()<br>LEAD()<br>SUM()<br>AVG()</pre><p>Let’s understand them one by one.</p><h3>1. ROW_NUMBER()</h3><p>ROW_NUMBER() gives a unique number to each row.</p><p>For example:</p><pre>SELECT<br>    Employee,<br>    Department,<br>    Salary,<br>    ROW_NUMBER() OVER(ORDER BY Salary DESC) AS RowNum<br>FROM Employees;</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*rR3iAF_QIcdjeMo0nLdPMw.png" /></figure><p>The employee with the highest salary gets 1, the next gets 2, and so on.</p><h3>Want numbering to restart for each department?</h3><p>Use PARTITION BY.</p><pre>SELECT<br>    Employee,<br>    Department,<br>    Salary,<br>    ROW_NUMBER() OVER(<br>        PARTITION BY Department<br>        ORDER BY Salary DESC<br>    ) AS RowNum<br>FROM Employees;</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*6DB5Ag7jp74pKL110z8nlQ.png" /></figure><p>Here, numbering starts again from 1 for each department.</p><h3>2. RANK()</h3><p>RANK() is used when we want to give a rank to rows.</p><p>Let’s add another employee:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*u_kG3qZDXlq7KjV3PxVR9A.png" /></figure><p>Now:</p><pre>SELECT<br>    Employee,<br>    Salary,<br>    RANK() OVER(ORDER BY Salary DESC) AS SalaryRank<br>FROM Employees;</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*rX32W-30SlJfS5wMAc60IQ.png" /></figure><p>Notice something?</p><p>Both Priya and Karan have the same salary, so both get <strong>Rank 1</strong>.</p><p>But the next person gets <strong>Rank 3</strong>.</p><p>This is an important point to remember.</p><h3>3. DENSE_RANK()</h3><p>DENSE_RANK() is also used for ranking.</p><p>The main difference is what happens after a tie.</p><p>Using the same example:</p><pre>SELECT<br>    Employee,<br>    Salary,<br>    DENSE_RANK() OVER(ORDER BY Salary DESC) AS SalaryRank<br>FROM Employees;</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*FUIt5wVCedc27pBzGTYryg.png" /></figure><p>Here, after two people get Rank 1, the next person gets Rank 2.</p><h3>So what is the difference?</h3><p>The easiest way to remember it:</p><pre>ROW_NUMBER()<br>→ Always gives a different number</pre><pre>RANK()<br>→ Same rank for same values, but skips the next rank</pre><pre>DENSE_RANK()<br>→ Same rank for same values, but does NOT skip the next rank</pre><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*FyYA1Z0jPHC0sifB5t-s-w.png" /></figure><p>This difference is a <strong>very common SQL interview question</strong>.</p><h3>4. LAG()</h3><p>Now let’s say we want to compare a row with the <strong>previous row</strong>.</p><p>For example, suppose we have monthly sales:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*QZz6E9v9tpBmfH9TIyO6hg.png" /></figure><p>We want to see the previous month’s sales.</p><p>We can use LAG():</p><pre>SELECT<br>    Month,<br>    Sales,<br>    LAG(Sales) OVER(ORDER BY Month) AS PreviousMonthSales<br>FROM Sales;</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*siLf-1newN4xrr06fBtOUg.png" /></figure><p>For January, there is no previous month, so we get NULL.</p><p>This is useful when we want to compare:</p><ul><li>This month’s sales vs last month’s sales</li><li>Current salary vs previous salary</li><li>Current transaction vs previous transaction</li></ul><h3>5. LEAD()</h3><p>LEAD() is almost the opposite of LAG().</p><p>LAG() → looks at the <strong>previous row</strong></p><p>LEAD() → looks at the <strong>next row</strong></p><p>Example:</p><pre>SELECT<br>    Month,<br>    Sales,<br>    LEAD(Sales) OVER(ORDER BY Month) AS NextMonthSales<br>FROM Sales;</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*qkj0Ls8JTYCM8TFEbXXPAw.png" /></figure><p>For April, there is no next month, so we get NULL.</p><h3>What is PARTITION BY?</h3><p>You may have noticed PARTITION BY in our queries.</p><p>Don’t let the name scare you. 😄</p><p>It simply means:</p><blockquote><strong><em>“Divide the data into groups and perform the calculation separately for each group.”</em></strong></blockquote><p>For example:</p><pre>ROW_NUMBER() OVER(<br>    PARTITION BY Department<br>    ORDER BY Salary DESC<br>)</pre><p>This means:</p><blockquote><em>Divide employees by department and give them a row number based on salary within each department.</em></blockquote><p>So IT employees are numbered separately, and HR employees are numbered separately.</p><h3>Window Function vs GROUP BY</h3><p>This is another important interview concept.</p><h3>GROUP BY</h3><p>GROUP BY combines rows.</p><pre>SELECT<br>    Department,<br>    AVG(Salary)<br>FROM Employees<br>GROUP BY Department;</pre><p>You get one row per department.</p><h3>Window Function</h3><p>A Window Function calculates the value but <strong>keeps the original rows</strong>.</p><pre>SELECT<br>    Employee,<br>    Department,<br>    Salary,<br>    AVG(Salary) OVER(PARTITION BY Department) AS AvgSalary<br>FROM Employees;</pre><p>You still get every employee.</p><h3>Easy way to remember:</h3><blockquote><strong><em>GROUP BY reduces rows. Window Functions keep the rows.</em></strong></blockquote><h3>A Real Interview Example</h3><p>Suppose an interviewer asks:</p><p><strong>“Find the second-highest salary in each department.”</strong></p><p>This is where Window Functions become very useful.</p><p>We can use DENSE_RANK():</p><pre>SELECT *<br>FROM (<br>    SELECT<br>        Employee,<br>        Department,<br>        Salary,<br>        DENSE_RANK() OVER(<br>            PARTITION BY Department<br>            ORDER BY Salary DESC<br>        ) AS SalaryRank<br>    FROM Employees<br>) AS E<br>WHERE SalaryRank = 2;</pre><p>First, we rank employees inside each department.</p><p>Then we select only Rank 2.</p><p>This type of question is very common in SQL interviews.</p><h3>Common Mistakes</h3><p>Here are a few things to remember while using Window Functions.</p><h3>1. Don’t forget ORDER BY</h3><p>For functions like ROW_NUMBER(), RANK(), and LAG(), the ORDER BY inside OVER() is very important.</p><pre>ROW_NUMBER() OVER(ORDER BY Salary DESC)</pre><h3>2. Understand PARTITION BY</h3><p>If you want the calculation separately for each group, use PARTITION BY.</p><pre>RANK() OVER(<br>    PARTITION BY Department<br>    ORDER BY Salary DESC<br>)</pre><h3>3. Don’t confuse RANK and DENSE_RANK</h3><p>Remember:</p><pre>RANK       → skips numbers after a tie<br>DENSE_RANK → does not skip numbers</pre><h3>Quick Interview Revision</h3><p>Before your interview, remember these simple points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*1B-wfWb8okj0QMew8FIvCQ.png" /></figure><h3>Final Takeaway 🚀</h3><p>Window Functions may look confusing at first, but the basic idea is actually simple:</p><blockquote><strong><em>They allow us to calculate something across multiple rows while still keeping each row in the result.</em></strong></blockquote><p>If you remember only these five functions, start with:</p><p><strong>ROW_NUMBER() → </strong><strong>RANK() → </strong><strong>DENSE_RANK() → </strong><strong>LAG() → </strong><strong>LEAD()</strong></p><p>Practice them with small datasets. Once you understand how they work, many SQL interview questions become much easier.</p><p>And remember:</p><blockquote><strong><em>Don’t just learn the syntax. Understand what problem the function is solving.</em></strong></blockquote><h3>Coming Up in Part 7 🚀</h3><p>In <strong>Part 7</strong>, we’ll explore another important SQL topic with simple explanations and practical examples.</p><p>Until then, keep practicing and keep learning.</p><p><strong>Happy Learning! 🚀</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1172634d724" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL CTEs (Common Table Expressions) Explained With Real Examples | SQL Interview Series #5]]></title>
            <link>https://medium.com/@chikuv2205/sql-ctes-common-table-expressions-explained-with-real-examples-sql-interview-series-5-414af47e6e8e?source=rss-b0c08ff5343d------2</link>
            <guid isPermaLink="false">https://medium.com/p/414af47e6e8e</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Varsha Vishwakarma]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 18:05:54 GMT</pubDate>
            <atom:updated>2026-08-19T18:05:54.217Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mx5dovGY7zRChFIHzxZiHg.png" /></figure><p>Have you ever written a SQL query with so many nested subqueries that even you couldn’t understand it the next day? 😭</p><p>You’re not alone.</p><p>As SQL queries become more complex, readability and maintainability become just as important as getting the correct result.</p><p>That’s where <strong>Common Table Expressions (CTEs)</strong> come in.</p><p>A CTE allows us to break a complicated query into smaller, logical steps, making the SQL easier to read, debug, and maintain.</p><p>In this article, we’ll understand CTEs with practical examples and cover some of the most common interview questions around them.</p><h3>What Is a CTE?</h3><p><strong>CTE stands for Common Table Expression.</strong></p><p>It is a temporary named result set that you can reference within the SQL statement that follows it.</p><p>The basic syntax is:</p><pre>WITH CTE_Name AS<br>(<br>    SELECT column1, column2<br>    FROM table_name<br>    WHERE condition<br>)<br>SELECT *<br>FROM CTE_Name;</pre><p>Think of a CTE as giving a <strong>name to an intermediate query result</strong>.</p><p>For example, suppose we have an Employees table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*z-HaWqQe3MpTZayM_HKE_Q.png" /><figcaption>Table: Employees</figcaption></figure><p>If we want to find employees earning more than ₹75,000:</p><pre>WITH HighSalaryEmployees AS<br>(<br>    SELECT *<br>    FROM Employees<br>    WHERE Salary &gt; 75000<br>)<br>SELECT *<br>FROM HighSalaryEmployees;</pre><p>Here, HighSalaryEmployees is our CTE.</p><p>The main query can then treat it almost like a temporary result table.</p><h3>Why Use a CTE?</h3><p>The biggest advantage of a CTE is <strong>readability</strong>.</p><p>Consider a query using a nested subquery:</p><pre>SELECT *<br>FROM<br>(<br>    SELECT<br>        Department,<br>        AVG(Salary) AS AvgSalary<br>    FROM Employees<br>    GROUP BY Department<br>) AS DepartmentSalary<br>WHERE AvgSalary &gt; 70000;</pre><p>It works, but as the query becomes larger, nested subqueries can become difficult to follow.</p><p>Now look at the same logic using a CTE:</p><pre>;WITH DepartmentSalary AS<br>(<br>    SELECT<br>        Department,<br>        AVG(Salary) AS AvgSalary<br>    FROM Employees<br>    GROUP BY Department<br>)<br>SELECT *<br>FROM DepartmentSalary<br>WHERE AvgSalary &gt; 70000;</pre><p>Much cleaner.</p><p>The CTE gives the intermediate result a meaningful name and separates the logic into steps.</p><h3>In simple terms:</h3><p><strong>Subquery:</strong> Put a query inside another query.</p><p><strong>CTE:</strong> Give that intermediate query a name and make the overall query easier to understand.</p><h3>Using Multiple CTEs</h3><p>One of the most useful features of CTEs is that you can define multiple CTEs in the same statement.</p><p>Suppose we want to:</p><ol><li>Calculate the average salary for each department.</li><li>Find departments where the average salary is above ₹70,000.</li><li>Get employees belonging to those departments.</li></ol><p>We can break this into two CTEs:</p><pre>;WITH DepartmentSalary AS<br>(<br>    SELECT<br>        Department,<br>        AVG(Salary) AS AvgSalary<br>    FROM Employees<br>    GROUP BY Department<br>),<br>HighPayingDepartments AS<br>(<br>    SELECT<br>        Department,<br>        AvgSalary<br>    FROM DepartmentSalary<br>    WHERE AvgSalary &gt; 70000<br>)<br>SELECT<br>    e.EmployeeName,<br>    e.Department,<br>    e.Salary,<br>    h.AvgSalary<br>FROM Employees e<br>JOIN HighPayingDepartments h<br>    ON e.Department = h.Department;</pre><p>Instead of writing one huge query, we have created a simple flow:</p><pre>Employees<br>    ↓<br>DepartmentSalary<br>    ↓<br>HighPayingDepartments<br>    ↓<br>Final Result</pre><p>This pattern is extremely useful when working with complex reporting or data transformation queries.</p><h3>CTE + Window Functions</h3><p>Here’s where CTEs become particularly useful in interviews.</p><p>Suppose the interviewer asks:</p><blockquote><strong><em>Find the highest-paid employee in each department.</em></strong></blockquote><p>We can use ROW_NUMBER() inside a CTE:</p><pre>WITH RankedEmployees AS<br>(<br>    SELECT<br>        EmployeeID,<br>        EmployeeName,<br>        Department,<br>        Salary,<br>        ROW_NUMBER() OVER<br>        (<br>            PARTITION BY Department<br>            ORDER BY Salary DESC<br>        ) AS RowNum<br>    FROM Employees<br>)<br>SELECT<br>    EmployeeID,<br>    EmployeeName,<br>    Department,<br>    Salary<br>FROM RankedEmployees<br>WHERE RowNum = 1;</pre><p>The CTE first ranks employees within each department.</p><p>Then the outer query simply selects:</p><pre>WHERE RowNum = 1</pre><p>This is a very common SQL pattern.</p><p>You can also modify it to find the second-highest salary, top 3 employees per department, duplicates, and many other scenarios.</p><h3>Recursive CTEs</h3><p>CTEs aren’t limited to simple queries.</p><p>They can also be <strong>recursive</strong>.</p><p>A recursive CTE is useful when working with hierarchical data such as:</p><ul><li>Employee-manager relationships</li><li>Organization structures</li><li>Folder hierarchies</li><li>Category trees</li></ul><p>Consider:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*1JAoGvHJCfQlhLv1jFdzMg.png" /></figure><p>The hierarchy is:</p><pre>CEO<br>├── Rahul<br>│   ├── Amit<br>│   └── Neha<br>└── Priya</pre><p>A recursive CTE can traverse this hierarchy:</p><pre>WITH EmployeeHierarchy AS<br>(<br>    -- Anchor member<br>    SELECT<br>        EmployeeID,<br>        EmployeeName,<br>        ManagerID,<br>        0 AS Level<br>    FROM Employees<br>    WHERE ManagerID IS NULL<br></pre><pre>UNION ALL<br><br>-- Recursive member<br>    SELECT<br>        e.EmployeeID,<br>        e.EmployeeName,<br>        e.ManagerID,<br>        eh.Level + 1<br>    FROM Employees e<br>    JOIN EmployeeHierarchy eh<br>        ON e.ManagerID = eh.EmployeeID<br>)<br>SELECT *<br>FROM EmployeeHierarchy;</pre><p>The important idea here is:</p><p><strong><em>Anchor → Recursive step → Next level → Repeat</em></strong></p><p>You don’t need to memorize the entire query for an interview. Understand the concept and know when recursive CTEs are useful.</p><h3>CTE vs Temporary Table vs View</h3><p>This is another popular interview question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*NTHj9jqC9wjYpWBsM_2uUA.png" /><figcaption>CTE vs Temporary Table vs View</figcaption></figure><h3>Easy way to remember:</h3><p><strong>CTE → Organize one query</strong></p><p><strong>Temporary Table → Store and reuse intermediate data</strong></p><p><strong>View → Save reusable query logic</strong></p><h3>Are CTEs Faster?</h3><p>Here’s a common misconception:</p><blockquote><strong><em>“CTEs are faster than subqueries.”</em></strong></blockquote><p>Not necessarily.</p><p>A CTE is mainly a <strong>readability and query-organization feature</strong>.</p><p>The actual performance depends on factors such as:</p><ul><li>Indexes</li><li>Joins</li><li>Filters</li><li>Data volume</li><li>Query structure</li><li>Database optimizer</li><li>Execution plan</li></ul><p>So don’t choose a CTE simply because you think it will automatically make the query faster.</p><p>Choose it when it makes the logic <strong>clearer and easier to maintain</strong>, and always check the execution plan when performance matters.</p><h3>Common CTE Mistakes</h3><h3>1. Thinking the CTE is a permanent table</h3><p>It isn’t.</p><p>A CTE normally exists only for the SQL statement immediately following it.</p><pre>WITH EmployeeCTE AS<br>(<br>    SELECT *<br>    FROM Employees<br>)<br>SELECT *<br>FROM EmployeeCTE;</pre><p>Once that statement finishes, the CTE is gone.</p><h3>2. Using a CTE for a simple query</h3><p>Don’t turn this:</p><pre>SELECT *<br>FROM Employees;</pre><p>into this:</p><pre>;WITH EmployeeCTE AS<br>(<br>    SELECT *<br>    FROM Employees<br>)<br>SELECT *<br>FROM EmployeeCTE;</pre><p>That’s not making your SQL cleaner. 😂</p><p>Use CTEs when they actually simplify your logic.</p><h3>3. Assuming CTE = performance improvement</h3><p>As mentioned earlier, CTEs don’t automatically make queries faster.</p><p><strong>Readability first. Performance should be validated separately.</strong></p><h3>SQL Interview Questions</h3><h3>1. What is a CTE?</h3><p>A CTE is a named temporary result set defined using the WITH clause and available within a single SQL statement.</p><h3>2. Why use a CTE?</h3><p>Primarily to improve readability, organize complex logic, and avoid deeply nested queries.</p><h3>3. Can we have multiple CTEs?</h3><p>Yes.</p><pre>WITH CTE1 AS<br>(<br>    SELECT ...<br>),<br>CTE2 AS<br>(<br>    SELECT ...<br>    FROM CTE1<br>)<br>SELECT *<br>FROM CTE2;</pre><h3>4. Can one CTE reference another CTE?</h3><p>Yes. A later CTE can reference an earlier CTE in the same WITH clause.</p><h3>5. What is a recursive CTE?</h3><p>A recursive CTE references itself and is commonly used to work with hierarchical or parent-child data.</p><h3>6. Are CTEs faster than subqueries?</h3><p>Not necessarily. Performance depends on the query, database optimizer, indexes, data volume, and execution plan.</p><h3>Final Takeaway</h3><p>CTEs are one of those SQL features that look simple but become extremely useful as queries get more complicated.</p><p>Remember these key points:</p><ul><li><strong>CTE = Common Table Expression</strong></li><li>Defined using the WITH keyword</li><li>Makes complex queries easier to read</li><li>Can replace deeply nested subqueries</li><li>Multiple CTEs can be chained together</li><li>Works especially well with Window Functions</li><li>Recursive CTEs are useful for hierarchical data</li><li>CTEs don’t automatically improve performance</li><li>Always use them when they make your SQL clearer — not simply because you can</li></ul><p>The goal isn’t to write the shortest SQL query.</p><p>The goal is to write SQL that is <strong>correct, readable, maintainable, and easy for the next developer to understand.</strong></p><p>And yes, sometimes that next developer is <strong>you six months later.</strong> 😭</p><h3>What’s Next?</h3><p>In <strong>Part 6</strong>, we’ll move into another extremely important SQL interview topic and explore <strong>Window Functions</strong> with practical examples.</p><p>Until then, keep practicing, stay curious, and remember:</p><p><strong>Great SQL isn’t just about getting the right answer — it’s about writing queries that make sense. 🚀</strong></p><p>If you found this article helpful, consider <strong>sharing it with your friends or colleagues</strong>, and don’t forget to <strong>follow this SQL Interview Series</strong> so you don’t miss the next article.</p><p><strong>Happy Learning, and I’ll see you in Part 6! 🚀</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=414af47e6e8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EXISTS vs IN in SQL Explained with Real Examples | SQL Interview Series (Part 4)]]></title>
            <link>https://medium.com/@chikuv2205/exists-vs-in-in-sql-explained-with-real-examples-sql-interview-series-part-4-ecc2e450f0c0?source=rss-b0c08ff5343d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecc2e450f0c0</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Varsha Vishwakarma]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 09:14:52 GMT</pubDate>
            <atom:updated>2026-07-23T09:14:52.211Z</atom:updated>
            <content:encoded><![CDATA[<h3>EXISTS vs IN in SQL Explained with Real Examples | SQL Interview Series #4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3i9PRXGTcVjeUvgA6mOgAQ.png" /></figure><p><em>Ever written a query that returned the correct results — but took forever to execute?</em></p><p>Or perhaps you’ve been asked in an interview:</p><blockquote><strong><em>“When would you use EXISTS instead of IN?”</em></strong></blockquote><p>At first glance, both seem to solve the same problem.</p><p>They both help us check whether matching values exist in another table.</p><p>So naturally, many beginners ask:</p><blockquote><strong><em>“If both produce the same result, why do we have two different operators?”</em></strong></blockquote><p>The answer lies in <strong>how SQL executes the query</strong>, not just what it returns.</p><p>And understanding that difference can save you from writing slow queries in production systems.</p><p>In this article, we’ll learn <strong>EXISTS vs IN</strong> using real business examples from Amazon, Swiggy, Netflix, and Banking systems. By the end, you’ll know not only which one to use but also <em>why</em>.</p><h3>What You’ll Learn</h3><p>In this article, we’ll cover:</p><ul><li>What EXISTS is</li><li>What IN is</li><li>How they work internally</li><li>Differences between EXISTS and IN</li><li>Performance comparison</li><li>NULL behavior</li><li>Interview questions</li><li>Common mistakes</li><li>Best practices</li></ul><p>Let’s begin.</p><h3>A Real-Life Story</h3><p>Imagine you work as a Data Engineer at Amazon.</p><p>The company wants to identify customers who have placed at least one order.</p><p>There are two tables:</p><p><strong>Customers:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*ozb27Q9nyjdRPCT1o72YTQ.png" /><figcaption>Table: Customers</figcaption></figure><p><strong>Orders:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*i62jTzZjWtY6r2mFGRyukg.png" /><figcaption>Table: Orders</figcaption></figure><p>Business wants this output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*bqSut7kFEmFVeXOifB3Whw.png" /><figcaption>Output</figcaption></figure><p>Notice something?</p><p>We don’t care <strong>how many orders</strong> Alice placed.</p><p>We only want to know whether <strong>at least one order exists</strong>.</p><p>This is exactly where EXISTS shines.</p><h3>Understanding EXISTS</h3><p>The EXISTS operator checks whether the subquery returns <strong>at least one row</strong>.</p><p>The moment SQL finds the first matching record, it stops searching.</p><p>Think of it like checking attendance.</p><p>Teacher asks:</p><blockquote><em>“Is Rahul present?”</em></blockquote><p>The monitor sees Rahul sitting in the first row.</p><p>Does the monitor continue checking every student?</p><p>No.</p><p>The answer is already found.</p><p>That’s how EXISTS works.</p><h3>SQL Query</h3><pre>SELECT CustomerID,<br>       Name<br>FROM Customers C<br>WHERE EXISTS<br>(<br>    SELECT 1<br>    FROM Orders O<br>    WHERE O.CustomerID = C.CustomerID<br>);</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*8j_B0Fc49lRNFITzsTHUQw.png" /><figcaption>Output</figcaption></figure><h3>Execution Flow of EXISTS</h3><p>For every customer:</p><p>Customer 1</p><p>↓</p><p>Order found?</p><p>↓</p><p>Yes</p><p>↓</p><p>Return Alice</p><p>Customer 2</p><p>↓</p><p>Order found?</p><p>↓</p><p>No</p><p>↓</p><p>Skip</p><p>Customer 3</p><p>↓</p><p>Order found?</p><p>↓</p><p>Yes</p><p>↓</p><p>Return Charlie</p><p>Notice something important?</p><p>SQL stops searching after the <strong>first match</strong>.</p><p>It never scans unnecessary rows.</p><h3>Understanding IN</h3><p>Now let’s solve the same problem using IN.</p><pre>SELECT CustomerID,<br>       Name<br>FROM Customers<br>WHERE CustomerID IN<br>(<br>    SELECT CustomerID<br>    FROM Orders<br>);</pre><p>Output</p><p>Exactly the same.</p><p>So what’s different?</p><p>IN first prepares a list of CustomerIDs.</p><pre>1<br>1<br>3</pre><p>Then SQL checks:</p><p>Is CustomerID = 1 in this list?</p><p>Is CustomerID = 2 in this list?</p><p>Is CustomerID = 3 in this list?</p><h3>Real-Life Example (Netflix)</h3><p>Netflix stores two tables.</p><h3>Users</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*eq5EDmKn9OjKnqDT6HBXDg.png" /><figcaption>Table: Users</figcaption></figure><h3>PremiumSubscriptions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*AnDGOQLZETJlo3KiMcGuvQ.png" /><figcaption>Table: PremiumSubscriptions</figcaption></figure><p>Find premium users.</p><p>Using IN:</p><pre>SELECT Name<br>FROM Users<br>WHERE UserID IN<br>(<br>    SELECT UserID<br>    FROM PremiumSubscriptions<br>);</pre><p>Simple.</p><p>Readable.</p><p>Perfect.</p><h3>Another Example (Swiggy)</h3><p>Swiggy wants restaurants that received at least one order today.</p><p>Tables:</p><p><strong>Restaurants</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*mSjgQ6Tk57MxtRe79aDu4g.png" /><figcaption>Table: Restaurants</figcaption></figure><p><strong>Orders</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*BDD3TSm2wGMSxCXlRZ4mvg.png" /><figcaption>Table: Orders</figcaption></figure><p>Using EXISTS</p><pre>SELECT Name<br>FROM Restaurants R<br>WHERE EXISTS<br>(<br>    SELECT 1<br>    FROM Orders O<br>    WHERE O.RestaurantID = R.RestaurantID<br>);</pre><p>The database stops after finding the first order.</p><p>Restaurant 1</p><p>First order found.</p><p>Done.</p><p>No need to check remaining orders.</p><h3>How SQL Executes EXISTS</h3><p>Suppose Orders has</p><p>10 million rows.</p><p>Restaurant 1 appears in Row 15.</p><p>EXISTS finds Row 15.</p><p>Stops.</p><p>Execution complete.</p><h3>How SQL Executes IN</h3><p>SQL often prepares the complete list first.</p><p>Even if Restaurant 1 appears in Row 15, SQL may still continue processing depending on the optimizer and execution plan.</p><p>This is why EXISTS is usually preferred for large correlated lookups.</p><h3>Performance Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*bAV6dqU8fEgi6pwz3I6soQ.png" /><figcaption>EXISTS vs IN</figcaption></figure><h3>Banking Example</h3><p>A bank wants customers who have at least one loan.</p><p><strong>Customers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*NLljOU40qduPL3YC0sbJow.png" /><figcaption>Table: Customers</figcaption></figure><p><strong>Loans</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*hTi-ctgAsXdU0NyS99ruaw.png" /><figcaption>Table: Loans</figcaption></figure><p>Using EXISTS</p><pre>SELECT Name<br>FROM Customers C<br>WHERE EXISTS<br>(<br>    SELECT 1<br>    FROM Loans L<br>    WHERE L.CustomerID = C.CustomerID<br>);</pre><p>As soon as LoanID 501 is found, SQL returns Amit.</p><p>LoanID 502 is irrelevant.</p><h3>EXISTS with Correlated Subquery</h3><p>One of the biggest strengths of EXISTS is that it works naturally with correlated subqueries.</p><pre>SELECT *<br>FROM Employees E<br>WHERE EXISTS<br>(<br>    SELECT 1<br>    FROM Attendance A<br>    WHERE A.EmployeeID = E.EmployeeID<br>);</pre><p>The inner query depends on the outer query.</p><p>This is exactly what correlated subqueries are designed for.</p><h3>What About NULL?</h3><p>Here’s where interviews become interesting.</p><p>Suppose Orders contains</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*bOYPeRX1TcqCG-GZz6qoEA.png" /><figcaption>Table: Orders</figcaption></figure><p>Now write</p><pre>SELECT *<br>FROM Customers<br>WHERE CustomerID IN<br>(<br>    SELECT CustomerID<br>    FROM Orders<br>);</pre><p>NULL introduces three-valued logic.</p><p>Depending on the query, comparisons involving NULL can produce unexpected results.</p><p>EXISTS doesn’t compare values directly.</p><p>It simply checks whether matching rows exist.</p><p>That’s why EXISTS avoids many NULL-related surprises.</p><h3>EXISTS vs IN — Quick Decision Guide</h3><p>Use <strong>EXISTS</strong> when:</p><ul><li>Working with large tables</li><li>Checking whether at least one row exists</li><li>Using correlated subqueries</li><li>Optimizing performance</li></ul><p>Use <strong>IN</strong> when:</p><ul><li>Comparing against a small lookup table</li><li>Writing simple readable queries</li><li>The subquery returns relatively few values</li><li>Performance isn’t a concern</li></ul><h3>Common Interview Questions</h3><h3>Q1. Which is faster?</h3><p>Answer:</p><p>There is no universal winner.</p><p>Modern query optimizers often rewrite both queries into similar execution plans.</p><p>However,</p><p>EXISTS generally performs better for large correlated searches because it stops after finding the first match.</p><h3>Q2. Why do developers write SELECT 1 inside EXISTS?</h3><pre>WHERE EXISTS<br>(<br>    SELECT 1<br>    FROM Orders<br>)</pre><p>Because EXISTS only checks whether rows exist.</p><p>It ignores the selected columns.</p><p>You can even write</p><pre>SELECT *</pre><p>and the result remains the same.</p><p>Using SELECT 1 simply makes the intent clear.</p><h3>Q3. Can EXISTS return duplicate rows?</h3><p>No.</p><p>EXISTS only returns rows from the outer query.</p><p>Duplicates depend on the outer table — not the subquery.</p><h3>Q4. Can IN use multiple columns?</h3><p>Yes, in some database systems using row constructors, but support varies by SQL dialect. In interviews, it’s safer to discuss single-column IN unless asked specifically about composite comparisons.</p><h3>Common Mistakes</h3><h3>Mistake 1</h3><p>Using EXISTS when a JOIN is actually needed.</p><p>Need customer names and order amounts?</p><p>Use JOIN.</p><p>Not EXISTS.</p><h3>Mistake 2</h3><p>Using IN on huge datasets unnecessarily.</p><p>This may increase memory usage and execution time depending on the optimizer.</p><h3>Mistake 3</h3><p>Ignoring indexes.</p><p>EXISTS performs best when the searched column is indexed.</p><h3>Mistake 4</h3><p>Confusing EXISTS with COUNT.</p><p>Instead of:</p><pre>SELECT COUNT(*)</pre><p>to check if data exists,</p><p>simply use EXISTS.</p><p>It avoids unnecessary counting.</p><h3>Best Practices</h3><ul><li>Use EXISTS when checking for the existence of related records in large datasets.</li><li>Use IN for small lookup lists where readability matters.</li><li>Create indexes on columns used in subqueries.</li><li>Understand execution plans instead of assuming one operator is always faster.</li><li>Be mindful of NULL values, especially when using NOT IN.</li></ul><h3>Key Takeaways</h3><ul><li>EXISTS stops searching after finding the first matching row.</li><li>IN compares values against a list returned by the subquery.</li><li>Both can produce the same result but may perform differently depending on the execution plan and data volume.</li><li>EXISTS is generally preferred for large correlated subqueries.</li><li>IN is clean, readable, and often ideal for small lookup datasets.</li><li>Understanding the execution plan matters more than memorizing “EXISTS is always faster.”</li></ul><h3>Conclusion</h3><p>At first glance, <strong>EXISTS</strong> and <strong>IN</strong> appear to be interchangeable. In many cases, they even return identical results. But writing efficient SQL isn’t just about getting the correct output — it’s about understanding how the database processes your query.</p><p>As your datasets grow from hundreds of rows to millions, these small choices can have a noticeable impact on performance. Knowing when to use EXISTS and when IN is sufficient is a skill that separates someone who can write SQL from someone who truly understands how SQL works.</p><p><strong>In Part 5, we’ll explore Common Table Expressions (CTEs)</strong> — one of the cleanest and most powerful SQL features for simplifying complex queries, improving readability, and replacing deeply nested subqueries. We’ll cover real-world examples, recursive CTEs, interview questions, common mistakes, and performance considerations to help you write cleaner, more maintainable SQL.</p><p>Until then, keep practicing, stay curious, and remember: <strong>great SQL isn’t just about getting the right answer — it’s about writing queries that are clear, efficient, and easy to maintain.</strong></p><p>If you found this article helpful, consider <strong>sharing it with your friends or colleagues</strong>, and don’t forget to <strong>follow this SQL Interview Series</strong> so you never miss the upcoming articles.</p><p><strong>Happy Learning, and I’ll see you in Part 5! 🚀</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecc2e450f0c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Correlated vs Non-Correlated Subqueries Explained with Real Interview Examples | SQL Interview…]]></title>
            <link>https://medium.com/@chikuv2205/correlated-vs-non-correlated-subqueries-explained-with-real-interview-examples-sql-interview-d794b8d0ff24?source=rss-b0c08ff5343d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d794b8d0ff24</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Varsha Vishwakarma]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 16:36:25 GMT</pubDate>
            <atom:updated>2026-07-08T16:36:25.717Z</atom:updated>
            <content:encoded><![CDATA[<h3>Correlated vs Non-Correlated Subqueries Explained with Real Interview Examples | SQL Interview Series #3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBAHVcYlkVPqjKmIZgD-5w.png" /></figure><p>After learning the basics of SQL Subqueries, the next concept you’ll almost certainly encounter in interviews is <strong>Correlated vs Non-Correlated Subqueries</strong>.</p><p>This topic often confuses beginners because both involve nested queries, but they work very differently.</p><p>If you’re preparing for SQL, Data Engineering, or Backend Developer interviews, understanding the difference is essential.</p><p>In this article, we’ll explore both types of subqueries using practical examples, execution flow, interview questions, and real-world business scenarios.</p><h3>What is a Non-Correlated Subquery?</h3><p>A <strong>Non-Correlated Subquery</strong> is a subquery that can execute independently of the outer query.</p><p>It does <strong>not</strong> depend on any values from the outer query.</p><p>The database executes the inner query <strong>once</strong>, stores the result, and then the outer query uses that result.</p><p>Think of it as asking a question first and then using the answer later.</p><h3>Example</h3><p>Suppose we have an Employees table.</p><h3>Employees Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*VnD_VF0LAQUAOTomwesIcw.png" /><figcaption>Table: Employees</figcaption></figure><h3>Problem</h3><p>Find employees whose salary is greater than the company’s average salary.</p><h3>SQL Query</h3><pre>SELECT EmployeeName,<br>       Salary<br>FROM Employees<br>WHERE Salary &gt;<br>(<br>    SELECT AVG(Salary)<br>    FROM Employees<br>);</pre><h3>How SQL Executes This Query</h3><h3>Step 1</h3><p>The database first executes the inner query.</p><pre>SELECT AVG(Salary)<br>FROM Employees;</pre><p>Result:</p><pre>Average Salary = 57,500</pre><h3>Step 2</h3><p>The outer query becomes:</p><pre>SELECT EmployeeName,<br>       Salary<br>FROM Employees<br>WHERE Salary &gt; 57500;</pre><h3>Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*emcTIU2ftNN9ZVQPiq6H_A.png" /><figcaption>Output</figcaption></figure><p>Notice that the subquery executed only <strong>once</strong>.</p><h3>What is a Correlated Subquery?</h3><p>A <strong>Correlated Subquery</strong> depends on values from the outer query.</p><p>Because of this dependency, the inner query executes <strong>once for every row</strong> processed by the outer query.</p><p>This makes correlated subqueries more powerful — but sometimes slower.</p><h3>Example</h3><p>Suppose every department has a different average salary.</p><p>We want to find employees earning more than the average salary <strong>within their own department</strong>.</p><h3>Employees Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*nHeHjEmMdFGxz_SInPMhdg.png" /><figcaption>Table: Employees</figcaption></figure><h3>SQL Query</h3><pre>SELECT e.EmployeeName,<br>       e.Department,<br>       e.Salary<br>FROM Employees e<br>WHERE e.Salary &gt;<br>(<br>    SELECT AVG(Salary)<br>    FROM Employees<br>    WHERE Department = e.Department<br>);</pre><p>Notice this line:</p><pre>WHERE Department = e.Department</pre><p>The subquery references <strong>e.Department</strong> from the outer query.</p><p>That’s why it’s called a <strong>Correlated Subquery</strong>.</p><h3>Execution Flow</h3><p>Imagine SQL processing the rows like this:</p><p>Employee: Alice</p><p>↓</p><p>Calculate average salary for IT</p><p>↓</p><p>Compare Alice’s salary</p><p>↓</p><p>Move to Charlie</p><p>↓</p><p>Calculate average salary for IT again</p><p>↓</p><p>Compare Charlie’s salary</p><p>↓</p><p>Move to Bob</p><p>↓</p><p>Calculate average salary for HR</p><p>↓</p><p>Compare Bob’s salary</p><p>The inner query keeps running repeatedly.</p><h3>Key Differences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*nroQAhyo3JHUa7u0RAa1yw.png" /><figcaption>Non-Correlated Vs Correlated</figcaption></figure><h3>Real-World Example</h3><p>Imagine you’re working for an e-commerce company.</p><h3>Non-Correlated Subquery</h3><p>Find all products whose price is higher than the overall average product price.</p><p>The average price is calculated once.</p><h3>Correlated Subquery</h3><p>Find products priced higher than the average price within <strong>their own category</strong>.</p><p>Now the average changes for every category.</p><p>The subquery must execute repeatedly.</p><h3>Performance Considerations</h3><p>Many interviewers ask:</p><p><strong>“Which is faster?”</strong></p><p>Generally:</p><p>✅ Non-Correlated Subqueries are faster because the inner query executes only once.</p><p>Correlated Subqueries execute many times and can become expensive on large datasets.</p><p>However, modern database optimizers can sometimes rewrite correlated subqueries into more efficient execution plans.</p><p>Always analyze query performance rather than assuming one approach is universally faster.</p><h3>Common Interview Questions</h3><h3>1. What is the biggest difference between correlated and non-correlated subqueries?</h3><p>A correlated subquery depends on the outer query, while a non-correlated subquery does not.</p><h3>2. Why are correlated subqueries slower?</h3><p>Because the inner query may execute once for every row returned by the outer query.</p><h3>3. Can correlated subqueries be replaced?</h3><p>Sometimes.</p><p>Depending on the requirement, they can often be rewritten using JOINs or window functions for better performance.</p><h3>4. Which one is asked more in interviews?</h3><p>Both are common, but correlated subqueries are often used to assess deeper SQL understanding.</p><h3>Common Mistakes</h3><p>❌ Thinking every subquery is correlated.</p><p>❌ Forgetting that a correlated subquery references the outer query.</p><p>❌ Assuming correlated subqueries are always slower.</p><p>❌ Using correlated subqueries where a JOIN would be simpler.</p><h3>Practice Questions</h3><h3>Question 1</h3><p>Find employees earning more than the average salary of their department.</p><h3>Question 2</h3><p>Find customers who spent more than the average order value.</p><h3>Question 3</h3><p>Find products priced higher than the average price in their category.</p><p>Try solving these problems using both correlated and non-correlated subqueries where possible.</p><h3>Key Takeaways</h3><p>✔ A Non-Correlated Subquery executes independently.</p><p>✔ A Correlated Subquery depends on the outer query.</p><p>✔ Non-Correlated Subqueries usually execute once.</p><p>✔ Correlated Subqueries execute once for each outer row.</p><p>✔ Understanding execution flow is more important than memorizing definitions.</p><h3>What’s Next?</h3><p>In the next article of the SQL Interview Series, we’ll learn <strong>EXISTS vs IN</strong>, one of the most frequently asked SQL interview topics, with practical examples, performance comparisons, and real-world use cases.</p><p>Happy Learning! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d794b8d0ff24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Subqueries Explained with Real Interview Examples | SQL Interview Series #2]]></title>
            <link>https://medium.com/@chikuv2205/sql-subqueries-explained-with-real-interview-examples-sql-interview-series-2-673b04dc020c?source=rss-b0c08ff5343d------2</link>
            <guid isPermaLink="false">https://medium.com/p/673b04dc020c</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Varsha Vishwakarma]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 10:10:10 GMT</pubDate>
            <atom:updated>2026-07-01T10:10:10.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1U8sdFMI-3wey_k3CE7jqw.png" /></figure><p>If SQL Joins are one of the most frequently asked interview topics, <strong>Subqueries</strong> are not far behind.</p><p>During SQL interviews, recruiters often test your ability to retrieve data using nested queries rather than relying solely on joins. Understanding subqueries can help you solve complex problems in a clean and efficient way.</p><p>In this article, we’ll learn what subqueries are, explore different types of subqueries, and solve real interview-style examples.</p><h3>What is a Subquery?</h3><p>A subquery is a query written inside another SQL query.</p><p>The inner query executes first, and its result is used by the outer query.</p><h3>Basic Syntax</h3><pre>SELECT column_name<br>FROM table_name<br>WHERE column_name =<br>(<br>    SELECT column_name<br>    FROM another_table<br>);</pre><p>Think of a subquery as a query that helps another query make a decision.</p><h3>Example 1: Find Employees Earning Above Average Salary</h3><h3>Employees Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*k5zdczva-ESxcvMf0EYH_w.png" /><figcaption>Table: Employees</figcaption></figure><h3>Query</h3><pre>SELECT EmployeeName, Salary<br>FROM Employees<br>WHERE Salary &gt;<br>(<br>    SELECT AVG(Salary)<br>    FROM Employees<br>);</pre><h3>Explanation</h3><p>First, the subquery calculates the average salary.</p><pre>SELECT AVG(Salary) FROM Employees;</pre><p>Average Salary = 55000</p><p>Then the outer query returns employees earning more than 55,000.</p><h3>Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*FpBY04Z7OupZVZdY4mrJkA.png" /><figcaption>Output</figcaption></figure><h3>Types of Subqueries</h3><h3>1. Single-Row Subquery</h3><p>Returns only one value.</p><p>Example:</p><pre>SELECT *<br>FROM Employees<br>WHERE Salary &gt;<br>(<br>    SELECT AVG(Salary)<br>    FROM Employees<br>);</pre><p>The subquery returns a single value.</p><h3>2. Multiple-Row Subquery</h3><p>Returns multiple rows.</p><p>Example:</p><pre>SELECT EmployeeName<br>FROM Employees<br>WHERE DepartmentID IN<br>(<br>    SELECT DepartmentID<br>    FROM Departments<br>    WHERE Location = &#39;Mumbai&#39;<br>);</pre><p>The IN operator is commonly used with multiple-row subqueries.</p><h3>Subquery with IN Operator</h3><p>Suppose we have two tables:</p><h3>Customers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*qESg-XFoIWm94SH9Rv9Ufg.png" /><figcaption>Table: Customers</figcaption></figure><h3>Orders</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*P9C-1GUTxVlHDJFUC1p7jQ.png" /><figcaption>Table: Orders</figcaption></figure><p>Find customers who have placed orders.</p><pre>SELECT CustomerName<br>FROM Customers<br>WHERE CustomerID IN<br>(<br>    SELECT CustomerID<br>    FROM Orders<br>);</pre><h3>Result</h3><p>Varsha</p><p>Rahul</p><h3>Correlated Subquery</h3><p>A correlated subquery depends on the outer query.</p><p>Unlike normal subqueries, it executes once for every row processed by the outer query.</p><h3>Example</h3><p>Find employees earning more than the average salary of their department.</p><pre>SELECT e.EmployeeName,<br>       e.Salary<br>FROM Employees e<br>WHERE e.Salary &gt;<br>(<br>    SELECT AVG(Salary)<br>    FROM Employees<br>    WHERE DepartmentID = e.DepartmentID<br>);</pre><p>This is one of the most popular SQL interview questions.</p><h3>Subquery vs JOIN</h3><p>A common interview question is:</p><p><strong>“Should I use a JOIN or a Subquery?”</strong></p><p>The answer depends on the problem.</p><p>Use a JOIN when:</p><ul><li>Combining data from multiple tables</li><li>Retrieving related information</li></ul><p>Use a Subquery when:</p><ul><li>You need an intermediate result</li><li>The logic becomes easier to understand</li></ul><p>In many cases, both approaches can produce the same result.</p><h3>Frequently Asked Interview Questions</h3><h3>1. What is a Subquery?</h3><p>A query nested inside another SQL query.</p><h3>2. Can a Subquery return multiple rows?</h3><p>Yes. Operators such as IN, ANY, and EXISTS are commonly used with multiple-row subqueries.</p><h3>3. What is a Correlated Subquery?</h3><p>A subquery that references columns from the outer query.</p><h3>4. Which is faster: JOIN or Subquery?</h3><p>There is no universal answer. Performance depends on the query structure, indexing, and database engine.</p><h3>Real-World Example</h3><p>Imagine you’re building a food delivery platform.</p><p>You need to find customers who have placed more orders than the average customer.</p><p>A subquery can first calculate the average number of orders and then compare each customer’s order count against that value.</p><p>This type of business logic appears frequently in analytics and reporting systems.</p><h3>Final Thoughts</h3><p>Subqueries are one of the most powerful tools in SQL. They help break complex problems into smaller, manageable steps and are frequently asked in technical interviews.</p><p>If you’re preparing for SQL interviews, make sure you understand:</p><ul><li>Single-row subqueries</li><li>Multiple-row subqueries</li><li>IN operator</li><li>Correlated subqueries</li><li>JOIN vs Subquery scenarios</li></ul><p>Mastering these concepts will make solving advanced SQL problems much easier.</p><p>In the next article of this SQL Interview Series, we’ll explore Correlated vs Non-Correlated Subqueries with practical examples and interview questions.</p><p>Happy Learning! ✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=673b04dc020c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Joins Explained with Real Examples | SQL Interview Series #1]]></title>
            <link>https://medium.com/@chikuv2205/sql-joins-explained-with-real-examples-sql-interview-series-1-c6a44ad78bad?source=rss-b0c08ff5343d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6a44ad78bad</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Varsha Vishwakarma]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 12:47:12 GMT</pubDate>
            <atom:updated>2026-06-24T12:47:12.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p939CHD8ZXT04pZn_WZZzw.png" /></figure><p>If you’re preparing for SQL interviews, there’s one topic you simply cannot afford to skip: <strong>Joins</strong>.</p><p>During my recent interview preparation, I noticed that almost every company asked at least one question related to joins. Sometimes it was a direct question like <em>“What’s the difference between INNER JOIN and LEFT JOIN?”</em> and other times it was hidden inside a business scenario.</p><p>In this article, we’ll understand SQL joins using simple examples that are commonly asked in interviews and used in real-world applications.</p><h3>Why Do We Need Joins?</h3><p>In real-world databases, data is usually spread across multiple tables rather than stored in a single table.</p><p>Let’s take an example of an e-commerce application.</p><h3>Customers Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*eRE7OOMCH1S3mzT4yK2D2g.png" /><figcaption>Table: Customers</figcaption></figure><h3>Orders Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*KWfFrk6ltjeA03kK3zcyjw.png" /><figcaption>Table: Orders</figcaption></figure><p>Now suppose we want to see the customer names along with their order amounts. Since the information exists in different tables, we need a JOIN.</p><h3>INNER JOIN</h3><p>An INNER JOIN returns only the records that have matching values in both tables.</p><h3>Query</h3><pre>SELECT<br>    c.CustomerName,<br>    o.Amount<br>FROM Customers c<br>INNER JOIN Orders o<br>ON c.CustomerID = o.CustomerID;</pre><h3>Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*2J6gsln24XyvNMgvQ1biQA.png" /><figcaption>Output</figcaption></figure><p>Only matching records are returned.</p><p>Think of INNER JOIN as the intersection between two tables.</p><h3>LEFT JOIN</h3><p>A LEFT JOIN returns all records from the left table and matching records from the right table.</p><p>Let’s add another customer who hasn’t placed an order yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*T1XQL7u-rGlQQ0M7zSqz0w.png" /><figcaption>New Record</figcaption></figure><h3>Query</h3><pre>SELECT<br>    c.CustomerName,<br>    o.Amount<br>FROM Customers c<br>LEFT JOIN Orders o<br>ON c.CustomerID = o.CustomerID;</pre><h3>Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*enSms5LJ0EwFbyW5gExXXw.png" /><figcaption>Output</figcaption></figure><p>Notice that customers without orders are still displayed. Their order amount appears as NULL.</p><h3>RIGHT JOIN</h3><p>A RIGHT JOIN works exactly opposite to a LEFT JOIN. It returns all records from the right table and matching records from the left table.</p><p>Although MySQL supports RIGHT JOIN, many developers prefer using LEFT JOIN because it is generally easier to read and maintain.</p><h3>FULL OUTER JOIN</h3><p>A FULL OUTER JOIN returns:</p><ul><li>All matching records</li><li>All records from the left table</li><li>All records from the right table</li></ul><p>MySQL does not directly support FULL OUTER JOIN, but it can be achieved using UNION.</p><h3>SELF JOIN</h3><p>A SELF JOIN occurs when a table is joined with itself.</p><p>One common example is an Employee table where each employee has a manager.</p><pre>SELECT<br>    e.EmployeeName,<br>    m.EmployeeName AS ManagerName<br>FROM Employees e<br>LEFT JOIN Employees m<br>ON e.ManagerID = m.EmployeeID;</pre><p>This is a very common SQL interview question.</p><h3>Frequently Asked Interview Questions</h3><h3>1. What is the difference between INNER JOIN and LEFT JOIN?</h3><ul><li>INNER JOIN returns only matching records.</li><li>LEFT JOIN returns all records from the left table and matching records from the right table.</li></ul><h3>2. Which JOIN is used most often in real projects?</h3><p>INNER JOIN and LEFT JOIN are by far the most commonly used joins in production systems.</p><h3>3. Can we join more than two tables?</h3><p>Absolutely.</p><p>A single query can join multiple tables depending on business requirements.</p><h3>4. How do joins affect performance?</h3><p>Joins on large datasets can be expensive. Creating indexes on the columns used in joins can significantly improve query performance.</p><h3>Real-World Example</h3><p>Imagine you’re building a food delivery application.</p><p>You may have separate tables for:</p><ul><li>Users</li><li>Orders</li><li>Restaurants</li><li>Payments</li></ul><p>To generate a report showing customer name, restaurant name, order amount, and payment status, you’ll need multiple joins.</p><p>This is exactly why joins are one of the most important concepts for backend developers, data analysts, and database engineers.</p><h3>Final Thoughts</h3><p>Learning joins is not about memorizing definitions. It’s about understanding how data is related across tables and how those relationships help answer business questions.</p><p>If you’re preparing for SQL interviews, focus on mastering:</p><ul><li>INNER JOIN</li><li>LEFT JOIN</li><li>SELF JOIN</li><li>Real-world business scenarios</li></ul><p>These concepts appear repeatedly in interviews and are used extensively in real applications.</p><p>In the next article of this SQL Interview Series, we’ll explore SQL Subqueries with practical examples and interview questions.</p><p>Happy Learning! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6a44ad78bad" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>