<?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 Cavid Shamil on Medium]]></title>
        <description><![CDATA[Stories by Cavid Shamil on Medium]]></description>
        <link>https://medium.com/@samilov.cavid2003?source=rss-2195d9f5d948------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MQAoGiA9BKIWpbZj</url>
            <title>Stories by Cavid Shamil on Medium</title>
            <link>https://medium.com/@samilov.cavid2003?source=rss-2195d9f5d948------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:33:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samilov.cavid2003/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SQL for Data Analysts: Distribution Functions]]></title>
            <link>https://medium.com/@samilov.cavid2003/sql-for-data-analysts-distribution-functions-8d28dd018180?source=rss-2195d9f5d948------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d28dd018180</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Cavid Shamil]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 10:15:10 GMT</pubDate>
            <atom:updated>2026-10-27T10:01:10.739Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kb7df0h3j30bl7msLRu5uQ.png" /></figure><p>In the last article, we talked about <a href="https://medium.com/@samilov.cavid2003/sql-for-data-analysts-value-offset-functions-0718be76b1a1">Value / Offset Functions</a>. Today, we will continue our SQL series with Distribution Functions used as window functions.</p><p>There are 4 main Distribution Functions and Percentile Functions: CUME_DIST(), PERCENT_RANK(), PERCENTILE_CONT(), PERCENTILE_DISC().</p><h4>CUME_DIST()</h4><p>The CUME_DIST() function calculates the cumulative distribution of a value within a result set. It returns the proportion of rows with values less than or equal to the current row&#39;s value, based on the specified order.</p><p>The result is a value greater than 0 and less than or equal to 1.</p><pre>CUME_DIST() OVER (<br>    [PARTITION BY column_name, ...]<br>    ORDER BY column_name [ASC | DESC]<br>)</pre><p>Let’s do a few examples. We are going to use <a href="https://www.kaggle.com/datasets/rohitsahoo/sales-forecasting">the Superstore dataset</a> for our examples.</p><p><strong>Task 1:</strong> Using the train table, calculate the cumulative distribution of Sales for each row. Order the results by Sales in ascending order. Display Product_Name, Sales, and the calculated cumulative distribution.</p><pre>select product_name,<br>sales,<br>cast(round(cume_dist() over (order by sales asc), 2) as decimal(10,2)) as  cumulative_distribution<br>from train</pre><p>Explanation: The CUME_DIST() function calculates the cumulative distribution of each row based on Sales in ascending order. ROUND() rounds the result to two decimal places, while CAST() converts it to DECIMAL(10,2) for consistent formatting.</p><p><strong>Task 2:</strong> Using the train table, calculate the cumulative distribution of Sales separately for each Category. Order the rows by Sales in ascending order. Display Category, Product_Name, Sales, and the cumulative distribution rounded to three decimal places.</p><pre>select category,<br>product_name,<br>sales,<br>cast(round(cume_dist() over (partition by category order by sales asc), 2) as decimal(10,2)) as  cumulative_distribution<br>from train</pre><p>Explanation: The PARTITION BY Category clause divides the data into separate categories, allowing CUME_DIST() to calculate the cumulative distribution independently within each category. ORDER BY Sales ASC sorts sales from lowest to highest within each category. ROUND() and CAST() format the result to two decimal places.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*84kvG-LuOQ_8Tbc1J7LaUQ.png" /><figcaption>For example, in the row Furniture | Hon 5100 Series Wood Tables | 698352.00 | 0.92, the value 0.92 means that 92% of the rows in the Furniture category have a Sales value less than or equal to 698,352.00.</figcaption></figure><h4>PERCENT_RANK()</h4><p>The PERCENT_RANK() function calculates the relative rank of a row within a result set. It returns a value between 0 and 1 based on the row&#39;s rank.</p><p>A result of 0 represents the first rank, while 1 represents the highest rank.</p><pre>PERCENT_RANK() OVER (<br>    [PARTITION BY column_name, ...]<br>    ORDER BY column_name [ASC | DESC]<br>)</pre><p><strong>Task 1:</strong> Using the train table, calculate the relative rank of each row based on Sales in ascending order. Display Product_Name, Sales, and the calculated PERCENT_RANK() rounded to two decimal places.</p><pre>select <br>product_name,<br>sales,<br>cast(round(percent_rank() over ( order by sales ), 2) as decimal(10,2)) as percent_rank<br>from train</pre><p>Explanation: The PERCENT_RANK() function calculates the relative rank of each row based on Sales in ascending order.</p><p><strong>Task 2: </strong>Using the train table, assign a rank to each row based on Sales in ascending order within each Category. Calculate the total number of rows in each category and the PERCENT_RANK() for each row. Display Category, Product_Name, Sales, Rank_Number, Category_Row_Count, and Percent_Rank. Round Percent_Rank to two decimal places.</p><pre>select Category,<br>product_name,<br>sales,<br>rank() over ( partition by category order by sales asc) as Rank_Number,<br>COUNT(*) OVER (PARTITION BY Category) as Category_Row_Count,<br>cast(round(percent_rank() over ( partition by category order by sales asc), 2) as decimal(10,2)) as percent_rank<br>from train</pre><p>Explanation: The RANK() function assigns a rank to each row based on Sales in ascending order within each category. The COUNT(*) window function calculates the total number of rows in each category without grouping the results into a single row per category. The PERCENT_RANK() function calculates the relative rank of each row within its category, returning a value between 0 and 1. The PARTITION BY Category clause ensures that all three calculations are performed separately for each category. Finally, ROUND() rounds the PERCENT_RANK() result to two decimal places, while CAST() converts it to DECIMAL(10,2) for consistent formatting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*vQTNPc1v9BBy0mD_J3LiAw.png" /></figure><h4>PERCENT_RANK() vs. CUME_DIST()</h4><p>Both PERCENT_RANK() and CUME_DIST() return values between 0 and 1, but they measure different things.</p><ul><li>PERCENT_RANK() shows a row&#39;s relative rank within the result set. It is calculated using the row&#39;s rank and the total number of rows.</li><li>CUME_DIST() shows the proportion of rows with values less than or equal to the current row&#39;s value.</li></ul><p>In simple terms, PERCENT_RANK() tells us where a row stands in the ranking, while CUME_DIST() tells us what proportion of rows have values at or below that row&#39;s value.</p><h3>PERCENTILE_CONT() and PERCENTILE_DISC()</h3><p>PERCENTILE_CONT() calculates a percentile within an ordered set of values. It uses linear interpolation to determine the percentile, so the result may be a value that does not exist in the original data.</p><p>For example, the 50th percentile represents the median. If the required percentile falls between two values, the function can calculate a value between them.</p><pre>PERCENTILE_CONT(numeric_literal)<br>WITHIN GROUP (<br>    ORDER BY order_by_expression [ASC | DESC]<br>)<br>OVER (<br>    [PARTITION BY partition_expression, ...]<br>)</pre><p>PERCENTILE_DISC() returns a percentile based on the actual values in the ordered data set. Unlike PERCENTILE_CONT(), it does not calculate an interpolated value. Instead, it returns a value that exists in the data.</p><pre>PERCENTILE_DISC(numeric_literal)<br>WITHIN GROUP (<br>    ORDER BY order_by_expression [ASC | DESC]<br>)<br>OVER (<br>    [PARTITION BY partition_expression, ...]<br>)</pre><p><strong>Task: </strong>Using the train table, calculate the 50th percentile (median) of Sales for each Category using both PERCENTILE_CONT() and PERCENTILE_DISC(). Display Category, Product_Name, Sales, Continuous_Median, and Discrete_Median. Compare the results to understand the difference between the two functions.</p><pre>select category,<br>Product_Name,<br>sales,<br>percentile_cont(0.50) within group (order by sales) over (partition by category) as Continuous_Median,<br>percentile_disc(0.50) within group (order by sales) over (partition by category) as Discrete_Median<br>from train</pre><p>Explanation: The PERCENTILE_CONT() function calculates the 50th percentile (median) of Sales within each category using linear interpolation when necessary. The PERCENTILE_DISC() function returns an actual Sales value from the ordered data set. The PARTITION BY Category clause ensures that the median is calculated separately for each category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*T6MGw87ZmzLvjnzdew55Xg.png" /><figcaption>For the Furniture category, PERCENTILE_CONT() returns a median Sales value of 43,904, while PERCENTILE_DISC() returns 43,872, an actual value from the ordered data set.</figcaption></figure><h3>Conclusion</h3><p>In this article, we explored four SQL distribution and percentile functions: CUME_DIST(), PERCENT_RANK(), PERCENTILE_CONT(), and PERCENTILE_DISC().</p><p>We learned how CUME_DIST() calculates the cumulative distribution of values and how PERCENT_RANK() shows the relative rank of each row within a result set. We also compared PERCENTILE_CONT() and PERCENTILE_DISC() to understand how they calculate percentiles differently: one can interpolate between values, while the other returns an actual value from the data.</p><p>These functions help data analysts understand data distribution, compare relative positions, and identify important statistical measures such as the median. Combined with other SQL window functions, they provide useful tools for deeper data analysis and better business insights.</p><p>You can find all the code examples and complete queries for these Distribution Functions on my <a href="https://github.com/cavid-shamilov/sql-window-functions-superstore-analytics"><strong>GitHub repositor</strong></a><strong>y</strong>.</p><p><strong>Thanks For Reading.</strong></p><p><strong>Let’s Connect!</strong></p><p><a href="https://www.linkedin.com/in/cavid-shamilov/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BTjypgAsOQvyFmfdbEjNlkg%3D%3D"><strong>LinkedIn</strong></a></p><p><a href="https://github.com/cavid-shamilov"><strong>GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d28dd018180" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL for Data Analysts: Value / Offset Functions]]></title>
            <link>https://medium.com/@samilov.cavid2003/sql-for-data-analysts-value-offset-functions-0718be76b1a1?source=rss-2195d9f5d948------2</link>
            <guid isPermaLink="false">https://medium.com/p/0718be76b1a1</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql-server]]></category>
            <dc:creator><![CDATA[Cavid Shamil]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 10:43:41 GMT</pubDate>
            <atom:updated>2026-10-25T10:43:41.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LrcFJs-Z1Rj4xCrvnnrs_Q.png" /></figure><p>In the last article, we talked about <a href="https://medium.com/@samilov.cavid2003/sql-for-data-analysts-aggregate-functions-a7dbb0f209dd">Aggregate Functions</a>. Today, we continue our SQL series with Value / Offset Functions used as window functions.</p><p>There are 4 main value / offset functions: LAG(), LEAD(), FIRST_VALUE(), LAST_VALUE().</p><h4><strong>LAG() Function</strong></h4><p>The LAG() function is a window function that allows you to access data from a previous row within the same result set without using a self-join. It is extremely useful for comparing a current row&#39;s value with a previous row&#39;s value—such as calculating day-over-day or month-over-month sales growth.</p><pre>LAG(column_name, [offset], [default_value]) <br>OVER (<br>    [PARTITION BY partition_column]<br>    ORDER BY sort_column<br>)</pre><ul><li>column_name: The column from which you want to retrieve the value of a previous row.</li><li>offset : The number of rows back from the current row you want to look. The default is 1. → optional</li><li>default_value: The value returned if the offset goes beyond the partition boundary. The default is NULL. → optional</li><li>PARTITION BY : Divides the data into partitions (groups) so that the LAG() function applies independently to each group. → optional</li><li>ORDER BY: Specifies the logical order of the rows within each partition before the function is evaluated. → required</li></ul><p>Let’s do a few examples. We are going to use <a href="https://www.kaggle.com/datasets/rohitsahoo/sales-forecasting">the Superstore dataset</a> for our examples.</p><p>Task: Write a SQL query to analyze the daily sales performance for the “Technology” category.</p><p>Specifically, calculate the total sales for each order date (Order_Date) within the &quot;Technology&quot; category, and display the previous day&#39;s sales along with the sales difference (Current Day Sales - Previous Day Sales).</p><pre>with Sales as (<br>select category,<br>order_date,<br>sum(sales) as [Total Sales]<br>from train<br>where category=&#39;Technology&#39;<br>group by category,Order_Date<br>)<br>select Category,<br>Order_Date,<br>[Total Sales],<br>lag([Total Sales], 1, 0) over (order by Order_date)<br>from sales</pre><p><strong>Explanation:</strong> First, we use a Common Table Expression (CTE) named Sales to aggregate the total sales for the &quot;Technology&quot; category by Order_Date. Then, in the main query, we apply the LAG() function over the ordered dates to retrieve the total sales of the previous order date. Subtracting the previous sales from the current sales gives us the net difference in performance between consecutive sales days.</p><h4>LEAD() Function</h4><p>The LEAD() function is the exact opposite of LAG(). While LAG() looks backward at previous rows, LEAD() allows you to access data from a subsequent (future) row within the same result set without performing a self-join. It is particularly useful when you want to compare current values against upcoming targets, future sales, or next order dates.</p><pre>LEAD(column_name, [offset], [default_value]) <br>OVER (<br>    [PARTITION BY partition_column]<br>    ORDER BY sort_column<br>)</pre><p>Task: Write a SQL query to compare each customer’s order date with their next order date.</p><p>Specifically, find the date of the next order for each customer (Customer_ID) and calculate the difference in days between the current order date (Order_Date) and the next order date.</p><pre>with Sales as (<br>select customer_id,<br>customer_name,<br>order_date,<br>sum(sales) as [Total Sales]<br>from train<br>group by Customer_ID,customer_name,Order_Date<br>)<br>select Customer_ID,<br>Customer_Name,<br>Order_Date,<br>[Total Sales],<br>lead(Order_Date, 1) over (partition by customer_id order by Order_date) as Next_Order_Date,<br>datediff(day, Order_Date, lead(Order_Date, 1) over (partition by customer_id order by Order_date)) as  Days_Between_Orders<br>from sales</pre><p><strong>Explanation: </strong>In this query, we first aggregate sales by customer and order date within the CustomerOrders CTE. In the main query, we use the LEAD() function partitioned by Customer_ID and ordered by Order_Date to fetch each customer&#39;s subsequent order date. Finally, we apply DATEDIFF() to calculate the exact number of days that passed between the current purchase and the next purchase for each customer.</p><h4>FIRST_VALUE() Function</h4><p>The FIRST_VALUE() function is a window function that returns the first value in an ordered set of values within a specified partition. It is useful when you want to compare every row in a group against the very first record of that group—for example, comparing all sales of a customer against their initial purchase amount or initial order date.</p><pre>FIRST_VALUE(column_name) <br>OVER (<br>    [PARTITION BY partition_column]<br>    ORDER BY sort_column<br>    [rows_or_range_clause]<br>)</pre><p>Task: Write a SQL query to compare each customer’s order sales with their very first order sales amount.</p><p>Specifically, for each customer (Customer_ID), retrieve their first ever sales amount (First_Order_Sales).</p><pre>with Sales as (<br>select customer_id,<br>customer_name,<br>order_date,<br>sum(sales) as [Total Sales]<br>from train<br>group by Customer_ID,customer_name,Order_Date<br>)<br>select Customer_ID,<br>Customer_Name,<br>Order_Date,<br>[Total Sales],<br>FIRST_VALUE([Total Sales]) over (partition by customer_id order by order_date) as First_Order_Sales<br>from sales</pre><p>Explanation: In this query, we first aggregate the sales data at the customer and order date level using a CTE. Then, in the main query, we use the FIRST_VALUE() window function partitioned by Customer_ID and ordered by Order_Date. This allows us to look at each customer&#39;s timeline and retrieve the exact sales amount from their very first order across all subsequent rows.</p><h4>LAST_VALUE() Function</h4><p>The LAST_VALUE() function returns the last value in an ordered set of values within a specified partition. However, unlike FIRST_VALUE(), when using LAST_VALUE() with ORDER BY, SQL Server sets a default window frame (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW). To ensure LAST_VALUE() evaluates all rows up to the end of the partition, you must explicitly specify the frame ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.</p><pre>LAST_VALUE(column_name) <br>OVER (<br>    [PARTITION BY partition_column]<br>    ORDER BY sort_column<br>    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING<br>)</pre><p>ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING: Ensures the window frame covers the entire partition from start to end so that the true last value is returned.</p><p>Task: Write a SQL query to display each customer’s order sales alongside the total sales amount from their most recent (latest) order.</p><p>Specifically, for each customer (Customer_ID), retrieve the sales amount of their last order date (Latest_Order_Sales).</p><pre>with Sales as (<br>select customer_id,<br>customer_name,<br>order_date,<br>sum(sales) as [Total Sales]<br>from train<br>group by Customer_ID,customer_name,Order_Date<br>)<br>select Customer_ID,<br>Customer_Name,<br>Order_Date,<br>[Total Sales],<br>last_value([Total Sales]) over (partition by customer_id order by order_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as Latest_Order_Sales<br>from sales</pre><p>Explanation:<strong> </strong>In this final query, we use the LAST_VALUE() window function along with the explicit frame clause ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING. This frame ensures that the window looks across the entire partition from start to finish. As a result, for every row associated with a customer, we can accurately retrieve the exact sales amount of their very last order.</p><p>In this article, we covered the core SQL Value / Offset Functions: LAG(), LEAD(), FIRST_VALUE(), LAST_VALUE() .In the next part, we will explore Analytic Distribution Functions with windowing! You can find all the code examples and complete queries for these Value / Offset Functions on my <a href="https://github.com/cavid-shamilov/sql-window-functions-superstore-analytics"><strong>GitHub repositor</strong></a><strong>y</strong>.</p><p><strong>Thanks For Reading.</strong></p><p><strong>Let’s Connect!</strong></p><p><a href="https://www.linkedin.com/in/cavid-shamilov/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BTjypgAsOQvyFmfdbEjNlkg%3D%3D"><strong>LinkedIn</strong></a></p><p><a href="https://github.com/cavid-shamilov"><strong>GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0718be76b1a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL for Data Analysts: Aggregate Functions]]></title>
            <link>https://medium.com/@samilov.cavid2003/sql-for-data-analysts-aggregate-functions-a7dbb0f209dd?source=rss-2195d9f5d948------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7dbb0f209dd</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Cavid Shamil]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 13:08:16 GMT</pubDate>
            <atom:updated>2026-10-25T10:39:24.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eegYcS_i3863ec51ATo_QQ.png" /></figure><p>In the last article, we talked about Ranking Functions. Today, we continue our SQL series with Aggregate Functions used as window functions.</p><p>There are 5 main aggregate functions: SUM(), COUNT(), AVG(), MIN(), and MAX().</p><p>Aggregate window functions perform calculations across a set of rows related to the current row, without collapsing the rows into a single summary output. Unlike standard GROUP BY aggregations, windowed aggregate functions keep the detail of every row while adding calculated values alongside them.</p><p>Let’s do a few examples. We are going to use <a href="https://www.kaggle.com/datasets/rohitsahoo/sales-forecasting">the Superstore dataset</a> for our examples.</p><p><strong>Sum().</strong></p><p><strong>Task 1.</strong></p><p>Business Purpose: Track a customer’s lifetime value by calculating their cumulative spending day-by-day.</p><p>Calculate the total daily sales for each customer (Customer_Name) on each order date (Order_Date), and then calculate the running cumulative total (SUM()) of their sales over time.</p><pre>with customer_daily_sales as (<br>select Customer_Name,<br>Order_Date,<br>sum(sales) as Daily_sales <br>from train<br>group by Customer_Name,Order_Date<br>)<br>select Customer_Name,order_date,<br>daily_sales,<br>sum(Daily_sales) over(partition by customer_name order by order_date) as Running_Total<br>from customer_daily_sales</pre><p><strong>Code Explanation:</strong></p><p>CTE (CustomerDailySales): We first aggregate the raw transaction data using GROUP BY Customer_Name, Order_Date to calculate each customer&#39;s total spending per day (Daily_Sales).</p><p>Window Function (SUM() OVER): We then apply SUM(Daily_Sales) OVER (PARTITION BY Customer_Name ORDER BY Order_Date) to compute the running cumulative spending for each customer over time.</p><p><strong>Task 2.</strong></p><p>Identify orders where a customer’s purchase exceeds 30% of their total overall spending across all their orders.</p><ul><li>Calculate the overall total spending for each customer using SUM(Sales) OVER (PARTITION BY Customer_Name).</li><li>Compare each individual order amount (Sales) against that customer&#39;s total spending.</li><li>Filter the results to show only orders where Sales &gt; 0.30 * Total_Customer_Sales.</li></ul><pre>with CustomerTotalSales as (<br>select<br>Customer_Name,<br>Order_Date,<br>Sales,<br>sum(Sales) Over (partition by Customer_Name) as Total_Customer_Sales<br>from train<br>)<br>select<br>Customer_Name,<br>Order_Date,<br>Sales,<br>Total_Customer_Sales,<br>cast(round((Sales * 100.0 / Total_Customer_Sales), 2) as decimal(10,2)) as Sales_Percentage<br>from CustomerTotalSales<br>where Sales &gt; 0.30 * Total_Customer_Sales</pre><p><strong>Count()</strong></p><p><strong>Task 1.</strong></p><p>Business Purpose: Identify how frequently each customer makes purchases across the dataset.</p><p>For each order row, calculate the total number of orders (COUNT(*)) placed by each customer (Customer_Name).</p><pre>with UniqueOrders as (<br>select distinct<br>Customer_Name, <br>Order_ID<br>from train<br>)<br>select <br>Customer_Name,<br>Order_ID,<br>count(Order_ID) over(partition by Customer_Name) as Total_Orders_Per_Customer<br>from UniqueOrders;</pre><p>Since SQL Server does not support COUNT(DISTINCT) directly inside a window function, we use a two-step approach:</p><ul><li>CTE (UniqueOrders): Filters out duplicate product rows by getting distinct Order_ID entries per customer.</li><li>Window Function (COUNT() OVER): Counts the unique orders for each customer while retaining individual order rows in the output.</li></ul><p><strong>Task 2.</strong></p><p>Business Purpose<strong>:</strong> Identify and analyze orders made by high-frequency customers (customers who have placed more than a specific threshold of unique orders, e.g., more than 5).</p><ul><li>Calculate the total unique order count for each customer using a window function.</li><li>Filter the dataset to keep only the customers who have placed strictly more than 5 unique orders.</li></ul><pre>with UniqueOrders as (<br>select distinct<br>Customer_Name, <br>Order_ID<br>from train<br>),<br>Total_orders as (<br>select <br>Customer_Name,<br>Order_ID,<br>count(Order_ID) over(partition by Customer_Name) as Total_Orders_Per_Customer<br>from UniqueOrders<br>)<br>select <br>Customer_Name,<br>Order_ID,<br>Total_Orders_Per_Customer<br>from Total_orders<br>where Total_Orders_Per_Customer&gt;5</pre><p><strong>Code Explanation:</strong></p><ul><li>UniqueOrders CTE: Eliminates duplicate product rows per order, leaving only distinct Order_ID entries per customer.</li><li>TotalOrders CTE: Applies COUNT(Order_ID) OVER (PARTITION BY Customer_Name) to aggregate the true count of unique orders placed by each customer.</li><li>Final Query: Filters the dataset using WHERE Total_Orders_Per_Customer &gt; 5 to isolate high-frequency customers.</li></ul><p><strong>AVG()</strong></p><p><strong>Task.</strong></p><p>Business Purpose: Compare individual order sales against each customer’s overall average purchase amount to identify above-average transactions.</p><p>Calculate the average sales amount (AVG(Sales)) for each customer (Customer_Name) across all their transactions.</p><pre>with CustomerOrderSales as (<br>select customer_name,<br>Order_ID,<br>sum(sales) as Order_Sales<br>from train<br>group by customer_name,order_id<br>)<br>select<br>customer_name,<br>order_sales,<br>cast(round(avg(Order_Sales) over (partition by customer_name), 2) as decimal(10,2)) as Avg_Order_Value<br>from CustomerOrderSales</pre><p><strong>Code Explanation:</strong></p><ul><li>CustomerOrderSales CTE: Aggregates raw data by Customer_Name and Order_ID to find the total sales value for each individual order.</li><li>Window Function (AVG() OVER): Calculates the average order value (AOV) for each customer across all their orders while keeping individual order rows visible.</li><li>Formatting (CAST &amp; ROUND): Rounds the final average to 2 decimal places for clean reporting.</li></ul><p><strong>Min() and Max ()</strong></p><p><strong>Task.</strong></p><p>Business Purpose: Identify each customer’s largest (maximum) single order value to understand their highest spending peak.</p><p>For each customer, find the maximum order amount (MAX()) across all their orders.</p><pre>with CustomerOrderSales as (<br>select customer_name,<br>Order_ID,<br>sum(sales) as Order_Sales<br>from train<br>group by customer_name,order_id<br>)<br>select<br>customer_name,<br>order_sales,<br>max(Order_Sales) over (partition by customer_name) as Max_Order_Value<br>from CustomerOrderSales</pre><p>In this article, we covered the core SQL Aggregate Functions: SUM(), COUNT(), AVG(), MIN(), and MAX() .In the next part, we will explore Value / Offset Functions with windowing! You can find all the code examples and complete queries for these Aggregate Functions on my <a href="https://github.com/cavid-shamilov/sql-window-functions-superstore-analytics"><strong>GitHub repositor</strong></a><strong>y</strong>.</p><p><strong>Thanks For Reading.</strong></p><p><strong>Let’s Connect!</strong></p><p><a href="https://www.linkedin.com/in/cavid-shamilov/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BTjypgAsOQvyFmfdbEjNlkg%3D%3D"><strong>LinkedIn</strong></a></p><p><a href="https://github.com/cavid-shamilov"><strong>GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7dbb0f209dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL for Data Analysts: Ranking Functions]]></title>
            <link>https://medium.com/@samilov.cavid2003/sql-for-data-analysts-ranking-functions-8f3f6b195a53?source=rss-2195d9f5d948------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f3f6b195a53</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Cavid Shamil]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 13:55:16 GMT</pubDate>
            <atom:updated>2026-10-23T13:55:16.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxZttTrm9HWjdlbqCwn0vg.png" /></figure><p>Hello! I’m Cavid, an aspiring data analyst. Today, we are starting to study Ranking Functions. We will learn what ranking functions are and look at a few examples.</p><p>Ranking functions assign a sequential integer (rank) to each row within a partition of a result set. They are extremely helpful when we need to order, filter, or categorize our data.</p><p>There are 4 main ranking functio<strong>ns</strong> in SQL Server:</p><p>ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE(N)</p><p><strong>Row_Number()</strong> assigns a unique sequential number to each row, starting from 1. Even if there are duplicate values in the sorting column, Row_Number() still gives each row a distinct, sequential number without ties.</p><pre>SELECT <br>    Column1,<br>    Column2,<br>    ROW_NUMBER() OVER (PARTITION BY partition_column ORDER BY sort_column) AS row_num<br>FROM table_name;</pre><p>Let’s do a few examples. We are going to use <a href="https://www.kaggle.com/datasets/rohitsahoo/sales-forecasting">the Superstore dataset</a> for our examples.</p><ol><li>Suppose we want to rank customers based on their sales amount within each product category. Here is how we can do it using ROW_NUMBER():</li></ol><pre>select Customer_Name,<br>Category,<br>Sales,<br>row_number() over (partition by Category order by Sales desc) as sales_row_num<br>from train</pre><ul><li>Partition by : Divides the dataset into partitions by each product category.</li><li>Order sales desc : Sorts the rows within each category partition from highest sales to lowest.</li><li>Row_number : Assigns a sequential row number starting from 1 for each partition independently</li></ul><p>2. Let’s move on to the next question: Find the top 3 highest sales (Sales) for each region (Region), along with the customer name (Customer_Name). Since window functions like ROW_NUMBER() cannot be used directly inside a Where clause, we need to use a Common Table Expression (CTE) to filter the ranked rows.</p><pre>with Region_Sales as (<br>select <br>region,<br>customer_name,<br>sales,<br>row_number() over (partition by region order by sales desc) as sales_row_number<br>from train<br>)<br><br>select<br>region,customer_name,<br>sales_row_number,<br>Sales<br>from Region_Sales<br>where sales_row_number&lt;=3</pre><p><strong>What is Rank()?</strong></p><p>Rank() assigns a unique rank to each row within a partition. Unlike Row_Number(), if two or more rows have identical values in the ordering column, Rank() assigns them the same rank.</p><p>However, it skips rank numbers after a tie. For example, if two rows tie for 1st place, the next rank will be 3rd (1, 1, 3, 4…).</p><pre>SELECT <br>    Column1,<br>    Column2,<br>    RANK() OVER (PARTITION BY partition_column ORDER BY sort_column) AS rank_num<br>FROM table_name;</pre><p>Okay, the first task from Rank(): Rank the products (Product_name) within each Category based on their total sales amount in descending order using Rank().</p><pre>select <br>Category,<br>Product_Name,<br>sales,<br>rank() over (partition by category order by sales desc) as sales_row_number<br>from train</pre><p>If there are products with identical sales amounts, they will receive the same rank number. For example, if two products share 1st place, the next product will receive a rank of 3.</p><p>The next task for Rank(): Find the top-ranked customer(s) based on total sales for each Region using Rank()<strong>:</strong></p><ol><li>First, calculate the total sales for each customer in each region.</li><li>Then, rank the customers within each region based on their total sales in descending order.</li><li>Filter the results to show only the top-ranked customer(s) (rank = 1) for each region.</li></ol><pre>with Customer_Totals as (<br><br>select region,<br>Customer_Name,<br>sum(sales) as Total_Sales,<br>rank() over(partition by region order by sum(sales) desc) as Sales_Rank<br>from train<br>group by Region,Customer_Name<br>)<br><br>select<br>region,<br>customer_name,<br>Total_Sales,<br>Sales_Rank<br>from Customer_Totals<br>where Sales_Rank=1</pre><p><strong>DENSE_RANK()</strong> assigns a rank to each row within a partition of a result set, similar to RANK().</p><p>The key difference is that DENSE_RANK() does not skip any rank numbers when there are ties. If two or more rows share the same rank, the next row receives the immediate next sequential rank number (e.g., 1, 1, 2, 3...).</p><pre>SELECT <br>    Column1,<br>    Column2,<br>    DENSE_RANK() OVER (PARTITION BY partition_column ORDER BY sort_column) AS dense_rank_num<br>FROM table_name;</pre><p>Task 1<strong>:</strong> Assign a dense rank to each customer (Customer_Name) based on their order sales (Sales) within each product category (Category) using Dense_Rank().</p><pre>select<br>Category,<br>Customer_Name,<br>sales,<br>dense_rank() over( partition by category order by sales desc)<br>from train</pre><p>Task 2: Find the top 3 highest unique sale amounts (Sales) for each product sub-category (Sub_Category) along with the associated product names (Product_Name).</p><p>Why must we use Dense_Rank instead of Row_number or Rank() here? Because if multiple products share the same top sales amount, we want to include all of them without skipping rank numbers or missing distinct top-performing sales tiers.</p><pre> with Total as (<br><br> select Sub_Category,<br> Product_Name,<br> Sales,<br> dense_rank() over(partition by sub_category order by sales desc) as Sales_Rank<br> from train<br> )<br><br> select<br> Sub_Category,<br> Product_Name,<br> Sales,<br> Sales_Rank<br> from Total<br> where Sales_Rank&lt;=3</pre><h3>What is NTILE()?</h3><p>NTILE() is a window function that distributes rows within an ordered partition into a specified number of approximately equal groups or &quot;buckets&quot;.</p><p>It assigns a bucket number (starting from 1 up to $N$) to each row.</p><pre>SELECT <br>    Column1,<br>    Column2,<br>    NTILE(number_of_buckets) OVER (PARTITION BY partition_column ORDER BY sort_column) AS bucket_num<br>FROM table_name;</pre><p>Task 1 : Divide all orders in the train table into 4 equal groups (quartiles) based on their sales amount using NTILE(4).</p><pre>select <br>sales,<br>ntile(4) over( order by sales desc) as Sales_Rank<br>from train</pre><p>Task 2:<strong> </strong>Divide customers into 3 groups (High, Medium, Low spenders) based on their total sales within each Region using NTILE(3).</p><pre>select Region,<br>Customer_Name,<br>sum(sales)as Total_Sales,<br>ntile(3) over(partition by region order by sum(sales) desc) as Sales_Rank<br>from train<br>group by region,Customer_Name</pre><p>In this article, we covered the core SQL Ranking Functions: ROW_NUMBER(), RANK(), DENSE_RANK(), and NTILE(). In the next part, we will explore Aggregate Functions with windowing! You can find all the code examples and complete queries for these ranking functions on my <a href="https://github.com/cavid-shamilov/sql-window-functions-superstore-analytics"><strong>GitHub repositor</strong></a><strong>y</strong>.</p><p><strong>Thanks For Reading.</strong></p><p><strong>Let’s Connect!</strong></p><p><a href="https://www.linkedin.com/in/cavid-shamilov/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BTjypgAsOQvyFmfdbEjNlkg%3D%3D"><strong>LinkedIn</strong></a></p><p><a href="https://github.com/cavid-shamilov"><strong>GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f3f6b195a53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL for Data Analysts: Self and Natural Join]]></title>
            <link>https://medium.com/@samilov.cavid2003/sql-for-data-analysts-self-and-natural-join-97abe9314bb0?source=rss-2195d9f5d948------2</link>
            <guid isPermaLink="false">https://medium.com/p/97abe9314bb0</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Cavid Shamil]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 12:14:53 GMT</pubDate>
            <atom:updated>2026-09-24T12:14:53.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7KU8iZ29vCtKB4Ybt34Yg.png" /></figure><p>Hello! I’m Cavid, an aspiring data analyst. Today, we are going to continue our series on SQL JOINs. <a href="https://medium.com/@samilov.cavid2003/sql-for-data-analysts-full-outer-and-cross-join-with-examples-f93bad202187">In my previous article</a>, We talked about Full Outer and Cross JOIN. In this article, we will dive deeper into Self Join and practice with SQL queries using<a href="https://www.kaggle.com/datasets/shaikhshoeb/adventureworks-dataset-for-data-analysis/data"> the AdventureWorks dataset</a>. We also will talk about Natural Join.</p><p>A Self Join is not a distinct SQL keyword or a special type of join like Left or Right . Instead, it is simply a regular join—usually an Inner Join or Left Join —where a table is joined with itself.</p><p>Why would you want to join a table to itself?</p><p>In real-world databases, tables often contain hierarchical or relational data within the same entity. The classic example is an organization chart where employees and their managers are stored in the very same Employees table. A manager is ultimately just another employee.</p><p>To perform a Self Join, you must use table aliases (e.g., Employees AS Emp and Employees AS Mgr). Aliasing forces SQL to treat the single table as if it were two separate copies, allowing you to compare rows within the same table—such as linking each employee&#39;s ManagerID to their manager&#39;s EmployeeID.</p><h4>Finding Customers with the Same Last Name (SELF JOIN)</h4><p>A Self Join allows us to evaluate relationships between rows inside the very same table. To achieve this, we query the table twice using two distinct aliases (e.g., C1 and C2), treating it as if we were joining two separate tables.</p><p>The marketing team wants to identify potential family members or households within our customer database. We need to query the AdventureWorks_Customers table to find distinct customers who share the exact same LastName.</p><pre>select C1.CustomerKey AS Customer1_ID,<br>C1.FirstName AS Customer1_FirstName,<br>C1.LastName,<br>C2.CustomerKey AS Customer2_ID,<br>C2.FirstName AS Customer2_FirstName<br>from AdventureWorks_Customers as  C1<br>inner join <br>AdventureWorks_Customers as C2<br>on<br>C1.lastname=C2.LastName<br>and <br>C1.CustomerKey &lt; C2.CustomerKey</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*2BZUvY-5VMFokM45xl7xSg.png" /></figure><p>If we used C1.CustomerKey &lt;&gt; C2.CustomerKey, SQL would compare Customer A with Customer B, but it would also compare Customer B with Customer A—resulting in duplicate paired rows. Using the &lt; operator ensures that each customer pair is compared exactly once and prevents a customer from matching with themselves.</p><p>A Natural Join is a type of join that automatically matches columns between two tables based on shared column names and compatible data types. When you execute a Natural Join, SQL implicitly creates an ON condition behind the scenes for every column that exists in both tables.</p><p>Unlike standard joins, you do not need to write an ON clause or specify key columns—SQL handles it for you.</p><p>A Natural Join automatically joins two tables based on all columns that share the exact same name and data type across both tables. While it eliminates the need to write an explicit ON clause, it is widely considered an anti-pattern in professional data engineering and analytics.</p><p>Relying on implicit column matching introduces significant risks to your data pipeline. If a database administrator adds a common metadata column like ModifiedDate or Status to both tables in the future, a Natural Join will silently alter its join logic, unexpectedly returning empty or inaccurate results. Furthermore, explicit join keys make queries self-documenting and easier to debug, whereas a Natural Join masks the underlying table relationships. To top it off, major database systems like Microsoft SQL Server do not support Natural Join syntax at all.</p><p>Understanding how to join a table to itself and knowing when to avoid implicit features like Natural Join marks an important milestone in your SQL journey. Self Join opens up powerful ways to analyze hierarchical data, family structures, and sequential events within a single dataset, while avoiding Natural Join keeps your code robust, predictable, and production-ready.</p><p>By combining these concepts with standard JOIN operations, you now have a versatile set of techniques to tackle complex data analytics challenges with confidence.</p><p>Thanks For Reading.</p><p><strong>Let’s Connect!</strong></p><p><a href="https://www.linkedin.com/in/cavid-shamilov/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BTjypgAsOQvyFmfdbEjNlkg%3D%3D"><strong>LinkedIn</strong></a></p><p><a href="https://github.com/cavid-shamilov"><strong>GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97abe9314bb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL for Data Analysts: Full Outer and Cross Join with Examples]]></title>
            <link>https://medium.com/@samilov.cavid2003/sql-for-data-analysts-full-outer-and-cross-join-with-examples-f93bad202187?source=rss-2195d9f5d948------2</link>
            <guid isPermaLink="false">https://medium.com/p/f93bad202187</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Cavid Shamil]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 18:45:48 GMT</pubDate>
            <atom:updated>2026-09-23T18:45:48.861Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWXikecXgK5tsi4HP0pnnQ.png" /></figure><p>Hello! I’m Cavid, an aspiring data analyst. Today, we are going to continue our series on SQL JOINs. <a href="https://medium.com/@samilov.cavid2003/sql-for-data-analysts-left-and-right-join-with-examples-68c309ae4d85">In my previous article</a>, We talked about LEFT JOIN. As I promised, in this article, we will dive deeper into Full Outer and Cross Join and practice with SQL queries using<a href="https://www.kaggle.com/datasets/shaikhshoeb/adventureworks-dataset-for-data-analysis/data"> the AdventureWorks dataset</a>.</p><p>While an Inner Join returns only matching rows and a Left Join preserves everything from the primary table, a full outer join leaves nobody behind. It combines the functionality of both Left and Right joins, returning all records from both tables regardless of whether a match exists.</p><p>If a row in Table A has a match in Table B, the values are combined. If there is no match on either side, SQL simply fills the missing side with NULL values. In short, Full Outer Join gives you a complete, unfiltered view of the relationships—and gaps—between two datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i-dDjWqXsSAR_wKj" /></figure><p>Unlike all the other JOIN operations we’ve covered so far, a Cross Join does not use a join key (ON clause) to match rows. Instead, it creates a Cartesian<strong> </strong>product by combining every single row from the first table with every single row from the second table.</p><p>If Table A has 10 rows and Table B has 5 rows, a Cross Join will produce exactly 10 x 5 = 50 rows. While this can generate massive datasets if used carelessly, it is an incredibly useful tool when you need to generate all possible combinations of two sets of data—such as pairing every product with every available store location or generating comprehensive reporting matrixes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/0*vhSfB7BvuNfp3TAR" /></figure><p>Let’s practice.</p><p>When analyzing historical data across different periods — such as yearly sales tables — using Inner join or Left Join often leads to missing information: An Inner Join only returns customers who bought products in both years. A Left Join preserves the first year but completely ignores new customers from the second year.</p><p>To get a complete, consolidated view of all customer activity across both years, we use a Full Outer Join.</p><p>The sales strategy team wants a complete list of customer keys who placed an order in 2016, 2017, or both years, ensuring no customer is left out.</p><pre>SELECT AS2016.CustomerKey AS Customers2016,<br>    AS2017.CustomerKey AS Customers2017<br>FROM AdventureWorks_Sales_2016 AS AS2016<br>FULL JOIN AdventureWorks_Sales_2017 AS AS2017<br>ON AS2016.CustomerKey = AS2017.CustomerKey</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*CnKg0_iwMxjyZcga7avIFg.png" /></figure><h4>Isolating Disjoint Sets (Finding Non-Overlapping Records)</h4><p>Sometimes you don’t want the entire consolidated dataset; instead, you specifically want to identify records that exist in one table or the other, but NOT both.</p><p>By combining Full Outer Join with a Where is Null clause, we can effectively filter out all matching records and leave behind only the non-overlapping data points.</p><p>The customer retention team wants to audit customer churn and acquisition. They need a list of customers who ordered in 2016 ONLY (lost customers) or 2017 ONLY (new acquisitions), excluding customers who bought in both years.</p><p>The Full Join pairs up matching records and includes unmatched rows from both sides with Null values. The WHERE AS2016.CustomerKey IS NULL OR AS2017.CustomerKey IS NULL condition drops every row where both keys exist (the overlap), isolating strictly the unique activity from each year.</p><pre>SELECT <br>    AS2016.CustomerKey AS Customer2016,<br>    AS2017.CustomerKey AS Customer2017<br>FROM AdventureWorks_Sales_2016 AS AS2016<br>FULL JOIN AdventureWorks_Sales_2017 AS AS2017<br>    ON AS2016.CustomerKey = AS2017.CustomerKey<br>where AS2016.CustomerKey is null<br>or AS2017.CustomerKey is null</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*3YUiJ2ZwFeSmDj8ZJvGPlg.png" /></figure><h4>Generating All Possible Combinations (CROSS JOIN)</h4><p>Unlike all other join types, a Cross Join does not use a join key (ON clause). Instead, it produces a Cartesian product, pairing every single row from the first table with every single row from the second table.</p><p>This is particularly useful in business scenarios where you need to create a complete coverage grid — such as checking inventory across all stores or setting up product-region matrixes.</p><p>The regional sales strategy team wants to generate a master matrix pairing every product category with every sales territory to identify potential expansion opportunities.</p><pre>select CategoryName,region <br>from AdventureWorks_Product_Categories <br>cross join AdventureWorks_Territories</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*oCGKCbIv8vCNbTVFO3Lu8A.png" /></figure><h3>Common Pitfall: The “INNER JOIN” Trap in Multi-Table FULL JOIN Chains</h3><p>When I was first structuring queries to fetch customer names alongside our consolidated 2016 and 2017 sales data, my initial instinct was to write something like this:</p><pre>-- INCORRECT: <br>SELECT <br>    AC.FirstName,<br>    AC.LastName,<br>    AS2016.CustomerKey AS Customer2016,<br>    AS2017.CustomerKey AS Customer2017<br>FROM AdventureWorks_Sales_2016 AS AS2016<br>FULL JOIN AdventureWorks_Sales_2017 AS AS2017<br>    ON AS2016.CustomerKey = AS2017.CustomerKey<br>INNER JOIN AdventureWorks_Customers AS AC<br>    ON AC.CustomerKey = AS2017.CustomerKey</pre><p>The Full Join successfully preserves customers who ordered only in 2016 (leaving AS2017.CustomerKey as NULL). However, the subsequent Inner Join evaluates AC.CustomerKey = AS2017.CustomerKey. Because an Inner Join filters out NULL values, all 2016-only customers are immediately dropped from the final output.</p><p>To preserve all unmatched records from your Full Join while bringing in customer details, use a Left Join combined with COALESCE:</p><pre>-- CORRECT: <br>SELECT <br>    AC.FirstName,<br>    AC.LastName,<br>    AS2016.CustomerKey AS Customer2016,<br>    AS2017.CustomerKey AS Customer2017<br>FROM AdventureWorks_Sales_2016 AS AS2016<br>FULL JOIN AdventureWorks_Sales_2017 AS AS2017<br>    ON AS2016.CustomerKey = AS2017.CustomerKey<br>LEFT JOIN AdventureWorks_Customers AS AC<br>    ON AC.CustomerKey = COALESCE(AS2016.CustomerKey, AS2017.CustomerKey);</pre><p>Mastering Full Outer and Cross JOINs completes your core SQL JOIN toolkit. Whether you are consolidating messy historical datasets, isolating disjoint customer lists, or generating comprehensive coverage matrices, these operations give you full control over how your data comes together.</p><p><strong>Let’s Connect!</strong></p><p><a href="https://www.linkedin.com/in/cavid-shamilov/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BTjypgAsOQvyFmfdbEjNlkg%3D%3D"><strong>LinkedIn</strong></a></p><p><a href="https://github.com/cavid-shamilov"><strong>GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f93bad202187" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL for Data Analysts: Left and Right Join with Examples]]></title>
            <link>https://medium.com/@samilov.cavid2003/sql-for-data-analysts-left-and-right-join-with-examples-68c309ae4d85?source=rss-2195d9f5d948------2</link>
            <guid isPermaLink="false">https://medium.com/p/68c309ae4d85</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Cavid Shamil]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 14:14:32 GMT</pubDate>
            <atom:updated>2026-09-22T14:14:32.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SmeVdicYW-d0miJ603A6QQ.png" /></figure><p>Hello! I’m Cavid, an aspiring data analyst. Today, we are going to continue our series on SQL JOINs. <a href="https://medium.com/@samilov.cavid2003/sql-for-data-analysts-inner-join-with-examples-8666d31e1ea8">In my previous article</a>, We talked about INNER JOIN. As I promised, in this article, we will dive deeper into LEFT JOIN and practice with SQL queries using<a href="https://www.kaggle.com/datasets/shaikhshoeb/adventureworks-dataset-for-data-analysis/data"> the AdventureWorks dataset</a>.</p><p>While an INNER JOIN returns only the matching rows from both tables, a LEFT JOIN is a bit more generous. It returns all records from the left table, along with the matching records from the right table. If there is no match for a row in the right table, SQL doesn’t leave that row behind — instead, it simply fills the right table’s columns with NULL values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nvdEzggcAs0BRkiE0QstBQ.jpeg" /></figure><p>A RIGHT JOIN (or RIGHT OUTER JOIN) works as the exact mirror image of a LEFT JOIN. Instead of prioritizing the first table, it returns all records from the right table, along with the matching rows from the left table. If a record in the right table has no matching counterpart in the left table, the left table’s columns will display NULL values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzV5KQ8Qk-jlz5lo6iizJQ.jpeg" /></figure><p>In professional data analysis, LEFT JOIN is used much more frequently than RIGHT JOIN. Analysts usually prefer to write queries from left to right because it keeps the code easier to read and maintain. In fact, any RIGHT JOIN query can be easily rewritten as a LEFT JOIN simply by swapping the order of the tables.</p><p>Let’s practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*lxtTQlk5WHNicZZbujSTmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*1yG8MI0YIf4JJYaXmpPWQw.png" /></figure><p>In real-world data analysis, missing links between tables are common. If we use an INNER JOIN, any product without an assigned subcategory would be completely filtered out. However, if we want a complete list of all products regardless of whether they have a subcategory assigned, we use a LEFT JOIN.</p><p>Suppose the inventory team asks for a report of all products along with their respective subcategory names. They explicitly require that products without a subcategory must still appear in the final report:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*I_5Fb7M-uD6dPdRQi234mg.png" /></figure><pre>select ProductName,SubcategoryName<br>from AdventureWorks_Products as AP<br>left join<br>AdventureWorks_Product_Subcategories as APS<br>on <br>AP.ProductSubcategoryKey=APS.ProductSubcategoryKey</pre><p><strong>What if we used a RIGHT JOIN instead?</strong></p><p>If we kept the same table order but swapped LEFT JOIN for RIGHT JOIN, the focus of the query would shift entirely to the right table (AdventureWorks_Product_Subcategories):</p><pre>select ProductName,SubcategoryName<br>from AdventureWorks_Products as AP<br>right join<br>AdventureWorks_Product_Subcategories as APS<br>on <br>AP.ProductSubcategoryKey=APS.ProductSubcategoryKey</pre><p>Swapping LEFT JOIN for RIGHT JOIN in this setup shifts the query&#39;s primary focus to the subcategories table, guaranteeing that every single subcategory is displayed even if it contains no products (returning NULL for the product name), while completely dropping any products that lack a subcategory assignment. In short, LEFT JOIN asks &quot;Show me all products and their subcategories if they exist&quot;, whereas RIGHT JOIN flips the perspective to &quot;Show me all subcategories and any products attached to them&quot;.</p><h3><strong>Identifying Inactive Records (LEFT JOIN + IS NULL)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*bSny5TCvOLPGtOXcfewlHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*hVxfOCTVhHU613JTilBaoA.png" /></figure><p>A powerful and extremely common use case for LEFT JOIN in business analytics is identifying &quot;missing&quot; or &quot;inactive&quot; records—such as products that have never been sold, or customers who haven&#39;t made a purchase.</p><p>The marketing team wants to launch a re-engagement campaign targeting customers who registered but did not make any purchases in 2017.</p><p>To find these inactive customers, we perform a LEFT JOIN from the AdventureWorks_Customers table to the AdventureWorks_Sales_2017 table, and then filter for rows where the sales record is NULL.</p><pre>select firstname,LastName,EmailAddress<br>from AdventureWorks_Customers as AC<br>left join<br>AdventureWorks_Sales_2017 as AS2017<br>on <br>AC.CustomerKey=AS2017.CustomerKey<br>WHERE AS2017.CustomerKey IS NULL</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*GTDib3mq7o1l4Fwo7WRt5A.png" /></figure><h3>Aggregating Data with LEFT JOIN (GROUP BY + COUNT)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*CMY2lb0jFtMt3yYLYQ2U0g.png" /></figure><p>When performing aggregation on joined tables, using LEFT JOIN ensures that categories or groups with zero associated records are not accidentally dropped from your summary report.</p><p>The inventory management team wants a report showing the total number of products listed under each product subcategory. It is essential that subcategories without any active products still appear in the report with a count of 0.</p><p>To achieve this, we left-join AdventureWorks_Product_Subcategories to AdventureWorks_Products and aggregate the count using COUNT(AP.ProductKey):</p><pre>select subcategoryname, COUNT(AP.ProductKey) as [Number of products]<br>from AdventureWorks_Product_Subcategories as APS<br>left join<br>AdventureWorks_Products as AP<br>on<br>APS.ProductSubcategoryKey=AP.ProductSubcategoryKey<br>group by SubcategoryName</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*xw3vd0enQkpUmbuIUBPOfQ.png" /></figure><p>If we used COUNT(*), SQL would count the NULL row generated by the LEFT JOIN, incorrectly returning 1 for empty subcategories. By explicitly passing AP.ProductKey into the COUNT() function, SQL ignores NULL values and correctly displays 0 for subcategories that have no linked products!</p><h3><strong>Multi-Table LEFT JOIN (and the INNER JOIN Trap)</strong></h3><p>Can we chain multiple tables together using LEFT JOIN? In complex datasets, you often need to bring in attributes from several related tables while still preserving every single row from your main table.</p><p>Scenario: Suppose we want a comprehensive customer activity report. We want to list all customers, any orders they placed in 2017, and the names of the products they purchased. If a customer hasn’t purchased anything, they must still stay in the report.</p><p>Here is how we chain three tables using LEFT JOIN:</p><pre>SELECT <br>    AC.FirstName,<br>    AC.LastName,<br>    AS2017.OrderNumber,<br>    AP.ProductName<br>FROM AdventureWorks_Customers AS AC<br>LEFT JOIN AdventureWorks_Sales_2017 AS AS2017<br>    ON AC.CustomerKey = AS2017.CustomerKey<br>LEFT JOIN AdventureWorks_Products AS AP<br>    ON AS2017.ProductKey = AP.ProductKey</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*mSQi5Y4oBLnrM8oEl65_xQ.png" /></figure><p>A common mistake when building multi-table queries is switching to an INNER JOIN further down the chain.</p><p>For example, if you start with a LEFT JOIN between Customers and Sales, but then use an INNER JOIN to connect Sales to Products, the INNER JOIN will eliminate all rows where ProductKey is NULL. Consequently, all non-purchasing customers you wanted to preserve will be filtered out!</p><p>Mastering LEFT JOIN and RIGHT JOIN gives you complete control over how you handle complete vs. incomplete data relationships. In real-world data analytics, datasets are rarely perfectly aligned, and knowing how to preserve unmatched rows or hunt down missing values using NULL filters is a critical skill for any data analyst.</p><p>In the next part of this series, we will explore FULL OUTER JOIN and CROSS JOIN to complete our deep dive into SQL JOIN operations!</p><p>Thanks For Reading!</p><p><strong>Let’s Connect!</strong></p><p><a href="https://www.linkedin.com/in/cavid-shamilov/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BTjypgAsOQvyFmfdbEjNlkg%3D%3D"><strong>LinkedIn</strong></a></p><p><a href="https://github.com/cavid-shamilov"><strong>GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68c309ae4d85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL for Data Analysts: Inner join with examples]]></title>
            <link>https://medium.com/@samilov.cavid2003/sql-for-data-analysts-inner-join-with-examples-8666d31e1ea8?source=rss-2195d9f5d948------2</link>
            <guid isPermaLink="false">https://medium.com/p/8666d31e1ea8</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Cavid Shamil]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 19:36:14 GMT</pubDate>
            <atom:updated>2026-09-20T19:36:14.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-d6CiBHCMueVkaAN9QBVng.png" /></figure><p>Hello! I’m Cavid, an aspiring data analyst. Today, we are going to continue our series on SQL JOINs. <a href="https://medium.com/@samilov.cavid2003/sql-for-data-analysts-understanding-joins-before-diving-into-details-affc6a73b682">In my previous article</a>, I gave a general overview of JOINs, including a quick look at INNER JOIN. As I promised, in this article, we will dive deeper into INNER JOIN and practice with SQL queries using<a href="https://www.kaggle.com/datasets/shaikhshoeb/adventureworks-dataset-for-data-analysis/data"> the AdventureWorks dataset</a>.</p><p>Simply put, an inner join only gives us the data that exists in both tables. If a row in Table A doesn’t find its ‘match’ in Table B based on our join condition, SQL simply leaves it out. It’s all about finding that common ground.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-nT6NSRhShB2mDnSOHQzTw.png" /></figure><p>The INNER JOIN focuses strictly on the overlapping area. It connects AdventureWorks_Products and AdventureWorks_Product_Subcategories using the ProductSubcategoryKey, which serves as a Foreign Key in the Products table and a Primary Key in the Subcategories table.</p><p>In our first example, let’s say we want to display each product name alongside its subcategory name. Since ProductName lives in the AdventureWorks_Products table and SubcategoryName lives in AdventureWorks_Product_Subcategories, we need to join them using their common column: ProductSubcategoryKey.</p><pre>select ProductName,SubcategoryName<br>from AdventureWorks_Products as AP<br>inner join AdventureWorks_Product_Subcategories as APS<br>on <br>AP.ProductSubcategoryKey=APS.ProductSubcategoryKey</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*oe9i4bcwM88x6O6vRQmNTQ.png" /></figure><p>In this query, ProductSubcategoryKey serves as the bridge between both tables. In the AdventureWorks_Product_Subcategories table, ProductSubcategoryKey is the Primary Key because each subcategory appears exactly once with a unique ID. In the AdventureWorks_Products table, ProductSubcategoryKey acts as a Foreign Key (FK) because multiple products can belong to the same subcategory.</p><p>By using INNER JOIN, SQL matches the FK in the Products table with the PK in the Subcategories table and only brings back the records that exist in both.</p><p>Now, let’s look at another example using sales and customer data. Suppose we want to list each sales order along with the customer’s first name and last name.</p><p>Before writing our second query, let’s inspect the structure of both tables using the images below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qrrJuI3yASO06-kIbEZQ4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*VQoxNFX9A31j-4Q9r0-HWg.png" /></figure><p>In the AdventureWorks_Customers table, CustomerKey acts as the Primary Key because every customer is uniquely identified by this ID. In the AdventureWorks_Sales_2017 table, CustomerKey is a Foreign Key because a single customer can make multiple purchases, causing their ID to appear multiple times across different sales transactions.</p><p>We can join the AdventureWorks_Sales_2017 table with the AdventureWorks_Customers table using their shared column: CustomerKey</p><pre>select ordernumber,<br>firstname,<br>lastname<br>from AdventureWorks_Sales_2017 as AS2017<br>inner join AdventureWorks_Customers as AC<br>on<br>AS2017.CustomerKey=AC.CustomerKey</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*zWdrKUEwendqYRwjXq-DFA.png" /></figure><p>INNER JOIN with a WHERE Clause</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*g7xqVRCKyzVf9SCoR49ezQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*O2sQkK2sSv3QpJf4Eah1dQ.png" /></figure><p>Sometimes, joining tables isn’t enough on its own; we also need to filter our combined dataset based on specific business rules. This is where the WHERE clause comes into play. In SQL execution order, the INNER JOIN matches and combines the tables first, and then the WHERE clause filters those joined rows.</p><p>Suppose our marketing team asks for a list of all products along with their subcategories, but they are only interested in products that are Black. Here is how we combine INNER JOIN with a WHERE clause:</p><pre>select productname,SubcategoryName,ProductColor<br>from  AdventureWorks_Products as AP<br>inner join AdventureWorks_Product_Subcategories as APS<br>on<br>AP.ProductSubcategoryKey=APS.ProductSubcategoryKey<br>where ProductColor=&#39;Black&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gQhG9lEaPKaokGRbHvzS9A.png" /></figure><p>INNER JOIN with GROUP BY and ORDER BY</p><p>In real-world data analysis, we rarely just pull raw data — we aggregate it to uncover insights. By combining INNER JOIN with GROUP BY and ORDER BY, we can answer business questions like: &quot;Which customer occupations generate the highest total order volumes?&quot;</p><p>We want to calculate the total number of items ordered (OrderQuantity) grouped by customer occupation (Occupation) and display only the top 5<strong> </strong>occupations with the highest order volume.</p><pre>select top 5<br>Occupation as [Top 5 profession],<br>sum(OrderQuantity) as  [Order count]<br>from AdventureWorks_Sales_2017 as AS2017<br>inner join AdventureWorks_Customers as AC<br>on<br>AS2017.CustomerKey=AC.CustomerKey<br>group by Occupation<br>order by sum(orderquantity) desc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*HlDfJO3gELMvYJ5RVGH6CA.png" /></figure><p>Joining More Than Two Tables (Multi-Table INNER JOIN)</p><p>In complex database models like AdventureWorks, business information is often spread across multiple related tables. Fortunately, INNER JOIN allows us to chain multiple tables together in a single query to create a unified view.</p><p>Suppose we want to generate a product catalog report that displays the Product Name, its Subcategory Name, and its overarching Category Name all together.</p><pre>select ProductName,<br>SubcategoryName,<br>CategoryName<br>from AdventureWorks_Product_Categories as APC<br>inner join AdventureWorks_Product_Subcategories as APS<br>on<br>APC.ProductCategoryKey=APS.ProductcategoryKey<br>inner join AdventureWorks_Products as AP<br>on<br>APS.ProductSubcategoryKey=AP.ProductSubcategoryKey</pre><p>SQL processes these joins sequentially: it first merges categories with subcategories based on matching category IDs, and then matches those subcategories to individual products. Only records that have a complete match across all three tables will appear in the final result!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*Q5x9GZURscdCI5QIOnB1nQ.png" /></figure><p>In this article, we covered INNER JOIN in detail with hands-on practice using the AdventureWorks dataset.</p><p>In the next article of this series, we will dive into left join and explore how to analyze missing data and unmatched rows.</p><p>Thanks For Reading!</p><p><strong>Let’s Connect!</strong></p><p><a href="https://www.linkedin.com/in/cavid-shamilov/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BTjypgAsOQvyFmfdbEjNlkg%3D%3D"><strong>LinkedIn</strong></a></p><p><a href="https://github.com/cavid-shamilov"><strong>GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8666d31e1ea8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL for Data Analysts: Understanding JOINs Before Diving into Details]]></title>
            <link>https://medium.com/@samilov.cavid2003/sql-for-data-analysts-understanding-joins-before-diving-into-details-affc6a73b682?source=rss-2195d9f5d948------2</link>
            <guid isPermaLink="false">https://medium.com/p/affc6a73b682</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Cavid Shamil]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 19:23:56 GMT</pubDate>
            <atom:updated>2026-09-18T19:23:56.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGQzj0-_GDywyeXS_BZRiw.png" /></figure><p>Hello, I’m Cavid, an aspiring data analyst. Today, I want to talk about SQL JOINs. This will be an overview article, and in the next posts, we will dive deeper into the details of each join type.<br>Basically, JOINs allow us to combine multiple tables and store our data much more efficiently. Instead of dumping everything into one giant table, we can break things down into smaller, related tables and use JOINs to bring them together whenever we need a deeper, more detailed analysis.</p><p>There are several types of JOINs in SQL: INNER, LEFT, RIGHT, FULL, CROSS, SELF, and NATURAL JOIN. We will examine each of these in detail in the upcoming articles. But for now, let’s see how a JOIN actually works on a real dataset. In my previous article, we talked about <a href="https://medium.com/@samilov.cavid2003/sql-for-data-analysts-building-database-diagrams-step-by-step-bb98410d19c8">building database</a> diagrams. We’ll be using the exact same dataset here, which you can also find on <a href="https://www.kaggle.com/datasets/shaikhshoeb/adventureworks-dataset-for-data-analysis/data">Kaggle</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*VBEvwaBojOfJvLilvruFdA.png" /></figure><p>If you look at the table closely, you will see ProductKey and ProductSubcategoryKey. The ProductKey is our primary Key, which simply means a unique ID for each product so we never confuse one item with another. And ProductSubcategoryKey is a Foreign Key, meaning it’s just a borrowed ID from another table that helps us connect this product to its category.</p><p>Let’s practice with an example. Suppose we want to see each product alongside its subcategory name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*qfxCQ5ZwkUhiysxX5aMouA.png" /></figure><pre>select ProductName,SubcategoryName<br>from AdventureWorks_Products as AP<br>inner join<br>AdventureWorks_Product_Subcategories as APS<br>on <br>AP.ProductSubcategoryKey=APS.ProductSubcategoryKey</pre><p>As you can see from the query result, SQL matches the ProductSubcategoryKey from both tables and brings together the product names and their corresponding subcategories into a single view.</p><p>I used aliases like APand APS in this query. I did that simply because I didn&#39;t want to type out the full table names every single time. It keeps the query much shorter, cleaner, and way easier to read.<br>So, if we want to truly master JOINs, we need to understand Primary Keys, Foreign Keys — where they are, why they exist, and what we can achieve with them.</p><p>Also, to get comfortable with this logic, practice is key. Working with different tables and writing various queries will make everything easier. In the next article, we’re going to examine every type of JOIN in detail!</p><p>Thanks for reading!</p><p><strong>Let’s Connect!</strong></p><p><a href="https://www.linkedin.com/in/cavid-shamilov/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BTjypgAsOQvyFmfdbEjNlkg%3D%3D"><strong>LinkedIn</strong></a></p><p><a href="https://github.com/cavid-shamilov"><strong>GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=affc6a73b682" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL for Data Analysts: Building Database Diagrams Step by Step]]></title>
            <link>https://medium.com/@samilov.cavid2003/sql-for-data-analysts-building-database-diagrams-step-by-step-bb98410d19c8?source=rss-2195d9f5d948------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb98410d19c8</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Cavid Shamil]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 14:07:52 GMT</pubDate>
            <atom:updated>2026-09-20T13:02:03.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQ80uCK2YcuNXFe4_G7EGA.png" /></figure><p>Hello everyone! I’m Cavid, an aspiring data analyst. Today’s article will be about SQL. Yesterday, after importing CSV data into SQL Server to practice my skills, I set out to create relationships between tables. In this article, I will show you an example of how I structured these relationships and created a database diagram.<br>Checking Data Types</p><p>First, I need to check the data types. Before connecting tables, it is important to make sure the key columns have matching data types. For example, if one key is an int, the foreign key in the other table must also be an int.</p><p>I used this query to check the column details:</p><pre>SELECT <br>    COLUMN_NAME, <br>    DATA_TYPE, <br>    CHARACTER_MAXIMUM_LENGTH  <br>FROM <br>    INFORMATION_SCHEMA.COLUMNS<br>WHERE <br>    TABLE_NAME = &#39;YourTableName&#39;;</pre><p>Here is an example query I ran for the AdventureWorks_Returns table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOTYC9ChhlA__PgaYEjjWg.png" /></figure><p>As shown in the result, TerritoryKey and ProductKey are both set to the int data type. This confirms that they match the primary keys in the main tables, so I can safely connect them later.</p><p>After performing the necessary checks, we begin the process of creating the diagram. Let me show you a few examples. Let’s look at these two tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UCduR4Z4B1M-9U6F1e3DZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ZazLiS_MZ6kYViDnkHBRg.png" /></figure><p>As you can see, there is a ProductCategoryKey column in the AdventureWorks_Product_Subcategories table. So, this column is the foreign key for the AdventureWorks_Product_Subcategories table and the primary key for the AdventureWorks_Product_Categories table. That means we should create a relationship between them.</p><p>To create the diagram, right-click on Database Diagrams under your database and select New Database Diagram. Then, add all the tables you want to connect.</p><p>Here is our first connection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*a7jmYQgDta81G8zFDZdOpg.png" /></figure><p>As you can see, I connected ProductCategoryKey from the Categories table to ProductCategoryKey in the Subcategories table. This creates a one-to-many relationship between the two tables.</p><p>Next, let’s connect AdventureWorks_Product_Subcategories and AdventureWorks_Products.</p><p>In this setup, ProductSubcategoryKey is the Primary Key in AdventureWorks_Product_Subcategories and the Foreign Key in AdventureWorks_Products.</p><p>Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*ZdrFKBCI-4TtwJXyj9pWlQ.png" /></figure><p>Now, let’s take a look at the full database diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*evYZovMxyvMOpaFV2ZLb-w.png" /></figure><p>It might look a bit complex or confusing at first glance, but as long as you build the relationships step-by-step with a plan, the process becomes very simple.</p><p>Creating database diagrams in SQL Server Management Studio is a powerful way to visualize table relationships, maintain data integrity, and better understand your data model as a data analyst. I hope this guide was helpful for your SQL practice!</p><p>Thanks For Reading!</p><p><strong>Let’s Connect!</strong></p><p><a href="https://www.linkedin.com/in/cavid-shamilov/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BTjypgAsOQvyFmfdbEjNlkg%3D%3D"><strong>LinkedIn</strong></a></p><p><a href="https://github.com/cavid-shamilov"><strong>GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb98410d19c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>