<?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 KoshyK on Medium]]></title>
        <description><![CDATA[Stories by KoshyK on Medium]]></description>
        <link>https://medium.com/@kamalikoshy97?source=rss-140ac3fd2264------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Y2y5Q0wxjAMieqBP.jpg</url>
            <title>Stories by KoshyK on Medium</title>
            <link>https://medium.com/@kamalikoshy97?source=rss-140ac3fd2264------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:53:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kamalikoshy97/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[Crack the LeetCode SQL 50 Series -Problem 18]]></title>
            <link>https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-18-2abd353d9076?source=rss-140ac3fd2264------2</link>
            <guid isPermaLink="false">https://medium.com/p/2abd353d9076</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <dc:creator><![CDATA[KoshyK]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 13:38:43 GMT</pubDate>
            <atom:updated>2025-09-28T13:38:43.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDculZfJJKV-pPKzkeGk_A.png" /><figcaption>LeetCode SQL 50 Series (Image generated using DALL·E via ChatGPT (OpenAI))</figcaption></figure><p>Hey there! 👋</p><h4>Short-tro</h4><p>Welcome back to the LeetCode SQL50 Series — the LeetCode SQL50 challenge collection that covers important SQL concepts you’ll come across in real-world applications and interviews. In this series, I’ll be sharing my solutions, thought process, and a bit of commentary along the way — like a learning journal.</p><p>This series is great for beginners, but it also serves as a solid refresher for anyone who wants to brush up on writing clean and efficient SQL queries.</p><h4>Problem</h4><p>In the last article (Problem 17), we revisited the <strong>GROUP BY</strong> clause and the <strong>LEFT JOIN</strong>.</p><p>If you attempted <strong>Problem 18</strong> on your own, that’s great practice! If not, no worries, let’s work through it together now.</p><p><a href="https://leetcode.com/problems/percentage-of-users-attended-a-contest/">1633. Percentage of Users Attended a Contest</a> (Easy)</p><pre>Table: Users<br><br>+-------------+---------+<br>| Column Name | Type    |<br>+-------------+---------+<br>| user_id     | int     |<br>| user_name   | varchar |<br>+-------------+---------+<br>user_id is the primary key (column with unique values) for this table.<br>Each row of this table contains the name and the id of a user.<br><br>Table: Register<br><br>+-------------+---------+<br>| Column Name | Type    |<br>+-------------+---------+<br>| contest_id  | int     |<br>| user_id     | int     |<br>+-------------+---------+<br>(contest_id, user_id) is the primary key (combination of columns with unique values) for this table.<br>Each row of this table contains the id of a user and the contest they registered into.<br><br>Write a solution to find the percentage of the users registered in each contest rounded to two decimals.<br><br>Return the result table ordered by percentage in descending order. In case of a tie, order it by contest_id in ascending order.<br><br>The result format is in the following example.<br><br> <br><br>Example 1:<br><br>Input: <br>Users table:<br>+---------+-----------+<br>| user_id | user_name |<br>+---------+-----------+<br>| 6       | Alice     |<br>| 2       | Bob       |<br>| 7       | Alex      |<br>+---------+-----------+<br>Register table:<br>+------------+---------+<br>| contest_id | user_id |<br>+------------+---------+<br>| 215        | 6       |<br>| 209        | 2       |<br>| 208        | 2       |<br>| 210        | 6       |<br>| 208        | 6       |<br>| 209        | 7       |<br>| 209        | 6       |<br>| 215        | 7       |<br>| 208        | 7       |<br>| 210        | 2       |<br>| 207        | 2       |<br>| 210        | 7       |<br>+------------+---------+<br>Output: <br>+------------+------------+<br>| contest_id | percentage |<br>+------------+------------+<br>| 208        | 100.0      |<br>| 209        | 100.0      |<br>| 210        | 100.0      |<br>| 215        | 66.67      |<br>| 207        | 33.33      |<br>+------------+------------+<br>Explanation: <br>All the users registered in contests 208, 209, and 210. The percentage is 100% and we sort them in the answer table by contest_id in ascending order.<br>Alice and Alex registered in contest 215 and the percentage is ((2/3) * 100) = 66.67%<br>Bob registered in contest 207 and the percentage is ((1/3) * 100) = 33.33%</pre><p>The problem statement involves <strong>two tables,</strong></p><ol><li><strong>Users</strong> table, where user_id is the<em> primary key</em>.</li><li><strong>Register</strong> table, where (contest_id, user_id) forms the <em>composite primary key</em>.</li></ol><p>The task is to,</p><ul><li>Calculate the <strong>percentage of users registered</strong> in each contest</li><li><strong>Round</strong> the percentage to 2 decimal places.</li><li><strong>Sort</strong> the results by percentage in descending order, and in case of a tie, by contest_id in ascending order.</li></ul><p>Let’s break this down into steps,</p><ul><li>Find the total number of users registered from <em>Users </em>table.</li><li>Find the number of users registered in each contest from <em>Register</em> table.</li><li>Calculate the percentage of users per contest using the formula,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*S9_44e4NTiZ6nvfy-tZzvQ.png" /><figcaption>Formula for percentage</figcaption></figure><ul><li>Round the percentage to 2 decimal places.</li><li>Sort the results by percentage (descending), and by contest_id (ascending) in case of a tie.</li></ul><p>Before we solve this problem, let’s learn about <strong><em>COUNT()</em></strong></p><h4>What is COUNT() in SQL?</h4><p><strong>COUNT()</strong> is a built-in aggregate function used to return the number of rows that match a specified condition.</p><p>Common use cases of COUNT() include,</p><ul><li>Count all rows in a table - <strong>COUNT(*)</strong></li><li>Count non-null values in a column - <strong>COUNT(column_name)</strong></li><li>Count distinct values in a column - <strong>COUNT(DISTINCT column_name)</strong></li></ul><p>Now, getting back to the problem we have,</p><h4><strong>Step-01: Calculate total number of users registered - COUNT()</strong></h4><pre>SELECT COUNT(*) FROM Users; </pre><p>Output</p><pre>| COUNT(*) |<br>| -------- |<br>| 3        |</pre><h4><strong>Step-02: Calculate number of users registered in each contest - GROUP BY clause</strong></h4><pre>SELECT contest_id, COUNT(user_id) <br><br>FROM Register <br><br>GROUP BY contest_id; </pre><p>Output</p><pre>| contest_id | COUNT(user_id) |<br>| ---------- | -------------- |<br>| 215        | 2              |<br>| 209        | 3              |<br>| 208        | 3              |<br>| 210        | 3              |<br>| 207        | 1              |</pre><h4><strong>Step-03: Calculate the percentage of users per contest using the formula</strong></h4><p>Using the result of <strong>Step-01</strong> as a subquery in <strong>Step-02</strong>, we can calculate the percentage of users registered in each contest.</p><pre>SELECT contest_id, (COUNT(user_id)/(SELECT COUNT(*) FROM Users AS registered_users))*100 AS percentage <br><br>FROM Register <br><br>GROUP BY contest_id; </pre><p>Output</p><pre>| contest_id | percentage |<br>| ---------- | ---------- |<br>| 215        | 66.6667    |<br>| 209        | 100        |<br>| 208        | 100        |<br>| 210        | 100        |<br>| 207        | 33.3333    |</pre><h4>Step-04 &amp; Step-05: Round and sort the results - ROUND(), ORDER BY clause</h4><pre>SELECT contest_id, ROUND((COUNT(user_id)/(SELECT COUNT(*) FROM Users AS registered_users))*100, 2) AS percentage <br><br>FROM Register <br><br>GROUP BY contest_id <br><br>ORDER BY percentage DESC, contest_id; </pre><p>Output</p><pre>| contest_id | percentage |<br>| ---------- | ---------- |<br>| 208        | 100        |<br>| 209        | 100        |<br>| 210        | 100        |<br>| 215        | 66.67      |<br>| 207        | 33.33      |</pre><p>All test cases passed succesfully.</p><h4>Conclusion</h4><p>That’s it for <strong>Problem 18 </strong>of the <strong>LeetCode SQL50 Series</strong>!</p><p>In this article, we explored the built-in aggregate function COUNT() and revisited GROUP BY clause and ROUND() clause.</p><p>As we continue through the series, we’ll solve more complex problem with <strong>aggregations</strong>, and <strong>sub-queries</strong>, gradually building our SQL muscle one problem at a time.</p><p>If you’re following along, I encourage you to try solving the next problem on your own before reading the next post — it’s a great way to reinforce what you’re learning.</p><p>Thanks for reading, and stay tuned for <strong>Problem 19!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2abd353d9076" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crack the LeetCode SQL 50 Series -Problem 17]]></title>
            <link>https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-17-e7bf591bcc93?source=rss-140ac3fd2264------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7bf591bcc93</guid>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[KoshyK]]></dc:creator>
            <pubDate>Tue, 23 Sep 2025 11:31:38 GMT</pubDate>
            <atom:updated>2025-09-23T11:31:38.309Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDculZfJJKV-pPKzkeGk_A.png" /><figcaption>LeetCode SQL 50 Series (Image generated using DALL·E via ChatGPT (OpenAI))</figcaption></figure><p>Hey there! 👋</p><h4>Short-tro</h4><p>Welcome back to the LeetCode SQL50 Series — the LeetCode SQL50 challenge collection that covers important SQL concepts you’ll come across in real-world applications and interviews. In this series, I’ll be sharing my solutions, thought process, and a bit of commentary along the way — like a learning journal.</p><p>This series is great for beginners, but it also serves as a solid refresher for anyone who wants to brush up on writing clean and efficient SQL queries.</p><h4>Problem</h4><p>In the previous article (Problem 16), we explored tables without primary keys.</p><p>I hope you had a chance to give Problem 17 a try. If not, let’s solve it now!</p><p><a href="https://leetcode.com/problems/project-employees-i/">1075. Project Employees I</a> (Easy)</p><pre>Table: Project<br><br>+-------------+---------+<br>| Column Name | Type    |<br>+-------------+---------+<br>| project_id  | int     |<br>| employee_id | int     |<br>+-------------+---------+<br>(project_id, employee_id) is the primary key of this table.<br>employee_id is a foreign key to Employee table.<br>Each row of this table indicates that the employee with employee_id is working on the project with project_id.<br><br>Table: Employee<br><br>+------------------+---------+<br>| Column Name      | Type    |<br>+------------------+---------+<br>| employee_id      | int     |<br>| name             | varchar |<br>| experience_years | int     |<br>+------------------+---------+<br>employee_id is the primary key of this table. It is guaranteed that experience_years is not NULL.<br>Each row of this table contains information about one employee.<br><br>Write an SQL query that reports the average experience years of all the employees for each project, rounded to 2 digits.<br><br>Return the result table in any order.<br><br>The query result format is in the following example.<br><br> <br><br>Example 1:<br><br>Input: <br>Project table:<br>+-------------+-------------+<br>| project_id  | employee_id |<br>+-------------+-------------+<br>| 1           | 1           |<br>| 1           | 2           |<br>| 1           | 3           |<br>| 2           | 1           |<br>| 2           | 4           |<br>+-------------+-------------+<br>Employee table:<br>+-------------+--------+------------------+<br>| employee_id | name   | experience_years |<br>+-------------+--------+------------------+<br>| 1           | Khaled | 3                |<br>| 2           | Ali    | 2                |<br>| 3           | John   | 1                |<br>| 4           | Doe    | 2                |<br>+-------------+--------+------------------+<br>Output: <br>+-------------+---------------+<br>| project_id  | average_years |<br>+-------------+---------------+<br>| 1           | 2.00          |<br>| 2           | 2.50          |<br>+-------------+---------------+<br>Explanation: The average experience years for the first project is (3 + 2 + 1) / 3 = 2.00 and for the second project is (3 + 2) / 2 = 2.50</pre><p>The problem involves two tables.</p><ul><li>The table <strong>Project</strong> contains a <strong><em>composite primary key</em></strong> (project_id, employee_id), with employee_id also serving as a <strong><em>foreign key</em></strong> referencing the Employee table.</li><li>The table <strong>Employee</strong> Uses employee_id as its <strong><em>primary key</em></strong>.</li></ul><p>The task is to calculate the <strong>average years of experience</strong> (<em>average_years</em>) of all employees assigned to each project.</p><p>We can approach the solution step by step,</p><ol><li>Create a consolidated dataset by joining the <em>Project</em> table (project_id, employee_id) with the corresponding <em>experience_years</em> from the <em>Employee</em> table.</li><li>For each project_id, calculate the average experience of all its employees.</li></ol><h4>Step-01: Create a consolidated dataset - LEFT JOIN</h4><pre>SELECT *<br>FROM Project<br>LEFT JOIN Employee<br>ON Project.employee_id = Employee.employee_id;</pre><p>Output</p><pre>| project_id | employee_id | employee_id | name   | experience_years |<br>| ---------- | ----------- | ----------- | ------ | ---------------- |<br>| 1          | 1           | 1           | Khaled | 3                |<br>| 1          | 2           | 2           | Ali    | 2                |<br>| 1          | 3           | 3           | John   | 1                |<br>| 2          | 1           | 1           | Khaled | 3                |<br>| 2          | 4           | 4           | Doe    | 2                |</pre><h4>Step-02: Calculate the average years of experience - GROUP BY clause, AVG()</h4><pre>SELECT project_id, AVG(experience_years) AS average_years<br>FROM Project<br>LEFT JOIN Employee<br>ON Project.employee_id = Employee.employee_id<br>GROUP BY project_id;</pre><p>Output</p><pre>| project_id | average_years |<br>| ---------- | ------------- |<br>| 1          | 2             |<br>| 2          | 2.5           |</pre><p>All test cases passed successfully.</p><h4>Conclusion</h4><p>That’s it for <strong>Problem 17 </strong>of the <strong>LeetCode SQL50 Series</strong>!</p><p>In this article, we revisited GROUP BY clause and the built-in function AVG().</p><p>As we continue through the series, we’ll solve more complex problem with <strong>aggregations</strong>, and <strong>sub-queries</strong>, gradually building our SQL muscle one problem at a time.</p><p>If you’re following along, I encourage you to try solving the next problem on your own before reading the next post — it’s a great way to reinforce what you’re learning.</p><p>Thanks for reading, and stay tuned for <strong>Problem 18!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7bf591bcc93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crack the LeetCode SQL 50 Series - Problem 16]]></title>
            <link>https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-16-1c5603f41ea1?source=rss-140ac3fd2264------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c5603f41ea1</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[KoshyK]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 07:08:46 GMT</pubDate>
            <atom:updated>2025-09-19T07:08:46.499Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crack the LeetCode SQL 50 Series -Problem 16</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDculZfJJKV-pPKzkeGk_A.png" /><figcaption>LeetCode SQL 50 Series (Image generated using DALL·E via ChatGPT (OpenAI))</figcaption></figure><p>Hey there! 👋</p><h4>Short-tro</h4><p>Welcome back to the LeetCode SQL50 Series — the LeetCode SQL50 challenge collection that covers important SQL concepts you’ll come across in real-world applications and interviews. In this series, I’ll be sharing my solutions, thought process, and a bit of commentary along the way — like a learning journal.</p><p>This series is great for beginners, but it also serves as a solid refresher for anyone who wants to brush up on writing clean and efficient SQL queries.</p><h4>Problem</h4><p>In the last article (Problem 15), we revisited the WHERE clause and solved a simple query using the built-in function MOD().</p><p>If you’ve already practiced <strong>Problem 16</strong> on your own, great job! <br>If not, no worries, let’s work through it together now.</p><p><a href="https://leetcode.com/problems/average-selling-price/">1251. Average Selling Price</a> (Easy)</p><pre>Table: Prices<br><br>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| product_id    | int     |<br>| start_date    | date    |<br>| end_date      | date    |<br>| price         | int     |<br>+---------------+---------+<br>(product_id, start_date, end_date) is the primary key (combination of columns with unique values) for this table.<br>Each row of this table indicates the price of the product_id in the period from start_date to end_date.<br>For each product_id there will be no two overlapping periods. That means there will be no two intersecting periods for the same product_id.<br><br>Table: UnitsSold<br><br>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| product_id    | int     |<br>| purchase_date | date    |<br>| units         | int     |<br>+---------------+---------+<br>This table may contain duplicate rows.<br>Each row of this table indicates the date, units, and product_id of each product sold.<br><br>Write a solution to find the average selling price for each product. average_price should be rounded to 2 decimal places. If a product does not have any sold units, its average selling price is assumed to be 0.<br><br>Return the result table in any order.<br><br>The result format is in the following example.<br><br> <br><br>Example 1:<br><br>Input: <br>Prices table:<br>+------------+------------+------------+--------+<br>| product_id | start_date | end_date   | price  |<br>+------------+------------+------------+--------+<br>| 1          | 2019-02-17 | 2019-02-28 | 5      |<br>| 1          | 2019-03-01 | 2019-03-22 | 20     |<br>| 2          | 2019-02-01 | 2019-02-20 | 15     |<br>| 2          | 2019-02-21 | 2019-03-31 | 30     |<br>+------------+------------+------------+--------+<br>UnitsSold table:<br>+------------+---------------+-------+<br>| product_id | purchase_date | units |<br>+------------+---------------+-------+<br>| 1          | 2019-02-25    | 100   |<br>| 1          | 2019-03-01    | 15    |<br>| 2          | 2019-02-10    | 200   |<br>| 2          | 2019-03-22    | 30    |<br>+------------+---------------+-------+<br>Output: <br>+------------+---------------+<br>| product_id | average_price |<br>+------------+---------------+<br>| 1          | 6.96          |<br>| 2          | 16.96         |<br>+------------+---------------+<br>Explanation: <br>Average selling price = Total Price of Product / Number of products sold.<br>Average selling price for product 1 = ((100 * 5) + (15 * 20)) / 115 = 6.96<br>Average selling price for product 2 = ((200 * 15) + (30 * 30)) / 230 = 16.96</pre><p>The problem has 2 tables.</p><ul><li>The table <strong>Prices</strong> has the <strong><em>composite primary key</em></strong> (product_id, start_date, end_date).</li><li>The table <strong>UnitsSold</strong> does <strong><em>no</em></strong>t have a <strong><em>primary key</em></strong>.</li></ul><p>This raises a question.</p><h4><strong>Can we have tables without primary key in relational databases?</strong></h4><p>Yes, relational databases <strong>allow tables without primary keys</strong>. A primary key is not mandatory at the schema level.</p><p>Such tables can store duplicate rows since no uniqueness constraint is enforced.</p><h4><strong>Why would we need tables without primary keys?</strong></h4><p>There are some real-world applications which requires this approach,</p><ol><li><strong>Transaction logs -</strong> Every event is recorded, even if it looks identical. <br>e.g., two customers buying the same product at the same time for the same quantity.</li><li><strong>Fact tables in Data Warehouses -</strong> Keeps real-world duplicate-looking events for analytics. e.g., every sale, click, view, etc,. <br>Removing duplicates would distort reality resulting in incorrect aggregation values (SUM, COUNT, AVG, etc,)</li><li><strong>Staging/temporary tables -</strong> Stores raw data as-is before cleaning or transformation. e.g., A staging table receiving daily logs from multiple sources might contain duplicates due to system retries or upstream errors. <br>Enforcing a primary key here would reject valid raw data before cleaning.</li></ol><h4><strong>What happens if we enforce a primary key in UnitsSold table here?</strong></h4><p>The database will reject duplicate rows.</p><p>e.g.,<em> In UnitsSold, if two identical sales occur (same product_id, purchase_date, and units), the second insert will fail.</em></p><p>This could incorrectly block valid data where two independent transactions look the same.</p><h4><strong>What is the alternative approach?</strong></h4><p><strong><em>Surrogate keys</em></strong>, A new, artificial column like an auto-incrementing integer can be added to serve as a unique identifier, even if it’s not formally declared as the primary key.</p><p>This strikes a balance between uniqueness at the row level and flexibility for real-world duplicate-looking events.</p><p>Now, getting back to the problem at hand.</p><p>The problem requires us to,</p><ul><li>Find the <strong>average selling price</strong> for each product.</li><li><strong>Round</strong> the result to 2 decimal places.</li></ul><p>Let’s form the solution in steps (Remember<strong><em>, “divide and conquer”</em></strong>).</p><ol><li><strong>Map units sold to price ranges -</strong> For each product_id, match every purchase date from the <strong>UnitsSold</strong> table with the correct date interval (start_date → end_date) in the <strong>Prices</strong> table.</li><li>Calculate the average selling price - This can be calculated using the formula,</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*ourmXba16o027QwDHY8fxQ.png" /><figcaption>Formula for average_price</figcaption></figure><h4>Step-01: <strong>Map units sold to price ranges - LEFT JOIN</strong></h4><p>To correctly map units sold to their corresponding price ranges, we apply a <strong>LEFT JOIN</strong> with the following conditions,</p><ul><li>The product_id in <strong>Prices</strong> must match the product_id in <strong>UnitsSold</strong>.</li><li>The purchase_date in <strong>UnitsSold</strong> must fall within the date range defined by start_date and end_date in <strong>Prices</strong>.</li></ul><pre>SELECT * <br>FROM Prices <br>LEFT JOIN UnitsSold <br>ON Prices.product_id = UnitsSold.product_id AND <br>(UnitsSold.purchase_date BETWEEN Prices.start_date AND Prices.end_date); </pre><p>Output</p><pre>| product_id | start_date | end_date   | price | product_id | purchase_date | units |<br>| ---------- | ---------- | ---------- | ----- | ---------- | ------------- | ----- |<br>| 1          | 2019-02-17 | 2019-02-28 | 5     | 1          | 2019-02-25    | 100   |<br>| 1          | 2019-03-01 | 2019-03-22 | 20    | 1          | 2019-03-01    | 15    |<br>| 2          | 2019-02-01 | 2019-02-20 | 15    | 2          | 2019-02-10    | 200   |<br>| 2          | 2019-02-21 | 2019-03-31 | 30    | 2          | 2019-03-22    | 30    |</pre><h4>Step-02: Calculate the average selling price — GROUP BY clause</h4><p>From the Step-01 result,</p><ol><li>Calculate the average_price for each product_id using the GROUP BY clause.</li><li>Round the calculated average_price to 2 decimal places using the built-in function ROUND().</li></ol><pre>SELECT Prices.product_id, ROUND((SUM(price*units)/SUM(units)), 2) AS average_price<br>FROM Prices <br>LEFT JOIN UnitsSold <br>ON Prices.product_id = UnitsSold.product_id AND <br>(UnitsSold.purchase_date BETWEEN Prices.start_date AND Prices.end_date)<br>GROUP BY Prices.product_id; </pre><p>Output</p><pre>| product_id | average_price |<br>| ---------- | ------------- |<br>| 1          | 6.96          |<br>| 2          | 16.96         |</pre><p>All test cases passed successfully.</p><blockquote>🎤 Now, please try answering,<br>1) What is <strong>aliasing</strong> in SQL, and why is it useful? <br>(Note: We have already covered this question in a <a href="https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-04-9e654e4e2b2a">previous article</a>)<br>2) What rules must be followed when using the GROUP BY clause?<br>(Note: We have already covered this question in a <a href="https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-08-f332f31cdf4a">previous article</a>) <br>3) In Step-01, we assumed <strong>each product_id and date range</strong> in the Prices table <strong>corresponds to only one purchase_date in UnitsSold</strong> (All the test cases are passing with this assumption). <br>How should the query be adapted if <strong>multiple purchase_date entries</strong> exist <strong>for the same product_id</strong> <strong>within a given date range</strong>?</blockquote><h4>Conclusion</h4><p>That’s it for <strong>Problem 16 </strong>of the <strong>LeetCode SQL50 Series</strong>!</p><p>In this article, we revisited WHERE clause, GROUP BY clause and the built-in function ROUND(). We also explored the fact that not all relational database tables necessarily have primary keys.</p><p>As we continue through the series, we’ll solve more complex problem with <strong>aggregations</strong>, and <strong>sub-queries</strong>, gradually building our SQL muscle one problem at a time.</p><p>If you’re following along, I encourage you to try solving the next problem on your own before reading the next post — it’s a great way to reinforce what you’re learning.</p><p>Thanks for reading, and stay tuned for <strong>Problem 17</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c5603f41ea1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crack the LeetCode SQL 50 Series -Problem 15]]></title>
            <link>https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-15-63eb30092032?source=rss-140ac3fd2264------2</link>
            <guid isPermaLink="false">https://medium.com/p/63eb30092032</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[KoshyK]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 13:51:26 GMT</pubDate>
            <atom:updated>2025-09-16T13:51:26.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDculZfJJKV-pPKzkeGk_A.png" /><figcaption>LeetCode SQL 50 Series (Image generated using DALL·E via ChatGPT (OpenAI))</figcaption></figure><p>Hey there! 👋</p><h4>Short-tro</h4><p>Welcome back to the LeetCode SQL50 Series — the LeetCode SQL50 challenge collection that covers important SQL concepts you’ll come across in real-world applications and interviews. In this series, I’ll be sharing my solutions, thought process, and a bit of commentary along the way — like a learning journal.</p><p>This series is great for beginners, but it also serves as a solid refresher for anyone who wants to brush up on writing clean and efficient SQL queries.</p><h4>Problem</h4><p>In the previous article (Problem 14), we learnt about CASE expression and its use cases. We also explored built-in functions, ROUND() and IFNULL()</p><p>I hope you had a chance to try <strong>Problem 15</strong> on your own. If not, no worries, let’s solve it together!</p><p><a href="https://leetcode.com/problems/not-boring-movies/">620. Not Boring Movies</a> (Easy)</p><pre>Table: Cinema<br><br>+----------------+----------+<br>| Column Name    | Type     |<br>+----------------+----------+<br>| id             | int      |<br>| movie          | varchar  |<br>| description    | varchar  |<br>| rating         | float    |<br>+----------------+----------+<br>id is the primary key (column with unique values) for this table.<br>Each row contains information about the name of a movie, its genre, and its rating.<br>rating is a 2 decimal places float in the range [0, 10]<br><br>Write a solution to report the movies with an odd-numbered ID and a description that is not &quot;boring&quot;.<br><br>Return the result table ordered by rating in descending order.<br><br>The result format is in the following example.<br><br> <br><br>Example 1:<br><br>Input: <br>Cinema table:<br>+----+------------+-------------+--------+<br>| id | movie      | description | rating |<br>+----+------------+-------------+--------+<br>| 1  | War        | great 3D    | 8.9    |<br>| 2  | Science    | fiction     | 8.5    |<br>| 3  | irish      | boring      | 6.2    |<br>| 4  | Ice song   | Fantacy     | 8.6    |<br>| 5  | House card | Interesting | 9.1    |<br>+----+------------+-------------+--------+<br>Output: <br>+----+------------+-------------+--------+<br>| id | movie      | description | rating |<br>+----+------------+-------------+--------+<br>| 5  | House card | Interesting | 9.1    |<br>| 1  | War        | great 3D    | 8.9    |<br>+----+------------+-------------+--------+<br>Explanation: <br>We have three movies with odd-numbered IDs: 1, 3, and 5. The movie with ID = 3 is boring so we do not include it in the answer.</pre><p>The problem involves a single table, <strong>Cinema</strong>, where <em>id</em> serves as the <strong>primary key</strong>.</p><p>The task requires us to,</p><ol><li>Filter rows where id is an odd number.</li><li>Exclude rows where description equals <em>“</em>boring<em>”</em>.</li><li>Sort the remaining results in descending order based on the rating column.</li></ol><p>Let’s form the solution using these simple steps.</p><h4>Step-01 &amp; Step-02: Filtering rows matching conditions — WHERE clause</h4><p>To filter the rows where id is an odd number, we could use MOD(),<strong> </strong>a built-in mathematical function used to return the remainder of a division operation.</p><pre>SELECT *<br>FROM Cinema<br>WHERE MOD(id, 2)=1 AND description!=&#39;boring&#39;;</pre><p>Output</p><pre>| id | movie      | description | rating |<br>| -- | ---------- | ----------- | ------ |<br>| 1  | War        | great 3D    | 8.9    |<br>| 5  | House card | Interesting | 9.1    |</pre><h4>Step-03: Sort the results in descending order — ORDER BY clause</h4><pre>SELECT *<br>FROM Cinema<br>WHERE MOD(id, 2)=1 AND description!=&#39;boring&#39;<br>ORDER BY rating DESC;</pre><p>Output</p><pre>| id | movie      | description | rating |<br>| -- | ---------- | ----------- | ------ |<br>| 5  | House card | Interesting | 9.1    |<br>| 1  | War        | great 3D    | 8.9    |</pre><p>All test cases passed successfully.</p><blockquote><strong>Note - By default, the results of a query are unordered</strong>. At times, they may appear to be ordered by the primary key or insertion order, but this behavior is not guaranteed and should not be relied upon. To ensure consistent ordering, always use an ORDER BY clause.</blockquote><h4>Conclusion</h4><p>That’s it for <strong>Problem 15 </strong>of the <strong>LeetCode SQL50 Series</strong>!</p><p>In this article, we revisited WHERE clause, ORDER BY clause and explored the built-in function MOD().</p><p>As we continue through the series, we’ll solve more complex problem with <strong>aggregations</strong>, and <strong>sub-queries</strong>, gradually building our SQL muscle one problem at a time.</p><p>If you’re following along, I encourage you to try solving the next problem on your own before reading the next post — it’s a great way to reinforce what you’re learning.</p><p>Thanks for reading, and stay tuned for <strong>Problem 16</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63eb30092032" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crack the LeetCode SQL 50 Series -Problem 14]]></title>
            <link>https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-14-c77115d4a486?source=rss-140ac3fd2264------2</link>
            <guid isPermaLink="false">https://medium.com/p/c77115d4a486</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[KoshyK]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 14:49:31 GMT</pubDate>
            <atom:updated>2025-09-15T14:51:46.774Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDculZfJJKV-pPKzkeGk_A.png" /><figcaption>LeetCode SQL 50 Series (Image generated using DALL·E via ChatGPT (OpenAI))</figcaption></figure><p>Hey there! 👋</p><h4>Short-tro</h4><p>Welcome back to the LeetCode SQL50 Series — the LeetCode SQL50 challenge collection that covers important SQL concepts you’ll come across in real-world applications and interviews. In this series, I’ll be sharing my solutions, thought process, and a bit of commentary along the way — like a learning journal.</p><p>This series is great for beginners, but it also serves as a solid refresher for anyone who wants to brush up on writing clean and efficient SQL queries.</p><h4>Problem</h4><p>In the previous article, we came across HAVING clause and explored its properties.</p><p>If you had the chance to solve<strong> Problem 14</strong>, that’s great. If not don’t worry, let’s check it out, now!</p><p><a href="https://leetcode.com/problems/confirmation-rate/">1934. Confirmation Rate</a> (Medium)</p><pre>Table: Signups<br><br>+----------------+----------+<br>| Column Name    | Type     |<br>+----------------+----------+<br>| user_id        | int      |<br>| time_stamp     | datetime |<br>+----------------+----------+<br>user_id is the column of unique values for this table.<br>Each row contains information about the signup time for the user with ID user_id.<br><br>Table: Confirmations<br><br>+----------------+----------+<br>| Column Name    | Type     |<br>+----------------+----------+<br>| user_id        | int      |<br>| time_stamp     | datetime |<br>| action         | ENUM     |<br>+----------------+----------+<br>(user_id, time_stamp) is the primary key (combination of columns with unique values) for this table.<br>user_id is a foreign key (reference column) to the Signups table.<br>action is an ENUM (category) of the type (&#39;confirmed&#39;, &#39;timeout&#39;)<br>Each row of this table indicates that the user with ID user_id requested a confirmation message at time_stamp and that confirmation message was either confirmed (&#39;confirmed&#39;) or expired without confirming (&#39;timeout&#39;).<br><br>The confirmation rate of a user is the number of &#39;confirmed&#39; messages divided by the total number of requested confirmation messages. The confirmation rate of a user that did not request any confirmation messages is 0. Round the confirmation rate to two decimal places.<br><br>Write a solution to find the confirmation rate of each user.<br><br>Return the result table in any order.<br><br>The result format is in the following example.<br><br> <br><br>Example 1:<br><br>Input: <br>Signups table:<br>+---------+---------------------+<br>| user_id | time_stamp          |<br>+---------+---------------------+<br>| 3       | 2020-03-21 10:16:13 |<br>| 7       | 2020-01-04 13:57:59 |<br>| 2       | 2020-07-29 23:09:44 |<br>| 6       | 2020-12-09 10:39:37 |<br>+---------+---------------------+<br>Confirmations table:<br>+---------+---------------------+-----------+<br>| user_id | time_stamp          | action    |<br>+---------+---------------------+-----------+<br>| 3       | 2021-01-06 03:30:46 | timeout   |<br>| 3       | 2021-07-14 14:00:00 | timeout   |<br>| 7       | 2021-06-12 11:57:29 | confirmed |<br>| 7       | 2021-06-13 12:58:28 | confirmed |<br>| 7       | 2021-06-14 13:59:27 | confirmed |<br>| 2       | 2021-01-22 00:00:00 | confirmed |<br>| 2       | 2021-02-28 23:59:59 | timeout   |<br>+---------+---------------------+-----------+<br>Output: <br>+---------+-------------------+<br>| user_id | confirmation_rate |<br>+---------+-------------------+<br>| 6       | 0.00              |<br>| 3       | 0.00              |<br>| 7       | 1.00              |<br>| 2       | 0.50              |<br>+---------+-------------------+<br>Explanation: <br>User 6 did not request any confirmation messages. The confirmation rate is 0.<br>User 3 made 2 requests and both timed out. The confirmation rate is 0.<br>User 7 made 3 requests and all were confirmed. The confirmation rate is 1.<br>User 2 made 2 requests where one was confirmed and the other timed out. The confirmation rate is 1 / 2 = 0.5.</pre><p>The problem statement involves two tables,</p><ul><li><strong>Signups</strong> table, with user_id as the primary key.</li><li><strong>Confirmations</strong> table with (user_id, time_stamp) as the composite primary key.</li></ul><p>The task is to calculate the <strong>confirmation rate</strong> for each user in the <strong>Signups</strong> table.</p><p>The confirmation rate of a user is defined as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQBZwT1Y77DlYW8zw_RtoQ.png" /><figcaption>Formula for confirmation_rate</figcaption></figure><p>We can approach the solution in the following steps,</p><ol><li><strong>Pivot the Confirmations table</strong> to separate “timeout” and “confirmed” requests.</li><li><strong>Calculate the confirmation rate</strong> using the derived timeout and confirmed counts.</li><li><strong>Assign the confirmation rate</strong> back to each user in the Signups table.</li></ol><p>Before we proceed on to the first step, let’s learn about CASE expressions in SQL.</p><h4>What is CASE expression in SQL?</h4><p>The <strong>CASE expression</strong> in SQL is a conditional expression that returns a value based on a set of conditions.</p><p>It is SQL’s equivalent of <strong>if-then-else logic</strong> inside queries.</p><p>It always evaluates to a <strong>single value </strong>and it can be used anywhere an expression is allowed: SELECT, WHERE, ORDER BY, GROUP BY, etc.</p><p><strong>Syntax for CASE expression is given by</strong>,</p><pre>CASE<br>WHEN condition1 THEN result1<br>WHEN condition2 THEN result2<br>…<br>ELSE default_result<br>END</pre><h4>So, where should we be using CASE expression?</h4><p>The most common use cases where we could use <strong>CASE expressions</strong> in SQL include,</p><ul><li><strong>Creating derived columns -</strong> Categorize or flag data based on conditions to generate new columns.</li><li><strong>Pivoting data (turning rows into columns) -</strong> Transform row values into separate columns, often with aggregation, similar to a pivot table.</li><li><strong>Conditional aggregations -</strong> Apply conditions inside aggregate functions (like SUM or COUNT) to calculate values selectively.</li><li><strong>Custom sorting</strong> - Control the order of results beyond the default alphabetical or numeric rules.</li><li><strong>Conditional filtering -</strong> Implement complex filtering logic within a single WHERE expression.</li></ul><p>Now that we have a grasp on CASE expressions, let’s return to the problem at hand.</p><h4><strong>Step-01: Pivot the Confirmations table to separate “timeout” and “confirmed” requests - CASE expression</strong></h4><p>The first step is to use the CASE expression to pivot row values of the action column into two separate columns, timeout and confirmed.</p><pre>SELECT user_id, <br>(CASE WHEN action = &#39;timeout&#39; THEN &#39;timeout&#39; END) AS &#39;timeout&#39;, <br>(CASE WHEN action = &#39;confirmed&#39; THEN &#39;confirmed&#39; END) AS &#39;confirmed&#39; <br>FROM Confirmations; </pre><p>Output</p><pre>| user_id | timeout | confirmed |<br>| ------- | ------- | --------- |<br>| 3       | timeout | null      |<br>| 3       | timeout | null      |<br>| 7       | null    | confirmed |<br>| 7       | null    | confirmed |<br>| 7       | null    | confirmed |<br>| 2       | null    | confirmed |<br>| 2       | timeout | null      |</pre><h4>Step-02: <strong>Calculate the confirmation rate</strong> using the derived timeout and confirmed counts — GROUP BY, ROUND</h4><p>With the query from step-01 as inline table,</p><ul><li>Use the derived timeout and confirmed columns, calculate the confirmation rate by aggregating counts for each user and apply the formula</li><li>Round the rate to two decimal places.</li></ul><pre>SELECT user_id, ROUND(COUNT(confirmed)/(COUNT(confirmed)+COUNT(timeout)), 2) AS rate  <br>FROM ( <br>    SELECT user_id, <br>    (CASE WHEN action = &#39;timeout&#39; THEN &#39;timeout&#39; END) AS &#39;timeout&#39;, <br>    (CASE WHEN action = &#39;confirmed&#39; THEN &#39;confirmed&#39; END) AS &#39;confirmed&#39; <br>    FROM Confirmations <br>) AS Info <br>GROUP BY user_id; </pre><p>Output</p><pre>| user_id | rate |<br>| ------- | ---- |<br>| 3       | 0    |<br>| 7       | 1    |<br>| 2       | 0.5  |</pre><h4>Step-03: <strong>Assign the confirmation rate</strong> back to each user in the Signups table - LEFT JOIN</h4><p>Finally, we join the calculated rates back to the Signups table using a LEFT JOIN with the inline table from Step-02, ensuring every user is included and assigning a confirmation rate (defaulting to 0 when no records exist).</p><pre>SELECT Signups.user_id, IFNULL(rate, 0) AS confirmation_rate <br>FROM Signups <br>LEFT JOIN ( <br>SELECT user_id, ROUND(COUNT(confirmed)/(COUNT(confirmed)+COUNT(timeout)), 2) AS rate  <br>FROM ( <br>    SELECT user_id, <br>    (CASE WHEN action = &#39;timeout&#39; THEN &#39;timeout&#39; END) AS &#39;timeout&#39;, <br>    (CASE WHEN action = &#39;confirmed&#39; THEN &#39;confirmed&#39; END) AS &#39;confirmed&#39; <br>    FROM Confirmations <br>) AS Info <br>GROUP BY user_id <br>) AS RateInfo <br>ON Signups.user_id = RateInfo.user_id; </pre><p>Output</p><pre>| user_id | confirmation_rate |<br>| ------- | ----------------- |<br>| 3       | 0                 |<br>| 7       | 1                 |<br>| 2       | 0.5               |<br>| 6       | 0                 |</pre><p>All test cases passed successfully.</p><h4>Conclusion</h4><p>That’s it for <strong>Problem 14 </strong>of the <strong>LeetCode SQL50 Series</strong>!</p><p>In this article, we explored CASE expression for pivoting table, revisited the LEFT JOIN, Inline table, GROUP BY clause, and built-in functions ROUND() and IFNULL().</p><p>As we continue through the series, we’ll solving more complex problems with <strong>aggregations</strong>, and <strong>sub-queries</strong>, gradually building our SQL muscle one problem at a time.</p><p>If you’re following along, I encourage you to try solving the next problem on your own before reading the next post — it’s a great way to reinforce what you’re learning.</p><p>Thanks for reading, and stay tuned for <strong>Problem 15</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c77115d4a486" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crack the LeetCode SQL 50 Series -Problem 13]]></title>
            <link>https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-13-a3bed7154fce?source=rss-140ac3fd2264------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3bed7154fce</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[KoshyK]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 10:12:42 GMT</pubDate>
            <atom:updated>2025-08-24T10:12:42.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDculZfJJKV-pPKzkeGk_A.png" /><figcaption>LeetCode SQL 50 Series (Image generated using DALL·E via ChatGPT (OpenAI))</figcaption></figure><p>Hey there! 👋</p><h4>Short-tro</h4><p>Welcome back to the LeetCode SQL50 Series — the LeetCode SQL50 challenge collection that covers important SQL concepts you’ll come across in real-world applications and interviews. In this series, I’ll be sharing my solutions, thought process, and a bit of commentary along the way — like a learning journal.</p><p>This series is great for beginners, but it also serves as a solid refresher for anyone who wants to brush up on writing clean and efficient SQL queries.</p><h4>Problem</h4><p>In the previous article(Problem 12), we explored CROSS JOIN and revisited the concepts of Inline tables and the GROUP BY clause.</p><p>I hope you had a chance to attempt <strong>Problem 13</strong> on your own. If not, no worries — let’s work through the solution together now!</p><p><a href="https://leetcode.com/problems/managers-with-at-least-5-direct-reports/">570. Managers with at Least 5 Direct Reports</a> (Medium)</p><pre>Table: Employee<br><br>+-------------+---------+<br>| Column Name | Type    |<br>+-------------+---------+<br>| id          | int     |<br>| name        | varchar |<br>| department  | varchar |<br>| managerId   | int     |<br>+-------------+---------+<br>id is the primary key (column with unique values) for this table.<br>Each row of this table indicates the name of an employee, their department, and the id of their manager.<br>If managerId is null, then the employee does not have a manager.<br>No employee will be the manager of themself.<br><br>Write a solution to find managers with at least five direct reports.<br><br>Return the result table in any order.<br><br>The result format is in the following example.<br><br> <br><br>Example 1:<br><br>Input: <br>Employee table:<br>+-----+-------+------------+-----------+<br>| id  | name  | department | managerId |<br>+-----+-------+------------+-----------+<br>| 101 | John  | A          | null      |<br>| 102 | Dan   | A          | 101       |<br>| 103 | James | A          | 101       |<br>| 104 | Amy   | A          | 101       |<br>| 105 | Anne  | A          | 101       |<br>| 106 | Ron   | B          | 101       |<br>+-----+-------+------------+-----------+<br>Output: <br>+------+<br>| name |<br>+------+<br>| John |<br>+------+</pre><p>Let’s take a look at the given table,</p><ul><li>The <strong>Employee</strong> table has id as the primary key.</li><li>The <strong>manager of an employee</strong> can be identified using the managerId column.</li></ul><p>The problem requires us to,</p><ul><li>Identify employees who are managers with <strong>five or more employees reporting to them</strong>.</li></ul><p>To accomplish this, we need to,</p><ol><li>Group the records by managerId.</li><li>Filter out groups where the count of employees is greater than or equal to 5.</li><li>Retrieve the names of employees from the Employee table whose id matches the managerIds identified in step 2.</li></ol><p>Before we proceed with the solution, let’s take a moment to understand the difference between the <strong>WHERE</strong> clause and the <strong>HAVING</strong> clause.</p><h4>What is WHERE clause?</h4><p>The <strong>WHERE clause</strong> in SQL is used to restrict rows are included in the query result set using logical and comparison operators.</p><p>Some properties of WHERE clause are,</p><ol><li>It works on <strong>individual rows</strong> (<strong><em>row-level filtering</em></strong>).</li><li>It is used to<strong> filter rows before any grouping or aggregation</strong> is applied.</li><li>It<strong> cannot use aggregate functions</strong> like COUNT(), SUM(), AVG(), etc.</li><li>It can use logical operators (AND, OR, NOT) and comparison operators (=, &lt;, &gt;, BETWEEN, IN, LIKE) on <strong>row conditions</strong> (non-aggregate).</li></ol><h4>What is HAVING clause?</h4><p>The <strong>HAVING clause</strong> in SQL is used to filter groups of rows after the GROUP BY operation and aggregation have been applied.</p><p>Some properties of HAVING clause are,</p><ol><li>It works on <strong>groups of rows</strong> (<strong><em>group-level filtering</em></strong>).</li><li>It usually comes <strong>after GROUP BY</strong> in the query.</li><li>It <strong>can use aggregate functions</strong> like COUNT(), SUM(), AVG(), MAX(), MIN().</li><li>It can use logical operators (AND, OR, NOT) and comparison operators (=, &lt;, &gt;, BETWEEN, IN, LIKE) on <strong>group conditions</strong> (often but not limited to aggregates).</li></ol><p>Now let’s get back to the problem.</p><h4>Step-01: Group records by managerId - Using GROUP BY</h4><pre>SELECT managerId, COUNT(managerId) AS reports <br>FROM Employee <br>GROUP BY managerId; </pre><p>Output</p><pre>| managerId | reports |<br>| --------- | ------- |<br>| null      | 0       |<br>| 101       | 5       |</pre><h4>Step-02: Filter out groups with employee count &gt;= 5 - Using HAVING</h4><pre>SELECT managerId<br>FROM Employee <br>GROUP BY managerId<br>HAVING COUNT(managerId) &gt;= 5; </pre><p>Output</p><pre>| managerId |<br>| --------- |<br>| 101       |</pre><h4><strong>Step-03: Retrieve manager names by matching Employee IDs with managerIds from Step-02 - Using sub-query</strong></h4><p>We’ll use a sub-query to refer the managerIds obtained in Step-02.</p><pre>SELECT name<br>FROM Employee<br>WHERE id IN (<br>    SELECT managerId<br>    FROM Employee <br>    GROUP BY managerId<br>    HAVING COUNT(managerId) &gt;= 5<br>); </pre><p>Output</p><pre>| name |<br>| ---- |<br>| John |</pre><p>All test cases passed successfully.</p><h4>Conclusion</h4><p>That’s it for <strong>Problem 13 </strong>of the <strong>LeetCode SQL50 Series</strong>!</p><p>In this article, we explored WHERE clause, HAVING clause, their properties and revisited sub-query.</p><p>As we continue through the series, we’ll solve more complex problem with <strong>aggregations</strong>, and <strong>sub-queries</strong>, gradually building our SQL muscle one problem at a time.</p><p>If you’re following along, I encourage you to try solving the next problem on your own before reading the next post — it’s a great way to reinforce what you’re learning.</p><p>Thanks for reading, and stay tuned for <strong>Problem 14</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3bed7154fce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crack the LeetCode SQL 50 Series -Problem 12]]></title>
            <link>https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-12-e79aedf01710?source=rss-140ac3fd2264------2</link>
            <guid isPermaLink="false">https://medium.com/p/e79aedf01710</guid>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <dc:creator><![CDATA[KoshyK]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 14:08:23 GMT</pubDate>
            <atom:updated>2025-08-23T14:08:23.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDculZfJJKV-pPKzkeGk_A.png" /><figcaption>LeetCode SQL 50 Series (Image generated using DALL·E via ChatGPT (OpenAI))</figcaption></figure><p>Hey there! 👋</p><h4>Short-tro</h4><p>Welcome back to the LeetCode SQL50 Series — the LeetCode SQL50 challenge collection that covers important SQL concepts you’ll come across in real-world applications and interviews. In this series, I’ll be sharing my solutions, thought process, and a bit of commentary along the way — like a learning journal.</p><p>This series is great for beginners, but it also serves as a solid refresher for anyone who wants to brush up on writing clean and efficient SQL queries.</p><h4>Problem</h4><p>In the previous article, we revisited primary key, foreign key and LEFT JOIN.</p><p>If you’ve already tried <strong>Problem 12</strong>, that’s great practice. If not, no worries — we’ll work through it together now!</p><p><a href="https://leetcode.com/problems/students-and-examinations/">1280. Students and Examinations</a> (Easy)</p><pre>Table: Students<br><br>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| student_id    | int     |<br>| student_name  | varchar |<br>+---------------+---------+<br>student_id is the primary key (column with unique values) for this table.<br>Each row of this table contains the ID and the name of one student in the school.<br><br>Table: Subjects<br><br>+--------------+---------+<br>| Column Name  | Type    |<br>+--------------+---------+<br>| subject_name | varchar |<br>+--------------+---------+<br>subject_name is the primary key (column with unique values) for this table.<br>Each row of this table contains the name of one subject in the school.<br><br>Table: Examinations<br><br>+--------------+---------+<br>| Column Name  | Type    |<br>+--------------+---------+<br>| student_id   | int     |<br>| subject_name | varchar |<br>+--------------+---------+<br>There is no primary key (column with unique values) for this table. It may contain duplicates.<br>Each student from the Students table takes every course from the Subjects table.<br>Each row of this table indicates that a student with ID student_id attended the exam of subject_name.<br><br>Write a solution to find the number of times each student attended each exam.<br><br>Return the result table ordered by student_id and subject_name.<br><br>The result format is in the following example.<br><br> <br><br>Example 1:<br><br>Input: <br>Students table:<br>+------------+--------------+<br>| student_id | student_name |<br>+------------+--------------+<br>| 1          | Alice        |<br>| 2          | Bob          |<br>| 13         | John         |<br>| 6          | Alex         |<br>+------------+--------------+<br>Subjects table:<br>+--------------+<br>| subject_name |<br>+--------------+<br>| Math         |<br>| Physics      |<br>| Programming  |<br>+--------------+<br>Examinations table:<br>+------------+--------------+<br>| student_id | subject_name |<br>+------------+--------------+<br>| 1          | Math         |<br>| 1          | Physics      |<br>| 1          | Programming  |<br>| 2          | Programming  |<br>| 1          | Physics      |<br>| 1          | Math         |<br>| 13         | Math         |<br>| 13         | Programming  |<br>| 13         | Physics      |<br>| 2          | Math         |<br>| 1          | Math         |<br>+------------+--------------+<br>Output: <br>+------------+--------------+--------------+----------------+<br>| student_id | student_name | subject_name | attended_exams |<br>+------------+--------------+--------------+----------------+<br>| 1          | Alice        | Math         | 3              |<br>| 1          | Alice        | Physics      | 2              |<br>| 1          | Alice        | Programming  | 1              |<br>| 2          | Bob          | Math         | 1              |<br>| 2          | Bob          | Physics      | 0              |<br>| 2          | Bob          | Programming  | 1              |<br>| 6          | Alex         | Math         | 0              |<br>| 6          | Alex         | Physics      | 0              |<br>| 6          | Alex         | Programming  | 0              |<br>| 13         | John         | Math         | 1              |<br>| 13         | John         | Physics      | 1              |<br>| 13         | John         | Programming  | 1              |<br>+------------+--------------+--------------+----------------+<br>Explanation: <br>The result table should contain all students and all subjects.<br>Alice attended the Math exam 3 times, the Physics exam 2 times, and the Programming exam 1 time.<br>Bob attended the Math exam 1 time, the Programming exam 1 time, and did not attend the Physics exam.<br>Alex did not attend any exams.<br>John attended the Math exam 1 time, the Physics exam 1 time, and the Programming exam 1 time.</pre><p>We are working with <strong>three tables</strong> in this problem,</p><ul><li><strong>Students</strong> table, where student_id serves as the primary key.</li><li><strong>Subjects</strong> table, where subject_name serves as the primary key.</li><li><strong>Examinations</strong> table, which does not have a primary key.</li></ul><p>The task requires us to:</p><ul><li>Find the <strong>attendance of each student for every subject</strong>.</li><li>Present the results in <strong>ascending order of student_id and subject_name</strong>.</li></ul><p>To achieve this, we can break the solution down into the following steps:</p><ol><li>Generate a table that contains <strong>all possible combinations</strong> of students and subjects using the Students and Subjects tables</li><li><strong>Map the attendance data</strong> from the Examinations table onto this combined table.</li><li><strong>Sort the final results</strong> in ascending order by student_id and subject_name.</li></ol><p>Let’s revisit <strong>SQL JOINs</strong> to understand which one fits our requirement.</p><h4>What are the different types of SQL JOINs?</h4><ol><li><strong>INNER JOIN</strong> — Returns only the rows where there is a match in <strong><em>both tables</em></strong> based on the join condition. Rows with no matching key in either table are excluded.</li><li><strong>LEFT JOIN</strong> — Returns <strong><em>all rows from the left table</em></strong>, and the matching rows from the right table. If there is no match on the right, columns from the right table are filled with NULL.</li><li><strong>RIGHT JOIN</strong> — Returns <strong><em>all rows from the right table</em></strong>, and the matching rows from the left table. If there is no match on the left, columns from the left table are filled with NULL.</li><li><strong>FULL OUTER JOIN</strong> — Returns <strong><em>all rows from both tables</em></strong>, regardless of whether a match exists. If there is no match on either side, the missing columns are filled with NULL.</li><li><strong>CROSS JOIN</strong> — Returns the<em> </em><strong><em>Cartesian product</em></strong><em> </em>of the two tables — every row from the first table is combined with every row from the second. <br>Note: No join condition is used.</li><li><strong>SELF JOIN</strong> — Joins a <strong><em>table with itself</em></strong> by using aliases.</li></ol><p>In our case, since we need <strong>all possible student–subject combinations</strong>, the appropriate choice is <strong>CROSS JOIN</strong>.</p><h4>Step-01: Generate student-subject combination — Cross Join.</h4><p>The first step is to create all possible combinations of each student with every subject. This can be achieved using a <strong>CROSS JOIN</strong>, which pairs every row from the Students table with every row from the Subjects table.</p><pre>SELECT *<br>FROM Students<br>CROSS JOIN Subjects;</pre><p>Output</p><pre>| student_id | student_name | subject_name |<br>| ---------- | ------------ | ------------ |<br>| 1          | Alice        | Programming  |<br>| 1          | Alice        | Physics      |<br>| 1          | Alice        | Math         |<br>| 2          | Bob          | Programming  |<br>| 2          | Bob          | Physics      |<br>| 2          | Bob          | Math         |<br>| 13         | John         | Programming  |<br>| 13         | John         | Physics      |<br>| 13         | John         | Math         |<br>| 6          | Alex         | Programming  |<br>| 6          | Alex         | Physics      |<br>| 6          | Alex         | Math         |</pre><h4>Step-02: Map attendance data from Examinations table — Inline table and GROUP BY</h4><p>Let’s break this down to further smaller steps.</p><ul><li>Treat the result from <strong>Step-01</strong> (student–subject combinations) as an <strong>inline table</strong>.</li><li>Use a <strong>LEFT JOIN</strong> with the Examinations table on:<br>1) student_id<br>2) subject_name</li><li>Apply <strong>GROUP BY</strong> to aggregate attendance for each (student_id, subject_name) pair.</li><li>Use <strong>COUNT(Examinations.subject_name)</strong> to calculate the attendance count.</li></ul><p>This leads us to the query,</p><pre>SELECT<br>    Info.student_id AS student_id,<br>    Info.student_name AS student_name,<br>    Info.subject_name AS subject_name,<br>    COUNT(Examinations.subject_name) AS attended_exams<br>FROM (<br>    SELECT *<br>    FROM Students<br>    CROSS JOIN Subjects<br>    ) AS INFO<br>LEFT JOIN Examinations<br>ON <br>    Info.student_id=Examinations.student_id AND<br>    Info.subject_name=Examinations.subject_name<br>GROUP BY <br>    Info.student_id, <br>    Info.student_name, <br>    Info.subject_name;</pre><blockquote><em>🎤</em> Please try answering,<br>1) What is a sub-query?<br>2) What is an Inline table? <br>(Note: We have already covered this in a <a href="https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-10-93c16073ce3e">previous article</a>)<br>3) What is the condition associated with columns and SELECT clause while using GROUP BY?<br>(Note: We have already covered this in a <a href="https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-08-f332f31cdf4a">previous article</a>)</blockquote><p>Output</p><pre>| student_id | student_name | subject_name | attended_exams |<br>| ---------- | ------------ | ------------ | -------------- |<br>| 1          | Alice        | Programming  | 1              |<br>| 1          | Alice        | Physics      | 2              |<br>| 1          | Alice        | Math         | 3              |<br>| 2          | Bob          | Programming  | 1              |<br>| 2          | Bob          | Physics      | 0              |<br>| 2          | Bob          | Math         | 1              |<br>| 13         | John         | Programming  | 1              |<br>| 13         | John         | Physics      | 1              |<br>| 13         | John         | Math         | 1              |<br>| 6          | Alex         | Programming  | 0              |<br>| 6          | Alex         | Physics      | 0              |<br>| 6          | Alex         | Math         | 0              |</pre><h4>Step-03: Sorting the results — ORDER BY</h4><p>The problem statement requires us to order the columns in ascending order by student_id and subject_name.</p><pre>SELECT<br>    Info.student_id AS student_id,<br>    Info.student_name AS student_name,<br>    Info.subject_name AS subject_name,<br>    COUNT(Examinations.subject_name) AS attended_exams<br>FROM (<br>    SELECT *<br>    FROM Students<br>    CROSS JOIN Subjects<br>    ) AS INFO<br>LEFT JOIN Examinations<br>ON <br>    Info.student_id=Examinations.student_id AND<br>    Info.subject_name=Examinations.subject_name<br>GROUP BY <br>    Info.student_id, <br>    Info.student_name, <br>    Info.subject_name<br>ORDER BY<br>    student_id,<br>    subject_name;<br></pre><p>Output</p><pre>| student_id | student_name | subject_name | attended_exams |<br>| ---------- | ------------ | ------------ | -------------- |<br>| 1          | Alice        | Math         | 3              |<br>| 1          | Alice        | Physics      | 2              |<br>| 1          | Alice        | Programming  | 1              |<br>| 2          | Bob          | Math         | 1              |<br>| 2          | Bob          | Physics      | 0              |<br>| 2          | Bob          | Programming  | 1              |<br>| 6          | Alex         | Math         | 0              |<br>| 6          | Alex         | Physics      | 0              |<br>| 6          | Alex         | Programming  | 0              |<br>| 13         | John         | Math         | 1              |<br>| 13         | John         | Physics      | 1              |<br>| 13         | John         | Programming  | 1              |</pre><p>All test cases passed successfully.</p><h4>Conclusion</h4><p>That’s it for <strong>Problem 12 </strong>of the <strong>LeetCode SQL50 Series</strong>!</p><p>In this article, we revisited the different SQL JOINs, Inline table, GROUP BY clause, ORDER BY clause and focused on CROSS JOIN.</p><p>As we continue through the series, we’ll solving more complex problems with <strong>aggregations</strong>, and <strong>sub-queries</strong>, gradually building our SQL muscle one problem at a time.</p><p>If you’re following along, I encourage you to try solving the next problem on your own before reading the next post — it’s a great way to reinforce what you’re learning.</p><p>Thanks for reading, and stay tuned for <strong>Problem 13</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e79aedf01710" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crack the LeetCode SQL 50 Series -Problem 11]]></title>
            <link>https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-11-0241f18eed75?source=rss-140ac3fd2264------2</link>
            <guid isPermaLink="false">https://medium.com/p/0241f18eed75</guid>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[KoshyK]]></dc:creator>
            <pubDate>Sun, 17 Aug 2025 13:33:27 GMT</pubDate>
            <atom:updated>2025-08-17T13:33:27.038Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDculZfJJKV-pPKzkeGk_A.png" /><figcaption>LeetCode SQL 50 Series (Image generated using DALL·E via ChatGPT (OpenAI))</figcaption></figure><p>Hey there! 👋</p><h4>Short-tro</h4><p>Welcome back to the LeetCode SQL50 Series — the LeetCode SQL50 challenge collection that covers important SQL concepts you’ll come across in real-world applications and interviews. In this series, I’ll be sharing my solutions, thought process, and a bit of commentary along the way — like a learning journal.</p><p>This series is great for beginners, but it also serves as a solid refresher for anyone who wants to brush up on writing clean and efficient SQL queries.</p><h4>Problem</h4><p>In the last article(Problem 10), we worked with sub-query, Inline table creation and buit-in functions — AVG(), ROUND().</p><p>I hope you had a chance to check <strong>Problem 11. </strong>If not, no problem — let’s solve it together!</p><p><a href="https://leetcode.com/problems/employee-bonus/">577. Employee Bonus</a> (Easy)</p><pre>Table: Employee<br><br>+-------------+---------+<br>| Column Name | Type    |<br>+-------------+---------+<br>| empId       | int     |<br>| name        | varchar |<br>| supervisor  | int     |<br>| salary      | int     |<br>+-------------+---------+<br>empId is the column with unique values for this table.<br>Each row of this table indicates the name and the ID of an employee in addition to their salary and the id of their manager.<br><br>Table: Bonus<br><br>+-------------+------+<br>| Column Name | Type |<br>+-------------+------+<br>| empId       | int  |<br>| bonus       | int  |<br>+-------------+------+<br>empId is the column of unique values for this table.<br>empId is a foreign key (reference column) to empId from the Employee table.<br>Each row of this table contains the id of an employee and their respective bonus.<br><br>Write a solution to report the name and bonus amount of each employee with a bonus less than 1000.<br><br>Return the result table in any order.<br><br>The result format is in the following example.<br><br> <br><br>Example 1:<br><br>Input: <br>Employee table:<br>+-------+--------+------------+--------+<br>| empId | name   | supervisor | salary |<br>+-------+--------+------------+--------+<br>| 3     | Brad   | null       | 4000   |<br>| 1     | John   | 3          | 1000   |<br>| 2     | Dan    | 3          | 2000   |<br>| 4     | Thomas | 3          | 4000   |<br>+-------+--------+------------+--------+<br>Bonus table:<br>+-------+-------+<br>| empId | bonus |<br>+-------+-------+<br>| 2     | 500   |<br>| 4     | 2000  |<br>+-------+-------+<br>Output: <br>+------+-------+<br>| name | bonus |<br>+------+-------+<br>| Brad | null  |<br>| John | null  |<br>| Dan  | 500   |<br>+------+-------+</pre><p>Let’s start by taking a closer look at the two tables defined in the problem before moving on to the solution.</p><ul><li>The <strong>Employee</strong> table has <strong>empId</strong> as its <strong><em>primary key</em></strong>.</li><li>The <strong>Bonus</strong> table has <strong>empId</strong> as both its primary key and a <strong><em>foreign key</em></strong> that references the empId column in the <strong>Employee</strong> table.</li></ul><blockquote>🎤 Now, please try answering,<br>1) What is a <strong>primary key</strong>?<br>2) What is a <strong>composite primary key</strong>?<br>3) What is a <strong>foreign key</strong>?<br>(Note: We have already covered these questions in <a href="https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-07-0712abb57e75">previous articles</a>)</blockquote><p>From the problem statement and the example, we understand that the task is to,</p><ol><li>Assign bonuses from the <strong>Bonus</strong> table to each employee in the <strong>Employee</strong> table.</li><li>Filter the results to include only those employees whose bonus is lesser than 1000 (including NULL).</li></ol><p>To accomplish this, we need to join the two tables. Since the requirement is to preserve <strong>all employees</strong> from the <strong>Employee</strong> table, even when they don’t have a corresponding entry in the <strong>Bonus</strong> table, the appropriate choice is a <strong>LEFT JOIN</strong>.</p><p>Let’s solve this step by step.</p><h4>Step-01: Assign bonus to each employee — LEFT JOIN</h4><pre>SELECT name, bonus<br>FROM Employee<br>LEFT JOIN Bonus<br>ON Employee.empId = Bonus.empId;</pre><p>Output</p><pre>| name   | bonus |<br>| ------ | ----- |<br>| Brad   | null  |<br>| John   | null  |<br>| Dan    | 500   |<br>| Thomas | 2000  |</pre><h4>Step-02: Filter only the records where the bonus is lesser than 1000 (including NULL)– WHERE clause</h4><pre>SELECT name, bonus<br>FROM Employee<br>LEFT JOIN Bonus<br>ON Employee.empId = Bonus.empId<br>WHERE bonus &lt; 1000 OR bonus IS NULL;</pre><blockquote>🎤 Please try answering,<br>1) Why is NULL not covered by <strong>bonus &lt; 1000</strong> condition?<br>(Note: We have already covered this in a <a href="https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-02-a803524b5264">previous article</a>)</blockquote><p>Output</p><pre>| name | bonus |<br>| ---- | ----- |<br>| Brad | null  |<br>| John | null  |<br>| Dan  | 500   |</pre><p>All test cases passed successfully.</p><h4>Conclusion</h4><p>That’s it for <strong>Problem 11 </strong>of the <strong>LeetCode SQL50 Series</strong>!</p><p>In this article, we revisited primary key, foreign key, LEFT JOIN and WHEREclause.</p><p>As we continue through the series, we’ll dive into more advanced topics like <strong>aggregations</strong>, and <strong>sub-queries</strong>, gradually building our SQL muscle one problem at a time.</p><p>If you’re following along, I encourage you to try solving the next problem on your own before reading the next post — it’s a great way to reinforce what you’re learning.</p><p>Thanks for reading, and stay tuned for <strong>Problem 12</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0241f18eed75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crack the LeetCode SQL 50 Series -Problem 10]]></title>
            <link>https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-10-93c16073ce3e?source=rss-140ac3fd2264------2</link>
            <guid isPermaLink="false">https://medium.com/p/93c16073ce3e</guid>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <dc:creator><![CDATA[KoshyK]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 11:25:40 GMT</pubDate>
            <atom:updated>2025-08-16T11:25:40.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDculZfJJKV-pPKzkeGk_A.png" /><figcaption>LeetCode SQL 50 Series (Image generated using DALL·E via ChatGPT (OpenAI))</figcaption></figure><p>Hey there! 👋</p><h4>Short-tro</h4><p>Welcome back to the LeetCode SQL50 Series — the LeetCode SQL50 challenge collection that covers important SQL concepts you’ll come across in real-world applications and interviews. In this series, I’ll be sharing my solutions, thought process, and a bit of commentary along the way — like a learning journal.</p><p>This series is great for beginners, but it also serves as a solid refresher for anyone who wants to brush up on writing clean and efficient SQL queries.</p><h4>Problem</h4><p>In the previous article (Problem 09), we came across <strong>self join using 2 different aliases</strong> and <strong>DATE_ADD()</strong> function.</p><p>If you’ve already tried <strong>Problem 10</strong>, that’s great practice. If not, don’t worry — we’ll work through it together now!</p><p><a href="https://leetcode.com/problems/average-time-of-process-per-machine/">1661. Average Time of Process per Machine</a> (Easy)</p><pre>Table: Activity<br><br>+----------------+---------+<br>| Column Name    | Type    |<br>+----------------+---------+<br>| machine_id     | int     |<br>| process_id     | int     |<br>| activity_type  | enum    |<br>| timestamp      | float   |<br>+----------------+---------+<br>The table shows the user activities for a factory website.<br>(machine_id, process_id, activity_type) is the primary key (combination of columns with unique values) of this table.<br>machine_id is the ID of a machine.<br>process_id is the ID of a process running on the machine with ID machine_id.<br>activity_type is an ENUM (category) of type (&#39;start&#39;, &#39;end&#39;).<br>timestamp is a float representing the current time in seconds.<br>&#39;start&#39; means the machine starts the process at the given timestamp and &#39;end&#39; means the machine ends the process at the given timestamp.<br>The &#39;start&#39; timestamp will always be before the &#39;end&#39; timestamp for every (machine_id, process_id) pair.<br>It is guaranteed that each (machine_id, process_id) pair has a &#39;start&#39; and &#39;end&#39; timestamp.<br><br>There is a factory website that has several machines each running the same number of processes. Write a solution to find the average time each machine takes to complete a process.<br><br>The time to complete a process is the &#39;end&#39; timestamp minus the &#39;start&#39; timestamp. The average time is calculated by the total time to complete every process on the machine divided by the number of processes that were run.<br><br>The resulting table should have the machine_id along with the average time as processing_time, which should be rounded to 3 decimal places.<br><br>Return the result table in any order.<br><br>The result format is in the following example.<br><br> <br><br>Example 1:<br><br>Input: <br>Activity table:<br>+------------+------------+---------------+-----------+<br>| machine_id | process_id | activity_type | timestamp |<br>+------------+------------+---------------+-----------+<br>| 0          | 0          | start         | 0.712     |<br>| 0          | 0          | end           | 1.520     |<br>| 0          | 1          | start         | 3.140     |<br>| 0          | 1          | end           | 4.120     |<br>| 1          | 0          | start         | 0.550     |<br>| 1          | 0          | end           | 1.550     |<br>| 1          | 1          | start         | 0.430     |<br>| 1          | 1          | end           | 1.420     |<br>| 2          | 0          | start         | 4.100     |<br>| 2          | 0          | end           | 4.512     |<br>| 2          | 1          | start         | 2.500     |<br>| 2          | 1          | end           | 5.000     |<br>+------------+------------+---------------+-----------+<br>Output: <br>+------------+-----------------+<br>| machine_id | processing_time |<br>+------------+-----------------+<br>| 0          | 0.894           |<br>| 1          | 0.995           |<br>| 2          | 1.456           |<br>+------------+-----------------+<br>Explanation: <br>There are 3 machines running 2 processes each.<br>Machine 0 average time is ((1.520 - 0.712) + (4.120 - 3.140)) / 2 = 0.894<br>Machine 1 average time is ((1.550 - 0.550) + (1.420 - 0.430)) / 2 = 0.995<br>Machine 2 average time is ((4.512 - 4.100) + (5.000 - 2.500)) / 2 = 1.456</pre><p>Before we dive into the solution, let’s first look at the problem statement,</p><ul><li>The <strong>primary key</strong> of the Activity table is a combination of three columns: (machine_id, process_id, activity_type).</li><li>The column <strong>activity_type</strong> is defined as an <strong>ENUM</strong> with only two possible values, ‘start’ or ‘end’.</li></ul><p>The task here is to calculate the <strong>average processing time</strong> for each machine.</p><p>To accomplish this, we can break it down into the following steps,</p><ol><li><strong>Extract start and end times</strong> <br>For each machine_id and process_id, create two new columns: start_time and end_time, using the values from the timestamp column<br><em>(Note: Every column in the SELECT statement must either be included in the GROUP BY clause or wrapped in an aggregate function.)</em></li><li><strong>Store intermediate results</strong> <br>Save the output from Step-01 into a temporary table for easier reference.</li><li><strong>Calculate processing time</strong> <br>Using the temporary table, compute the processing time for each process (end_time — start_time) and then calculate the <strong>average processing time per machine_id</strong>.</li><li><strong>Format results<br></strong>Round the final average processing time to <strong>three decimal places</strong> as required by the problem statement.</li></ol><p>Let’s solve this step by step.</p><h4>Step-01: Extract start and end times — Multi-column grouping</h4><p>In a previous article, we learnt about <strong>GROUP BY</strong> clause and how it is used to arrange identical data into groups.</p><p>Here for each machine_id, for every process_id, we’ll be adding 2 columns start_time and end_time.</p><ul><li>start_time will hold the earliest timestamp (when the process starts) for each process_id of a machine.</li><li>end_time will hold the the latest timestamp (when the process ends) for each process_id of a machine.</li></ul><p>This grouping of timestamp for each machine_id and process_id is <strong><em>multi-column grouping</em></strong>.</p><p>This results in the query,</p><pre>SELECT <br><br>    machine_id, <br><br>    process_id, <br><br>    MIN(timestamp) AS start_time, <br><br>    MAX(timestamp) AS end_time <br><br>FROM Activity <br><br>GROUP BY machine_id, process_id;</pre><p>Output</p><pre>| machine_id | process_id | start_time | end_time |<br>| ---------- | ---------- | ---------- | -------- |<br>| 0          | 0          | 0.712      | 1.52     |<br>| 0          | 1          | 3.14       | 4.12     |<br>| 1          | 0          | 0.55       | 1.55     |<br>| 1          | 1          | 0.43       | 1.42     |<br>| 2          | 0          | 4.1        | 4.512    |<br>| 2          | 1          | 2.5        | 5        |</pre><h4>Step-02: <strong>Store intermediate results — I</strong>nline temporary table</h4><p>We have grouped the data by (machine_id, process_id) to derive start_time and end_time. Instead of storing these results in a separate table, we can <strong>embed this query as a sub-query</strong> and create an inline table.</p><p>Now, you might have a few questions.</p><h4>What is a sub-query?</h4><p>A <strong>sub-query</strong> is a query nested inside another SQL statement.</p><ul><li>It can appear in SELECT, FROM, WHERE, or HAVING clauses.<br>(We’ll check out HAVING clauses in )</li><li>The result of a sub-query is passed to the outer query for further processing.</li></ul><h4>What is an Inline table?</h4><p>When a <strong>sub-query</strong> is placed inside the FROM clause and given an <strong>alias</strong>, it behaves like a <strong>temporary virtual table </strong>which is also referred as <strong>Inline table.</strong></p><ul><li>It doesn’t exist permanently in the database.</li><li>It exists only for the duration of the query.</li><li><strong><em>It is mandatory to assign an alias to reference it.</em></strong></li></ul><p>Getting back to the problem, this leads to the query,</p><pre>SELECT * <br><br>FROM ( <br><br>    SELECT <br><br>        machine_id, <br><br>        process_id, <br><br>        MIN(timestamp) AS start_time, <br><br>        MAX(timestamp) AS end_time <br><br>    FROM Activity <br><br>    GROUP BY machine_id, process_id <br><br>) AS ProcessingTimes;</pre><p>The alias <strong><em>ProcessingTimes</em></strong> now behaves just like a table, holding machine_id, process_id, start_time, and end_time. This makes it easier to calculate processing times in the next step without repeating the grouping logic.</p><p>Output</p><pre>| machine_id | process_id | start_time | end_time |<br>| ---------- | ---------- | ---------- | -------- |<br>| 0          | 0          | 0.712      | 1.52     |<br>| 0          | 1          | 3.14       | 4.12     |<br>| 1          | 0          | 0.55       | 1.55     |<br>| 1          | 1          | 0.43       | 1.42     |<br>| 2          | 0          | 4.1        | 4.512    |<br>| 2          | 1          | 2.5        | 5        |</pre><h4>Step-03: <strong>Calculate processing time — AVG()</strong></h4><p>From the temporary inline table created, we can calculate the average processing time using the aggregate function AVG() for each machine_id.</p><p>This modifies the query as,</p><pre>SELECT <br><br>    machine_id, <br><br>    AVG(end_time-start_time) AS processing_time <br><br>FROM  <br><br>( <br><br>    SELECT <br><br>        machine_id, <br><br>        process_id, <br><br>        MIN(timestamp) AS start_time, <br><br>        MAX(timestamp) AS end_time <br><br>    FROM Activity <br><br>    GROUP BY machine_id, process_id <br><br>) AS ProcessingTimes <br><br>GROUP BY machine_id; </pre><p>Output</p><pre>| machine_id | processing_time    |<br>| ---------- | ------------------ |<br>| 0          | 0.8939998745918274 |<br>| 1          | 0.9949999451637268 |<br>| 2          | 1.4560000896453857 |</pre><h4>Step-04: <strong>Format results — ROUND()</strong></h4><p>Now the problem mentions that the processing time should be rounded off to 3 decimal points.</p><p>There’s a built-in function, <strong>ROUND()</strong> which could be used for this, giving us the final solution.</p><h4>Solution</h4><pre>SELECT <br><br>    machine_id, <br><br>    ROUND(AVG(end_time-start_time), 3) AS processing_time <br><br>FROM  <br><br>( <br><br>    SELECT <br><br>        machine_id, <br><br>        process_id, <br><br>        MIN(timestamp) AS start_time, <br><br>        MAX(timestamp) AS end_time <br><br>    FROM Activity <br><br>    GROUP BY machine_id, process_id <br><br>) AS ProcessingTimes <br><br>GROUP BY machine_id; </pre><p>Output</p><pre>| machine_id | processing_time |<br>| ---------- | --------------- |<br>| 0          | 0.894           |<br>| 1          | 0.995           |<br>| 2          | 1.456           |</pre><p>All the test cases passed successfully.</p><h4>Conclusion</h4><p>That’s it for <strong>Problem 10 </strong>of the <strong>LeetCode SQL50 Series.</strong></p><p>Congrats on solving the first 10 problems of LeetCode SQL 50 series 👏!</p><p>In this article, we explored what a sub-query is, how we could create an Inline table and built-in functions — AVG() and ROUND(). We also revisited ENUM data type and grouping with multi-column.</p><blockquote>📌 <em>Now that we have solved 10 problems, there are two important observations I would like to share,</em></blockquote><blockquote>* Follow the <strong>divide and conquer approach</strong>.</blockquote><blockquote>* Check for availability of <strong>built-in functions</strong> for each step.</blockquote><p>As we continue through the series, we’ll dive into more complex problems with the topics we have covered like <strong>aggregations</strong>, <strong>sub-queries</strong>, gradually building our SQL muscle one problem at a time.</p><p>If you’re following along, I encourage you to try solving the next problem on your own before reading the next post — it’s a great way to reinforce what you’re learning.</p><p>Thanks for reading, and stay tuned for <strong>Problem 11</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93c16073ce3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crack the LeetCode SQL 50 Series -Problem 09]]></title>
            <link>https://medium.com/@kamalikoshy97/crack-the-leetcode-sql-50-series-problem-09-08723687ee23?source=rss-140ac3fd2264------2</link>
            <guid isPermaLink="false">https://medium.com/p/08723687ee23</guid>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <dc:creator><![CDATA[KoshyK]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 16:30:21 GMT</pubDate>
            <atom:updated>2025-08-04T16:30:21.914Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDculZfJJKV-pPKzkeGk_A.png" /><figcaption>LeetCode SQL 50 Series (Image generated using DALL·E via ChatGPT (OpenAI))</figcaption></figure><p>Hey there! 👋</p><h4>Short-tro</h4><p>Welcome back to the LeetCode SQL50 Series — the LeetCode SQL50 challenge collection that covers important SQL concepts you’ll come across in real-world applications and interviews. In this series, I’ll be sharing my solutions, thought process, and a bit of commentary along the way — like a learning journal.</p><p>This series is great for beginners, but it also serves as a solid refresher for anyone who wants to brush up on writing clean and efficient SQL queries.</p><h4>Problem</h4><p>In the last article (Problem 08), we explored the GROUP BY clause and aggregate functions to analyse data in meaningful chunks.</p><p>It’s been a while — hope you had a chance to give <strong>Problem 09</strong> a shot.</p><p>Let’s dive in and solve it together!</p><p><a href="https://leetcode.com/problems/rising-temperature/">197. Rising Temperature</a> (Easy)</p><pre>Table: Weather<br><br>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| id            | int     |<br>| recordDate    | date    |<br>| temperature   | int     |<br>+---------------+---------+<br>id is the column with unique values for this table.<br>There are no different rows with the same recordDate.<br>This table contains information about the temperature on a certain day.<br><br>Write a solution to find all id of dates with higher temperatures compared to its previous dates (yesterday).<br><br>Return the result table in any order.<br><br>The result format is in the following example.<br><br> <br>Example 1:<br><br>Input: <br>Weather table:<br>+----+------------+-------------+<br>| id | recordDate | temperature |<br>+----+------------+-------------+<br>| 1  | 2015-01-01 | 10          |<br>| 2  | 2015-01-02 | 25          |<br>| 3  | 2015-01-03 | 20          |<br>| 4  | 2015-01-04 | 30          |<br>+----+------------+-------------+<br>Output: <br>+----+<br>| id |<br>+----+<br>| 2  |<br>| 4  |<br>+----+<br>Explanation: <br>In 2015-01-02, the temperature was higher than the previous day (10 -&gt; 25).<br>In 2015-01-04, the temperature was higher than the previous day (20 -&gt; 30).</pre><p>This problem involves a single table — Weather, where id is the primary key.</p><p>It requires us to,</p><ol><li>Consider only those dates (recordDate) that have an entry for the previous day.</li><li>Compare the temperature on each date with the temperature from the previous date.</li><li>Filter for dates where the temperature is <strong>higher</strong> than the previous day.</li><li>Return only the id of those records.</li></ol><p>In earlier problems, we filtered records by comparing column values either <strong>against constants or against other columns within the same row</strong>.</p><p>However, this problem introduces a new twist — we need to compare values <strong><em>within the same column but across different rows</em></strong>. This cross-row comparison adds a layer of complexity that can’t be handled by basic filters alone.</p><p>To tackle this, we have a few options:</p><ul><li><strong>Self-Join</strong> — a widely used method that pairs rows based on a logical relationship (e.g., comparing one date to the previous).</li><li><strong>Window Function</strong> — offers a clean and elegant solution using functions like LAG(), but not all SQL engines support it.</li><li><strong>Correlated Subquery</strong> — straightforward in logic but can be less efficient on larger datasets.</li></ul><p>For this problem, we’ll go with the <strong><em>Self-Join</em></strong> approach — simple, effective, and broadly supported.</p><p>(Don’t worry — we’ll explore the other two techniques in upcoming problems in this series!)</p><h4><strong>What is the Self-Join Approach in SQL?</strong></h4><p>A <strong>self-join</strong> is when a table is joined to itself. It’s particularly useful when you need to <strong>compare values across different rows</strong> <strong>in the same table</strong> — like in this problem, where we compare a value in one row to a value in another row in the same column.</p><h4><strong>How does a table join to itself?</strong></h4><p>To perform a self-join, we assign <strong>two different aliases</strong> to the same table (e.g., w1 and w2). This makes it possible for SQL to treat them as two separate entities. We then define a <strong>JOIN condition</strong> that logically connects rows from one alias to matching rows in the other.</p><p>So, we can solve this problem using the <strong>Self-Join approach</strong> by following these steps,</p><ol><li><strong>Create two aliases</strong> (w1 and w2) for the same table to enable comparison across different rows.</li><li><strong>Join the aliases</strong> on the condition that w1.recordDate + 1 = w2.recordDate, so we’re comparing each date to its previous day.</li><li><strong>Filter the results</strong> where w2.temperature &gt; w1.temperature — meaning the temperature increased compared to the previous day.</li><li><strong>Select only the IDs</strong> from the filtered results (specifically, w2.id).</li></ol><p>Now, how do we compare dates in SQL — specifically, check if one date is exactly one day after another?</p><p>This is where the <strong>DATE_ADD()</strong> function comes in handy.</p><h4>What is DATE_ADD() function in SQL?</h4><p>DATE_ADD() is a <strong>built-in</strong> SQL function. It is used in SQL to <strong>add a specified time interval</strong> (like days, months, or years) to a given date.</p><p>It’s most commonly used to <strong>manipulate date value.</strong></p><p><strong>Syntax</strong></p><pre>DATE_ADD(date, INTERVAL value unit)</pre><p>It accepts 2 parameters,</p><ol><li>date — the <strong>starting point</strong> — a valid date or datetime expression from which you want to <strong>add</strong> an interval.</li><li>INTERVAL value unit — comprising of 2 parts,</li></ol><ul><li>value — A <strong>numeric value</strong> — how much time to add.</li><li>unit — A <strong>time unit</strong> — what type of time to be added (YEAR, QUARTER, MINUTE, HOUR_MINUTE, etc,.)</li></ul><h4>Steps 1 &amp; 2: Create aliases and perform self-join using DATE_ADD()</h4><pre>SELECT * <br><br>FROM Weather AS w1 <br><br>INNER JOIN Weather AS w2 <br><br>ON DATE_ADD(w1.recordDate, INTERVAL 1 DAY) = w2.recordDate; </pre><p>Output</p><pre>| id | recordDate | temperature | id | recordDate | temperature |<br>| -- | ---------- | ----------- | -- | ---------- | ----------- |<br>| 1  | 2015-01-01 | 10          | 2  | 2015-01-02 | 25          |<br>| 2  | 2015-01-02 | 25          | 3  | 2015-01-03 | 20          |<br>| 3  | 2015-01-03 | 20          | 4  | 2015-01-04 | 30          |</pre><h4>Steps 3 &amp; 4: Filter IDs based on temperature comparison</h4><pre>SELECT w2.id <br><br>FROM Weather AS w1 <br><br>INNER JOIN Weather AS w2 <br><br>ON DATE_ADD(w1.recordDate, INTERVAL 1 DAY) = w2.recordDate <br><br>WHERE w2.temperature &gt; w1.temperature; </pre><p>Output</p><pre>| id |<br>| -- |<br>| 2  |<br>| 4  |</pre><p>All the test cases passed successfully.</p><h4>Conclusion</h4><p>That’s it for <strong>Problem 09</strong> of the <strong>LeetCode SQL50 Series</strong>!</p><p>In this article, we explored how to compare values across different rows within the same table using SQL. We introduced the concept of <strong>self-join</strong>, where a table is joined with itself using<strong> aliases</strong>. We also used the <strong>DATE_ADD()</strong> function to shift dates for comparison and revisited the WHERE clause to filter rows based on conditions.</p><p>As we continue through the series, we’ll dive into more advanced topics like <strong>aggregations</strong>, and <strong>sub-queries</strong>, gradually building our SQL muscle one problem at a time.</p><p>If you’re following along, I encourage you to try solving the next problem on your own before reading the next post — it’s a great way to reinforce what you’re learning.</p><p>Thanks for reading, and stay tuned for <strong>Problem 10</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08723687ee23" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>