Mastering Data Summarization with SQL Cross Tab (PIVOT) Function:

When dealing with large datasets, especially with categorical data, summarizing insights quickly is key. SQL’s PIVOT function (also known as a cross-tab) transforms rows into columns, helping you spot trends and compare values easily. In this blog, we’ll explore how to use cross-tab functionality in SQL to create clean, analyzable summaries.
The cross tab Query is used to display a single row as column heading for a specific number of rows. This query can be useful in creating reports or reports that group data by multiple columns. This report is similar to pivot tables in excel. The crosstab query may be combined with a GroupBy clause to obtain the same result.
A cross tab (short for cross-tabulation) is used in data pulling and analysis to summarize and analyze relationships between two or more categorical variables. It creates a matrix (table) where Rows represent one category. Columns represent another category, Cells show aggregated values like counts, sums, averages, etc.
Visualizing Patient Data with SQL Crosstab (PIVOT): MS Type vs. COVID Status

When analyzing medical data, it’s often useful to compare multiple categories side by side.
One powerful way to do this in SQL is using a cross-tab (or PIVOT). In this blog, we’ll create a crosstab to show how many patients with different types of Multiple Sclerosis (MS) were diagnosed or not diagnosed with COVID-19.
Problem Statement: Using crosstab to Analyze MS Type vs. COVID Diagnosis
Analyzing how different types of Multiple Sclerosis (MS) correlate with COVID-19 diagnosis can uncover important clinical insights. PostgreSQL offers a powerful tool called crosstab() — part of the tablefunction extension — that allows you to pivot categorical data into a tabular summary for easy comparison.
In this example, we’ll use data from a medical dataset that includes patient details, MS classification, and COVID diagnosis status.
⦁ how COVID diagnosis status (Diagnosed, Not Diagnosed) as rows
⦁ Show MS types as columns
⦁ Show count of patients in each combination
code:
SELECT * FROM crosstab(
$$SELECT
cd.covid19_diagnosis,
pd.ms_type2,
COUNT(*)
FROM covid_details cd
JOIN patient_details pd ON cd.patient_id = pd.patient_id
GROUP BY cd.covid19_diagnosis, pd.ms_type2
ORDER BY cd.covid19_diagnosis, pd.ms_type2$$,
$$SELECT DISTINCT ms_type2 FROM patient_details ORDER BY ms_type2$$
) AS ct (
covid_status TEXT,
“Progressive MS” INT,
“Relapsing Remitting” INT,
“Other” INT
);
Table1 :covid_detals:

Table2 : patient_details:

Crosstab:TAble

Understanding the relationship between different types of Multiple Sclerosis (MS) and COVID-19 diagnosis can provide valuable clinical insights. we can transform categorical medical data into a clear and interpretable tabular format. In this analysis, we used a dataset containing patient details, MS classifications, and COVID-19 diagnosis status. Our goal was to explore how the distribution of MS types, such as Progressive MS, Relapsing Remitting MS, and Other, varies between patients who were diagnosed with COVID-19 and those who were not. Using SQL, we first aggregated patient counts by combining COVID diagnosis status with MS types through a GROUP BY clause. We then passed this data into the crosstab() function to pivot the MS types into columns, with COVID-19 diagnosis status as row labels. The result is a clean, comparative table showing the number of patients in each MS category across both diagnosed and non-diagnosed groups. This method not only simplifies data exploration but also highlights patterns that may support medical decision-making or further research into how chronic neurological conditions interact with infectious diseases like COVID-19.
Data Sources Used
⦁ covid_details: contains patient_id and COVID diagnosis status (covid_status)
⦁ patient_details: contains patient_id and MS type (ms_type2)
⦁ These two tables are joined on the patient_id field.
⦁ The second SQL block defines the order and values of the MS types (the pivoted columns). These must match the labels and number of output columns in the AS ct(…) part.
⦁ First column as the row label: covid_status
⦁ Remaining columns as the expected MS types: “Progressive MS”, “Relapsing Remitting”, and “Other”.
Conclusion:
The crosstab() function is an essential tool in PostgreSQL when working with categorical healthcare data. It allows analysts to convert normalized records into insightful, matrix-style views for easier pattern recognition.
In this example, pivoting COVID diagnosis against MS types reveals how each group is affected, which is crucial in clinical planning and public health research. Such analysis helps bridge the gap between raw data and decision-making by transforming tables into intuitive summaries.
Whether you’re tracking disease outcomes or exploring demographic trends, mastering crosstab() can significantly level up your data analysis workflow.


