<?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 Shobha Rani on Medium]]></title>
        <description><![CDATA[Stories by Shobha Rani on Medium]]></description>
        <link>https://medium.com/@rani.shoba94?source=rss-341028ed6240------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Shobha Rani on Medium</title>
            <link>https://medium.com/@rani.shoba94?source=rss-341028ed6240------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:42:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rani.shoba94/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[Choosing the Right Machine Learning Model for Healthcare: A Practical Guide]]></title>
            <link>https://medium.com/@rani.shoba94/choosing-the-right-machine-learning-model-for-healthcare-a-practical-guide-6215337aee2e?source=rss-341028ed6240------2</link>
            <guid isPermaLink="false">https://medium.com/p/6215337aee2e</guid>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Shobha Rani]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 21:15:59 GMT</pubDate>
            <atom:updated>2026-07-04T21:15:59.011Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>“From disease prediction to medical imaging, here’s how to choose the right machine learning model based on the healthcare problem you’re solving”</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*uRuXqdTDIOey9sZOn7okIg.png" /></figure><p><strong>Introduction</strong></p><p>Artificial Intelligence is transforming healthcare at an unprecedented pace. Hospitals are using machine learning to predict diseases before symptoms become severe, radiologists are using AI to assist in detecting tumors from medical images, and researchers are analyzing millions of patient records to discover hidden patterns that can improve treatment outcomes.</p><p>With so many successful applications, it’s easy to assume that the biggest challenge is building a machine learning model.</p><p>The first and often the most important challenge is choosing the right one.</p><p>When I first started learning machine learning, I spent countless hours studying algorithms. I learned how Logistic Regression works, understood the intuition behind Decision Trees, experimented with Random Forests, and was fascinated by the performance of XGBoost.</p><p>Like many beginners, I believed that learning more algorithms would automatically make me better at machine learning. It didn’t.</p><p>The real turning point came when I realized that experienced data scientists rarely begin by asking:</p><p><strong>“Which algorithm should I use?”</strong></p><p>Instead, they ask a much simpler question.</p><p><strong>“What problem am I trying to solve?”</strong></p><p>That single question eliminates most of the possible algorithms before the first line of code is even written.</p><p>Healthcare provides an excellent example of why this matters.</p><p>Imagine you’ve just joined the analytics team at a large hospital.</p><p>On your first day, three different departments approach you with three completely different requests.</p><p>The <strong>cardiology department</strong> wants to identify patients who are at high risk of developing heart disease.</p><p>The <strong>radiology department</strong> is exploring whether artificial intelligence can assist in detecting tumors from MRI scans.</p><p>Meanwhile, <strong>hospital administrators</strong> want to predict which patients are most likely to be readmitted within thirty days after discharge so they can improve care planning.</p><p>At first glance, these requests appear unrelated.</p><p>But they all have one thing in common.</p><p>Each team wants to use machine learning.</p><p>The interesting part is that <strong>none of these problems should begin with the same machine learning model.</strong></p><p>That’s where many beginners become overwhelmed.</p><p>With dozens of machine learning algorithms available today, how do you decide which one to use?</p><p>Choosing the wrong model can lead to poor predictions, unnecessary complexity, and solutions that clinicians may not trust.</p><p>Choosing the right model, however, can improve prediction accuracy, simplify implementation, and produce results that healthcare professionals can confidently use in their daily decision-making.</p><p><strong>Why Choosing the Right Machine Learning Model Matters</strong></p><p>One of the biggest misconceptions among beginners is believing that there is a single “best” machine learning algorithm.</p><p>In practice, there isn’t.</p><p>The best model always depends on three things:</p><ul><li>The problem you’re trying to solve.</li><li>The type of healthcare data available.</li><li>How the prediction will be used.</li></ul><p>Consider these examples.</p><p>Suppose you’re predicting whether a patient has diabetes based on laboratory test results, age, BMI, glucose levels, and family history.</p><p>This is a <strong>binary classification problem</strong>, and several traditional machine learning models can perform extremely well.</p><p>Now imagine you’re analyzing thousands of chest X-rays to detect pneumonia.</p><p>The data has completely changed.</p><p>Instead of structured tables containing numbers and laboratory values, you’re working with images.</p><p>The machine learning model that worked well for diabetes prediction is no longer the right choice.</p><p>Finally, imagine you’re monitoring patients admitted to an intensive care unit.</p><p>Vital signs are collected continuously over several days.</p><p>Now your data is no longer static.</p><p>It changes over time.</p><p>Again, the best model changes.</p><p>These examples demonstrate an important principle.</p><p><strong>Different healthcare problems naturally require different machine learning approaches.</strong></p><p>That’s why experienced practitioners spend time understanding the problem before selecting the algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*e_p6_uh0zEX-tAMe4kvVTg.png" /></figure><p><strong>Figure 1.</strong> Selecting a machine learning model is only one step within a complete healthcare analytics workflow.</p><p><strong>Before Choosing Any Machine Learning Model</strong></p><p>Before discussing specific algorithms, I always encourage beginners to pause and answer three simple questions.</p><p>These questions often narrow the list of suitable models far more effectively than memorizing dozens of algorithms.</p><p><strong>Question 1</strong></p><p><strong>What are you trying to predict?</strong></p><p>This is the most important question.</p><p>Every machine learning project begins with an objective.</p><p>Are you predicting:</p><ul><li>A continuous number?</li><li>A category?</li><li>Hidden groups?</li><li>An image?</li><li>A future event over time?</li></ul><p>Each answer points toward a different family of machine learning models.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7sbIw8nJ4I7O76WUpRFnQ.png" /></figure><p>Notice that we still haven’t chosen an algorithm.</p><p>We’ve only identified the type of problem.</p><p>That’s exactly where the decision should begin.</p><p><strong>Question 2</strong></p><p><strong>What type of healthcare data do you have?</strong></p><p>Healthcare data comes in many forms.</p><p>A machine learning model that performs well on structured laboratory data may perform poorly when applied to medical images or physician notes.</p><p>Some of the most common healthcare data sources include:</p><ul><li>Electronic Health Records (EHR)</li><li>Laboratory test results</li><li>Medical images (MRI, CT, X-ray)</li><li>Wearable device data</li><li>Clinical notes</li><li>Genomic and molecular data</li></ul><p>Understanding your data is just as important as understanding your algorithm.</p><p><strong>Question 3</strong></p><p><strong>Who will use the prediction?</strong></p><p>This question is often overlooked.</p><p>The same prediction may be used by different audiences, each with different expectations.</p><p>A physician may prefer an interpretable model that clearly explains why a patient is considered high risk.</p><p>A hospital administrator may focus on operational efficiency and population-level trends.</p><p>A medical researcher may prioritize predictive performance for scientific discovery.</p><p>The intended user influences the model selection process just as much as the data itself.</p><p>Sometimes a slightly less accurate but more interpretable model is the better choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*w3nATJFxVqBgkcS8S_G_BA.png" /></figure><p><strong>Figure 2.</strong> Every machine learning project should begin by identifying the prediction task rather than selecting an algorithm.</p><p><strong>Match the Healthcare Problem to the Right Machine Learning Model</strong></p><p>As we discussed earlier, selecting a machine learning model should never be the first decision in a healthcare project.</p><p>Instead, every successful project begins by answering three fundamental questions:</p><ul><li>What are you trying to predict?</li><li>What type of healthcare data do you have?</li><li>Who will use the prediction?</li></ul><p>Once you have clear answers to these questions, the number of suitable machine learning models becomes much smaller, making the selection process far more straightforward.</p><p>Rather than reviewing algorithms one by one, let’s look at this from a healthcare practitioner’s perspective.</p><p>Imagine you’re part of a hospital’s data analytics team. Throughout the day, different departments approach you with challenges they hope machine learning can help solve.</p><p>The endocrinology department wants to identify patients who are at risk of developing diabetes.</p><p>The cardiology department is looking for a way to predict heart disease before serious complications occur.</p><p>The radiology team is interested in using AI to detect abnormalities in medical images.</p><p>Hospital administrators want to predict which patients are likely to be readmitted after discharge.</p><p>Researchers are exploring patient populations to identify hidden disease patterns.</p><p>Although these requests all fall under healthcare analytics, they represent very different machine learning problems.</p><p>Each department has a unique objective, works with different types of data, and expects different outcomes.</p><p>Your responsibility isn’t to choose the most sophisticated algorithm.</p><p>Your responsibility is to understand the problem, evaluate the available data, and recommend the machine learning model that best fits the clinical objective.</p><p>That’s exactly how experienced data scientists approach real-world healthcare projects, and that’s the approach we’ll follow throughout the rest of this article.</p><p>Recommended Machine Learning Models for Common Healthcare Problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJvDyZI8HQEm-FvOf1aRHA.png" /></figure><p><strong>Clinical Problem 1: Predicting Diabetes Risk</strong></p><p>Imagine an endocrinologist asks,</p><p>Can we identify patients who are likely to develop Type 2 Diabetes before symptoms become severe?</p><p>The hospital has several years of patient information, including age, BMI, blood glucose levels, blood pressure, insulin measurements, family history, and lifestyle factors.</p><p>Since the data consists of structured patient records and the outcome is either diabetes or no diabetes, this becomes a binary classification problem.</p><p>As shown in the table above, Logistic Regression, Random Forest, and XGBoost are all excellent choices for this type of problem.</p><p>The final selection depends on the project’s objective. If clinicians need clear explanations behind every prediction, Logistic Regression offers excellent interpretability. If the focus is on capturing complex relationships among patient characteristics, Random Forest provides a strong balance between performance and robustness. When maximizing predictive accuracy on structured healthcare data is the primary goal, XGBoost is often one of the strongest performers.</p><p>Rather than searching for a single “best” algorithm, the objective is to select the model that best supports the clinical decision-making process.</p><p><strong>Clinical Problem 2: Predicting Heart Disease</strong></p><p>Now imagine the cardiology department asks,</p><p>Can we identify patients who are at high risk of developing cardiovascular disease?</p><p>The available information includes cholesterol levels, blood pressure, smoking history, ECG measurements, chest pain type, exercise-induced angina, age, and maximum heart rate.</p><p>Although this is another classification problem, cardiovascular disease often involves complex interactions among multiple clinical variables.</p><p>For these scenarios, Random Forest, XGBoost, and Support Vector Machine are commonly used because they capture nonlinear relationships that traditional statistical methods may overlook.</p><p>The choice depends on the size of the dataset, the complexity of the relationships, and the level of explainability required by clinicians.</p><p><strong>Part 3 — Beyond Structured Healthcare Data</strong></p><p>So far, we’ve focused on structured clinical records.</p><p>Healthcare, however, extends far beyond tables of laboratory values and patient demographics.</p><p>Hospitals generate millions of medical images every year.</p><p>Wearable devices continuously record patient vital signs.</p><p>Electronic Health Records contain years of longitudinal patient histories.</p><p>Clinical notes capture valuable information in unstructured text.</p><p>As the nature of the data changes, so does the choice of machine learning model.</p><p>Clinical Problem 3: Detecting Disease from Medical Images</p><p>Imagine you’re working with the radiology department.</p><p>Every day, hundreds of MRI scans, CT images, and chest X-rays are reviewed by radiologists.</p><p>The question becomes,</p><p>Can machine learning assist in detecting abnormalities before a clinician reviews the image?</p><p>Unlike diabetes prediction, this problem involves image data rather than structured patient records.</p><p>Models such as Convolutional Neural Networks (CNNs), ResNet, and EfficientNet are specifically designed to learn visual features directly from medical images, making them the preferred choice for image classification tasks.</p><p>These models have been widely adopted for applications such as tumor detection, pneumonia diagnosis, diabetic retinopathy screening, and skin lesion classification.</p><p><strong>Clinical Problem 4: Predicting Disease Progression</strong></p><p>Some healthcare questions require understanding how a patient’s condition changes over time.</p><p>Examples include monitoring Parkinson’s disease, Alzheimer’s disease, chronic kidney disease, diabetes progression, and patients admitted to intensive care units.</p><p>Unlike traditional machine learning models that analyze each observation independently, sequential models learn patterns across an entire patient timeline.</p><p>For these problems, LSTM, GRU, and Transformer models are commonly used because they capture temporal relationships within longitudinal healthcare data.</p><p>These models are particularly valuable when continuous patient monitoring is required.</p><p><strong>Clinical Problem 5: Patient Segmentation</strong></p><p>Not every healthcare project begins with a prediction.</p><p>Sometimes the objective is simply to discover meaningful patterns within the patient population.</p><p>Researchers may want to identify subgroups of diabetic patients with similar characteristics or discover patient populations that respond differently to treatment.</p><p>These projects do not have predefined labels.</p><p>Instead, the goal is to uncover naturally occurring groups within the data.</p><p>For these situations, clustering algorithms such as K-Means, Hierarchical Clustering, and DBSCAN provide effective solutions by grouping patients according to similarities in their clinical characteristics.</p><p>These insights support personalized medicine, population health management, and preventive care initiatives.</p><p>At this point, we’ve explored how different healthcare problems naturally lead to different families of machine learning models.</p><p>One important lesson should now be clear:</p><p>The healthcare problem determines the machine learning model — not the other way around.</p><p>The next question is equally important.</p><p>Given a new healthcare dataset, where should you begin?</p><p>In the final section, we’ll bring everything together with a practical model selection framework, a visual decision tree, common mistakes to avoid, and a healthcare machine learning cheat sheet that you can use as a quick reference for future projects.</p><p>“In healthcare, successful machine learning doesn’t begin with choosing an algorithm — it begins with understanding the clinical problem.”</p><p>Original article is from: <a href="https://www.numpyninjaacademy.com/post/choosing-the-right-machine-learning-model-for-healthcare-a-practical-guide">https://www.numpyninjaacademy.com/post/choosing-the-right-machine-learning-model-for-healthcare-a-practical-guide</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6215337aee2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Four PostgreSQL Features That Instantly Simplified My SQL Queries]]></title>
            <link>https://medium.com/@rani.shoba94/four-postgresql-features-that-instantly-simplified-my-sql-queries-6a161608cd13?source=rss-341028ed6240------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a161608cd13</guid>
            <dc:creator><![CDATA[Shobha Rani]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 22:14:51 GMT</pubDate>
            <atom:updated>2026-07-03T22:14:51.865Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve worked with PostgreSQL for a while, you’ve probably reached a point where a simple query slowly turns into something much bigger. It starts with a couple of joins, then another subquery, followed by a GROUP BY, and before long you’re scrolling through dozens of lines trying to remember what each part of the query is doing.</p><p>I’ve been in that situation more times than I’d like to admit.</p><p>Most of us learn SQL by mastering the fundamentals. We write SELECT statements, join tables, filter data with WHERE, and summarize results using GROUP BY. Those skills are essential, but they’re only the beginning of what PostgreSQL can do.</p><p>A few days ago, I was looking for a dataset that would let me practice some PostgreSQL concepts without falling back on the classic <strong>Employee</strong> and <strong>Department</strong> tables that appear in almost every tutorial. After a bit of searching, I came across a <strong>Gym Management</strong> dataset online. It included members, membership plans, payments, trainers, attendance records, and gym locations. It wasn’t a large database, but it had enough relationships to make the examples feel realistic.</p><p>Initially, my plan was simple. I wanted to understand the schema, write a few interesting queries, and move on.</p><p>That didn’t happen.</p><p>As I explored the dataset, every new question naturally introduced another PostgreSQL feature that simplified the solution. A ranking report led me to <strong>Window Functions</strong>. Reusing the same insert logic pointed me toward <strong>Stored Procedures</strong>. Monthly reporting became a perfect opportunity to use <strong>Recursive Queries</strong>, and presenting those results in a dashboard-friendly format introduced <strong>Crosstabs</strong>.</p><p>By the time I finished exploring the database, I realized I hadn’t just practiced SQL. I had rediscovered four PostgreSQL features that consistently made my queries cleaner, easier to read, and much simpler to maintain.</p><p><strong>Exploring the Dataset</strong></p><p>The Gym Management dataset follows a typical transactional design. Members enroll in membership plans, make payments, attend training sessions, and belong to specific gym locations. Although the database is small, it contains enough relationships to demonstrate many of PostgreSQL’s advanced capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OUFWBcCxm8ri5TzFkf3CVg.png" /></figure><p><strong>Figure 1.</strong> Entity Relationship Diagram of the Gym Management database.</p><p>After restoring the database into PostgreSQL, I spent a little time exploring each table and understanding how they were connected. Looking through the relationships first made it much easier to decide where to begin.</p><p>One table immediately caught my attention: <strong>payment</strong>.</p><p>It looked like a straightforward transactional table containing payment amounts, payment methods, payment dates, and the membership plan associated with each payment.</p><p>Naturally, the first question I wanted to answer was:</p><p><strong>Which payments are the highest within each membership plan?</strong></p><p>Finding the maximum payment is easy enough using MAX().</p><p>Ranking every payment while still displaying every record is where the query starts becoming more interesting.</p><p>That turned out to be the perfect introduction to one of PostgreSQL’s most useful analytical features.</p><p><strong>Window Functions</strong></p><p>When I first started learning SQL, I had a habit of solving ranking problems with nested subqueries. They worked, but they were rarely enjoyable to read a few weeks later.</p><p>Looking at the <strong>payment</strong> table, my initial instinct was exactly the same. I started thinking about subqueries, self joins, and temporary result sets before reminding myself that PostgreSQL already has a feature designed specifically for this type of analysis.</p><p><strong>Window Functions</strong></p><p>For this example, I wanted to rank payment amounts within each membership plan while keeping every payment record visible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*f3bT1QZk6_dS96IOnLyxUQ.jpeg" /></figure><p>At first glance, the query looks similar to a regular ranking query, but the OVER() clause changes everything.</p><p>PARTITION BY divides the data into separate groups based on the membership plan. Instead of calculating one ranking across the entire table, PostgreSQL creates an independent ranking for each plan.</p><p>Within every partition, ORDER BY payment_amt DESC sorts the payments from highest to lowest before assigning the rankings.</p><p>The important detail is what <strong>doesn’t</strong> happen.</p><p>No rows disappear.</p><p>Every payment record remains in the result while PostgreSQL adds an additional column containing the ranking.</p><p>That’s a very different way of thinking compared to GROUP BY.</p><p>GROUP BY summarizes data by combining rows.</p><p>Window Functions analyze data while preserving the original rows.</p><p>That distinction completely changed how I approached analytical SQL.</p><p><strong>Result:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*0DF9O1Y-8bIGMJ_6m_KqDQ.jpeg" /><figcaption>Instead of receiving one summary row per membership plan, every payment remains visible while PostgreSQL calculates the rankings.</figcaption></figure><p>The first time this clicked for me, I realized I had been reaching for GROUP BY far too often. Many reports don’t actually need summarized data. They need <strong>analytical information added to detailed data</strong>, and that’s exactly where Window Functions shine.</p><p>Once I became comfortable with OVER() and PARTITION BY, several queries that previously relied on nested subqueries became noticeably shorter and much easier to understand.</p><p><strong>Tip:</strong> If your SQL contains multiple subqueries just to calculate rankings, running totals, or moving averages, it’s worth asking whether a Window Function can simplify the solution.</p><p>Ranking the payments answered my first question about the dataset, but it also led to another thought.</p><p>Exploring data is only one side of working with a database.</p><p>Eventually, every system needs to <strong>insert</strong> new data as well.</p><p>The next table I explored was <strong>members</strong>, and that naturally introduced another PostgreSQL feature that has been around for years but is often overlooked: <strong>Stored Procedures</strong>.</p><p><strong>Stored Procedures</strong></p><p>The <strong>payment</strong> table answered my first reporting question, but as I continued exploring the dataset, I realized I had spent all my time reading data.</p><p>Eventually, every database needs to write data as well.</p><p>The <strong>members</strong> table was the obvious place to continue. At first glance, registering a new member looked simple enough. It’s just an INSERT statement with a handful of columns.</p><p>Or at least that’s how it starts.</p><p>The more I thought about it, the more I realized that inserting a member isn’t something that happens in only one place. A gym could have a website where new members register online, a mobile application for existing customers, an administrative portal used by staff, and a reception system at the front desk.</p><p>If every application contains its own version of the same INSERT statement, keeping them synchronized becomes difficult over time. A small change to the registration process suddenly needs to be updated in multiple places.</p><p>That’s exactly the kind of problem Stored Procedures were designed to solve.</p><p>Instead of repeating the SQL everywhere, PostgreSQL allows us to place the logic inside the database and call it whenever it’s needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*f9eju1DSx_tGGS6rYkEvEQ.png" /></figure><p>Once the procedure has been created, adding a member becomes much simpler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*4TcpN8wEBKYLJzLdgiK72w.png" /></figure><p>simply calls the procedure and passes the required values.</p><p>That’s a subtle change, but an important one.</p><p>This example only inserts a single row, so the benefit might not seem obvious yet. Production systems, however, rarely stop there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*KgoVNS_xaYusuHZaAcEanQ.png" /></figure><p>A registration process often grows over time. It might validate phone numbers, prevent duplicate registrations, generate membership IDs, create the first payment record, update audit tables, or perform all of those operations inside a single transaction.</p><p>When that logic lives inside a stored procedure, every application automatically follows the same business rules.</p><p><strong>Recursive Queries</strong></p><p>Ask someone for an example of a recursive query, and there’s a good chance they’ll show an employee hierarchy.</p><p>There’s nothing wrong with that example, but after seeing it so many times, I wanted to find a use case that felt more practical for this dataset.</p><p>The Gym Management database doesn’t contain managers or reporting structures.</p><p>What it does contain is member registration dates.</p><p>That raised a simple question.</p><p><strong>How many members joined each month?</strong></p><p>The query itself wasn’t difficult.</p><p>The challenge was generating a complete list of months.</p><p>Without a calendar table, months with no registrations would simply disappear from the report.</p><p>Fortunately, PostgreSQL can generate that list dynamically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*ylyV-f6bkZZxLs11wW2sjQ.png" /></figure><p>The query starts with a single row representing January.</p><p>From there, PostgreSQL repeatedly adds one month until it reaches December.</p><p>Jan</p><p>↓</p><p>Feb</p><p>↓</p><p>Mar</p><p>↓</p><p>Apr</p><p>↓</p><p>…</p><p>↓</p><p>Dec</p><p>I like this example because the recursion is easy to visualize.</p><p>Each new month is generated from the previous month, and the process stops once the ending condition is reached.</p><p>Generating the months was only the first step.</p><p>The next task was combining those months with the <strong>members</strong> table.</p><p>By this point, the monthly registration report was complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*CEkrXezou-o0WC_xLI2FDA.jpeg" /></figure><p><strong>Crosstabs</strong></p><p>By this point, the monthly registration report was doing exactly what I wanted.</p><p>It showed how many members joined each month, included months with no registrations, and the SQL was much cleaner than I expected when I first started exploring the dataset.</p><p>There was just one problem.</p><p>The report still looked like transactional data.</p><p>Gym Month Members</p><p>— — — — — — — — — — — -</p><p>1010 Jan 12</p><p>1010 Feb 15</p><p>1010 Mar 18</p><p>1020 Jan 8</p><p>1020 Feb 11</p><p>1020 Mar 13</p><p>From a database perspective, this structure is perfect. Each row represents a single observation, making it easy to store, update, and query but from a reporting perspective, not so much.</p><p>If I wanted to compare January, February, and March side by side, I’d probably end up exporting the results into Excel and creating a Pivot Table.</p><p>Then I remembered PostgreSQL already had a feature designed for exactly this purpose is crosstab.</p><p>Before using crosstab(), PostgreSQL requires the tablefunc extension.</p><h4>CREATE EXTENSION IF NOT EXISTS tablefunc;</h4><p>Once the extension is available, transforming the report becomes surprisingly straightforward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*oA_2EmbnCfvJViBb1h6_NQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*AfqF46LxcVqEX-5mwjrz0Q.png" /></figure><p>The difference in the output is immediately obvious.</p><p>Instead of reading down the page, the report becomes much easier to scan horizontally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tFZoZVySHDu_mnoiX90QBA.jpeg" /></figure><p>Seeing the results side by side made it much easier to compare activity across different gym locations.</p><p>What I liked most about this feature is that the transformation happens inside PostgreSQL itself. There was no need to export the data into another tool just to reshape it into a presentation-friendly format.</p><p>If you’ve ever copied SQL results into Excel just to build a Pivot Table, crosstab() can often eliminate that extra step.</p><p>That was probably my biggest takeaway from this section. PostgreSQL isn’t just capable of storing and retrieving data. It also provides features that prepare the data for reporting before it ever leaves the database.</p><p>There’s a good chance PostgreSQL already has a simpler solution waiting for you.</p><p>If you enjoyed this article, I’d love to hear which PostgreSQL feature has made the biggest difference in your own projects.</p><p>Happy querying!</p><p>Article originally from <a href="https://www.numpyninjaacademy.com/post/four-postgresql-features-that-instantly-simplified-my-sql-queries">https://www.numpyninjaacademy.com/post/four-postgresql-features-that-instantly-simplified-my-sql-queries</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a161608cd13" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>