<?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 Charan Kumar Kharade Somoji Rao on Medium]]></title>
        <description><![CDATA[Stories by Charan Kumar Kharade Somoji Rao on Medium]]></description>
        <link>https://medium.com/@charankumarkharade2003?source=rss-25cfd879d39e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Dv2ynEjbGeUbimLDxajcuA.png</url>
            <title>Stories by Charan Kumar Kharade Somoji Rao on Medium</title>
            <link>https://medium.com/@charankumarkharade2003?source=rss-25cfd879d39e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:31:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@charankumarkharade2003/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[Introduction to dbt — Amazing Transformation tool]]></title>
            <link>https://medium.com/@charankumarkharade2003/introduction-to-dbt-amazing-transformation-tool-e04956bbbf42?source=rss-25cfd879d39e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e04956bbbf42</guid>
            <category><![CDATA[transformation]]></category>
            <category><![CDATA[dbt-labs]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Charan Kumar Kharade Somoji Rao]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 15:20:33 GMT</pubDate>
            <atom:updated>2026-11-13T15:20:33.807Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. How dbt Helps (In Simple Terms)</h3><p>dbt (<strong>data build tool</strong>) handles the <strong>T (Transform)</strong> in an <strong>ELT</strong> (Extract, Load, Transform) pipeline. Once your raw data is loaded into a data warehouse, dbt lets you turn that messy raw data into clean, analytics-ready tables using plain <strong>SQL </strong>SELECT<strong> statements</strong>.</p><ul><li><strong>No complex boilerplate:</strong> You don’t write CREATE TABLE or INSERT statements—dbt handles the DDL/DML automatically based on your configurations.</li><li><strong>Automatic dependency order:</strong> Using {{ ref(&#39;model_name&#39;) }}, dbt builds a dependency graph (DAG) so upstream tables always run before downstream ones.</li><li><strong>Software engineering workflow:</strong> Everything is stored as .sql and .yml files in Git, giving your data team version control, pull requests, and code reviews.</li><li><strong>Built-in testing &amp; documentation:</strong> You can verify data quality (e.g., checking for nulls or duplicates) and auto-generate a searchable website with data lineage maps.</li></ul><h3>2. What dbt Connects To</h3><p>dbt connects directly to SQL-speaking databases, cloud data warehouses, data lakes, and query engines using dedicated <strong>adapters</strong>:</p><ul><li><strong>Cloud Data Warehouses:</strong> Snowflake, Google BigQuery, Amazon Redshift</li><li><strong>Data Lakes &amp; Query Engines:</strong> Databricks, Apache Spark, Trino, Presto, Starburst, Dremio</li><li><strong>Databases &amp; Local Engines:</strong> PostgreSQL, DuckDB, ClickHouse, SQL Server, MySQL, Oracle</li><li><strong>Surrounding Ecosystem:</strong> Ingestion tools like <strong>Fivetran/Airbyte</strong> load data <em>before</em> dbt runs, orchestrators like <strong>Airflow/Dagster</strong> schedule dbt runs, and BI tools like <strong>Tableau/Looker/Power BI</strong> read the final tables dbt builds.</li></ul><h3>3. Essential dbt Commands</h3><p>dbt initCreates a brand-new dbt project with the default folder structure.</p><p>dbt debugTests your database connection and verifies your setup.</p><p>dbt depsInstalls third-party dbt packages listed in packages.yml.</p><p>dbt seedLoads local CSV files into your data warehouse as tables.</p><p>dbt runExecutes your SQL models to build views and tables in the warehouse.</p><p>dbt testRuns data quality checks (e.g., unique, not_null) against your models.</p><p>dbt snapshotCaptures historical changes in mutable tables (Type-2 Slowly Changing Dimensions).</p><p>dbt buildRuns models, tests, snapshots, and seeds all in one command in dependency order.</p><p>dbt docs generateCompiles your project documentation and visual lineage graph.</p><p>dbt docs serveOpens the generated documentation website in your browser.</p><h3>4. dbt File Structure &amp; What You Do in Each Folder</h3><p>When you initialize a dbt project, it creates a standardized layout:</p><pre>my_dbt_project/<br>├── dbt_project.yml<br>├── packages.yml<br>├── models/<br>│   ├── staging/<br>│   ├── intermediate/<br>│   └── marts/<br>├── seeds/<br>├── snapshots/<br>├── tests/<br>├── macros/<br>├── analyses/<br>└── target/</pre><ul><li>dbt_project.yml<strong> (File):</strong> The master configuration file. Here you define your project name, connection profile, and rules for how folders should be built (e.g., building staging as views and marts as tables).</li><li>packages.yml<strong> (File):</strong> Where you list helpful open-source dbt libraries (like dbt_utils) to install via dbt deps.</li><li>models/<strong>:</strong> The heart of your project where you write SQL SELECT queries. Teams usually split this into three layers:</li><li>staging/<strong>:</strong> 1-to-1 cleanup of raw source tables (renaming columns, casting data types, basic filtering).</li><li>intermediate/<strong>:</strong> Modular, multi-step joins or complex business logic that bridges raw data and final tables.</li><li>marts/<strong>:</strong> Final, clean fact and dimension tables (fct_orders, dim_customers) ready for BI dashboards and business teams.</li><li>seeds/<strong>:</strong> Stores small, static CSV files (like country codes or employee mappings) that you want version-controlled in Git and loaded into your warehouse.</li><li>snapshots/<strong>:</strong> Contains SQL queries used to track historical changes over time when a source table overwrites old values (like tracking a customer&#39;s changing subscription status).</li><li>tests/<strong>:</strong> Holds custom SQL queries written to catch edge-case data bugs (any rows returned by a test query means the test fails).</li><li>macros/<strong>:</strong> Stores reusable Jinja-SQL functions (similar to Python functions) so you don&#39;t repeat the same SQL logic across multiple files.</li><li>analyses/<strong>:</strong> A place to store ad-hoc analytical SQL queries that you want tracked in Git without turning them into actual tables in the warehouse.</li><li>target/<strong>:</strong> An auto-generated folder where dbt puts compiled SQL code and execution artifacts (usually ignored in Git).</li></ul><p>Feel free to explore the dbt documentation: https://docs.getdbt.com/docs/introduction?version=2</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e04956bbbf42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Efficient Python for Data Engineers: Combining, Counting, Iterating, and Profiling]]></title>
            <link>https://medium.com/@charankumarkharade2003/writing-efficient-python-for-data-engineers-combining-counting-iterating-and-profiling-4af8583786e8?source=rss-25cfd879d39e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4af8583786e8</guid>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[memory-profiling]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python-optimization]]></category>
            <dc:creator><![CDATA[Charan Kumar Kharade Somoji Rao]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 19:41:57 GMT</pubDate>
            <atom:updated>2026-10-20T19:41:57.255Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Practical Python techniques for cleaner ETL pipelines, faster data processing, and better resource usage.</em></p><p>As data engineers, we spend a lot of time writing Python code to extract data from APIs, transform records, validate datasets, remove duplicates, and prepare data for analytics.</p><p>But writing code that works is only the first step. We also need to consider whether our code is readable, efficient, and scalable.</p><p>For example, imagine processing one million customer records. A simple nested loop might work perfectly for a small dataset, but it can become a performance bottleneck as the data grows.</p><p>However, Python provides built-in functions, standard-library modules, and profiling tools that help us write better code without making it unnecessarily complicated.</p><p>In this article, we will explore:</p><ol><li>Combining data with zip()</li><li>Counting values with collections.Counter</li><li>Generating combinations with itertools</li><li>Comparing datasets with sets</li><li>Replacing unnecessary loops with built-in functions</li><li>Improving loops by moving repeated calculations</li><li>Measuring execution time with timeit</li><li>Profiling runtime and memory usage</li></ol><p>We will use practical data-engineering examples throughout the article.</p><h3>1. Combining Data with zip()</h3><p>Imagine that we extract customer names and their corresponding order counts from two different sources.</p><pre>customers = [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;]<br>order_counts = [5, 3, 8]</pre><p>Our goal is to combine these two lists into customer-order pairs.</p><h3>The traditional approach</h3><p>We could use a loop and access both lists by index.</p><pre>combined = []</pre><pre>for i in range(len(customers)):<br>    combined.append((customers[i], order_counts[i]))</pre><pre>print(combined)</pre><p>Output:</p><pre>[<br>    (&quot;Alice&quot;, 5),<br>    (&quot;Bob&quot;, 3),<br>    (&quot;Charlie&quot;, 8)<br>]</pre><p>This works, but Python provides a simpler alternative.</p><h3>The Pythonic approach</h3><pre>combined = list(zip(customers, order_counts))</pre><pre>print(combined)</pre><p>Output:</p><pre>[<br>    (&quot;Alice&quot;, 5),<br>    (&quot;Bob&quot;, 3),<br>    (&quot;Charlie&quot;, 8)<br>]</pre><p>The zip() function combines elements from multiple iterables position by position.</p><h3>How does zip() work?</h3><p>Consider these two lists:</p><pre>customers = [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;]<br>order_counts = [5, 3, 8]</pre><p>Python pairs the first element of each list, then the second, and so on.</p><p>Conceptually:</p><pre>Alice    → 5<br>Bob      → 3<br>Charlie  → 8</pre><p>One important detail: zip() returns an iterator, not a list. Wrapping it in list() materializes all the resulting pairs in memory.</p><pre>pairs = zip(customers, order_counts)</pre><pre>print(type(pairs))<br># &lt;class &#39;zip&#39;&gt;</pre><h3>What if the lists have different lengths?</h3><p>By default, zip() stops when the shortest iterable is exhausted.</p><pre>customers = [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;]<br>order_counts = [5, 3]</pre><pre>print(list(zip(customers, order_counts)))</pre><p>Output:</p><pre>[(&quot;Alice&quot;, 5), (&quot;Bob&quot;, 3)]</pre><p>Charlie is excluded because there is no corresponding order count.</p><p>If missing values must be preserved, use itertools.zip_longest():</p><pre>from itertools import zip_longest</pre><pre>customers = [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;]<br>order_counts = [5, 3]</pre><pre>combined = list(<br>    zip_longest(<br>        customers,<br>        order_counts,<br>        fillvalue=None<br>    )<br>)</pre><pre>print(combined)</pre><p>Output:</p><pre>[<br>    (&quot;Alice&quot;, 5),<br>    (&quot;Bob&quot;, 3),<br>    (&quot;Charlie&quot;, None)<br>]</pre><h3>Data-engineering use case</h3><p>Suppose you retrieve customer IDs from an API and corresponding scores from a transformation step. zip() can combine aligned results into records.</p><p>However, make sure the two collections have the same intended ordering. If records can arrive in different orders, joining them by a stable key is safer than pairing them by position.</p><p><strong>Key takeaway:</strong> Use zip() when combining aligned sequences. Use zip_longest() when unmatched positions must be retained.</p><h3>2. Counting Values with collections.Counter</h3><p>Counting values is a common data-engineering task.</p><p>You might need to count:</p><ul><li>Orders by status</li><li>Events by event type</li><li>API responses by HTTP status code</li><li>Records by country</li><li>Failed rows by validation reason</li></ul><p>Let’s say we have extracted event types from an application.</p><pre>event_types = [<br>    &quot;purchase&quot;,<br>    &quot;login&quot;,<br>    &quot;purchase&quot;,<br>    &quot;logout&quot;,<br>    &quot;login&quot;,<br>    &quot;purchase&quot;<br>]</pre><h3>The traditional approach</h3><p>We could build a dictionary and increment each count manually.</p><pre>counts = {}</pre><pre>for event in event_types:<br>    if event in counts:<br>        counts[event] += 1<br>    else:<br>        counts[event] = 1</pre><pre>print(counts)</pre><p>Output:</p><pre>{<br>    &quot;purchase&quot;: 3,<br>    &quot;login&quot;: 2,<br>    &quot;logout&quot;: 1<br>}</pre><p>The logic is correct, but Python has a dedicated tool for this task.</p><h3>A simpler approach with Counter</h3><pre>from collections import Counter</pre><pre>counts = Counter(event_types)</pre><pre>print(counts)</pre><p>Output:</p><pre>Counter({<br>    &quot;purchase&quot;: 3,<br>    &quot;login&quot;: 2,<br>    &quot;logout&quot;: 1<br>})</pre><p>Counter is part of Python&#39;s standard library. It is a specialized dictionary-like class designed to count hashable objects.</p><h3>Finding the most common values</h3><p>Suppose we want the three most common event types.</p><pre>print(counts.most_common(3))</pre><p>Output:</p><pre>[<br>    (&quot;purchase&quot;, 3),<br>    (&quot;login&quot;, 2),<br>    (&quot;logout&quot;, 1)<br>]</pre><p>This is particularly useful when investigating data distributions or identifying the most frequent errors in an ingestion pipeline.</p><h3>Counting records by category</h3><pre>from collections import Counter</pre><pre>statuses = [<br>    &quot;success&quot;,<br>    &quot;failed&quot;,<br>    &quot;success&quot;,<br>    &quot;success&quot;,<br>    &quot;failed&quot;<br>]</pre><pre>status_counts = Counter(statuses)</pre><pre>print(status_counts[&quot;success&quot;])<br># 3</pre><pre>print(status_counts[&quot;failed&quot;])<br># 2</pre><p>You can also combine counters:</p><pre>batch_1 = Counter([&quot;success&quot;, &quot;success&quot;, &quot;failed&quot;])<br>batch_2 = Counter([&quot;success&quot;, &quot;failed&quot;, &quot;failed&quot;])</pre><pre>total_counts = batch_1 + batch_2</pre><pre>print(total_counts)<br># Counter({&quot;success&quot;: 3, &quot;failed&quot;: 3})</pre><p>This is useful for aggregating counts from independent batches, provided that each batch represents the intended, non-overlapping data.</p><h3>Data-engineering use case</h3><p>Imagine an ETL pipeline that processes customer events. At the end of each batch, you want to know how many records were successfully processed and how many failed validation.</p><p>Counter gives you a readable way to generate those counts without writing repetitive dictionary-update logic.</p><p><strong>Key takeaway:</strong> Use Counter when your task is to count occurrences. It improves readability and reduces the amount of code you need to maintain.</p><h3>3. Generating Combinations with itertools</h3><p>Sometimes we need to compare every unique pair of values.</p><p>For example, we might want to generate all unique pairs of data sources to test whether their outputs agree.</p><p>Consider these sources:</p><pre>sources = [<br>    &quot;CRM&quot;,<br>    &quot;ERP&quot;,<br>    &quot;Web&quot;,<br>    &quot;Payments&quot;<br>]</pre><p>We want pairs such as:</p><pre>CRM - ERP<br>CRM - Web<br>CRM - Payments<br>ERP - Web<br>ERP - Payments<br>Web - Payments</pre><p>Each pair should appear only once, and we do not want pairs such as both CRM - ERP and ERP - CRM.</p><h3>A loop-based approach</h3><pre>pairs = []</pre><pre>for i in range(len(sources)):<br>    for j in range(i + 1, len(sources)):<br>        pairs.append((sources[i], sources[j]))</pre><pre>print(pairs)</pre><p>This works, but it requires nested loops and index management.</p><h3>A cleaner approach with itertools.combinations()</h3><pre>from itertools import combinations</pre><pre>pairs = list(combinations(sources, 2))</pre><pre>print(pairs)</pre><p>Output:</p><pre>[<br>    (&quot;CRM&quot;, &quot;ERP&quot;),<br>    (&quot;CRM&quot;, &quot;Web&quot;),<br>    (&quot;CRM&quot;, &quot;Payments&quot;),<br>    (&quot;ERP&quot;, &quot;Web&quot;),<br>    (&quot;ERP&quot;, &quot;Payments&quot;),<br>    (&quot;Web&quot;, &quot;Payments&quot;)<br>]</pre><p>The 2 tells Python to select two items at a time.</p><p>If we wanted groups of three:</p><pre>triples = list(combinations(sources, 3))</pre><h3>Why use itertools?</h3><p>The itertools module is part of Python&#39;s standard library. It provides tools for working with iterators, including combinations, permutations, chaining, and accumulation.</p><p>Unlike manually building every combination, combinations() returns an iterator. This allows us to process the results without necessarily storing every pair in memory.</p><p>For example:</p><pre>for source_a, source_b in combinations(sources, 2):<br>    print(source_a, source_b)</pre><p>This is more memory-friendly than building a list when you only need to process each pair once.</p><h3>An important scalability consideration</h3><p>The number of unique pairs grows quickly as the number of sources increases.</p><p>For (n) items, the number of pairs is:</p><p>[<br>\frac{n(n-1)}{2}<br>]</p><p>With 4 sources, there are 6 pairs. With 1,000 sources, there are 499,500 pairs.</p><p>Using itertools makes the code cleaner, but it does not remove the computational cost of generating all those pairs.</p><p><strong>Key takeaway:</strong> Use combinations() when you need unique unordered groups. Consider the number of generated results before applying it to large datasets.</p><h3>4. Comparing Datasets with Sets</h3><p>Data engineers regularly compare datasets to identify missing records, duplicates, and differences between source and target systems.</p><p>Python sets are particularly useful for these tasks.</p><p>A set stores unique hashable elements and supports efficient membership testing and mathematical set operations.</p><p>Let’s compare two lists of customer IDs.</p><pre>source_ids = [<br>    &quot;C101&quot;,<br>    &quot;C102&quot;,<br>    &quot;C103&quot;,<br>    &quot;C104&quot;<br>]</pre><pre>target_ids = [<br>    &quot;C102&quot;,<br>    &quot;C103&quot;,<br>    &quot;C105&quot;<br>]</pre><p>Our goal is to understand which IDs exist in both datasets and which are missing.</p><h3>Convert lists into sets</h3><pre>source_set = set(source_ids)<br>target_set = set(target_ids)</pre><p>Converting to a set removes duplicate values. That is useful for comparing unique IDs, but remember that it discards duplicate-count information and does not preserve the original list ordering.</p><h3>Operation 1: Intersection</h3><p>Intersection returns the elements present in both sets.</p><pre>common_ids = source_set.intersection(target_set)</pre><pre>print(common_ids)</pre><p>Output:</p><pre>{&quot;C102&quot;, &quot;C103&quot;}</pre><p>You can also use the &amp; operator:</p><pre>common_ids = source_set &amp; target_set</pre><p><strong>When is this useful?</strong></p><p>When checking which source records are also present in the target.</p><h3>Operation 2: Difference</h3><p>Difference returns elements present in the first set but absent from the second.</p><pre>missing_from_target = source_set.difference(target_set)</pre><pre>print(missing_from_target)</pre><p>Output:</p><pre>{&quot;C101&quot;, &quot;C104&quot;}</pre><p>These customer IDs appear in the source but not in the target.</p><p>You can also write:</p><pre>missing_from_target = source_set - target_set</pre><p>Reverse the operation to find target-only IDs:</p><pre>target_only = target_set - source_set</pre><pre>print(target_only)</pre><p>Output:</p><pre>{&quot;C105&quot;}</pre><h3>Operation 3: Symmetric difference</h3><p>Symmetric difference returns elements that exist in either set, but not both.</p><pre>differences = source_set.symmetric_difference(target_set)</pre><pre>print(differences)</pre><p>Output:</p><pre>{&quot;C101&quot;, &quot;C104&quot;, &quot;C105&quot;}</pre><p>The ^ operator provides the same operation:</p><pre>differences = source_set ^ target_set</pre><h3>Operation 4: Union</h3><p>Union combines the unique elements from both sets.</p><pre>all_ids = source_set.union(target_set)</pre><pre>print(all_ids)</pre><p>Output:</p><pre>{&quot;C101&quot;, &quot;C102&quot;, &quot;C103&quot;, &quot;C104&quot;, &quot;C105&quot;}</pre><h3>A practical data-quality check</h3><p>Here is a complete example that compares source and target IDs.</p><pre>source_ids = [&quot;C101&quot;, &quot;C102&quot;, &quot;C103&quot;, &quot;C104&quot;]<br>target_ids = [&quot;C102&quot;, &quot;C103&quot;, &quot;C105&quot;]</pre><pre>source_set = set(source_ids)<br>target_set = set(target_ids)</pre><pre>print(&quot;Matched IDs:&quot;, source_set &amp; target_set)<br>print(&quot;Missing from target:&quot;, source_set - target_set)<br>print(&quot;Target-only IDs:&quot;, target_set - source_set)</pre><p>This pattern can be useful during reconciliation between an API extract, a staging table, and a target dataset.</p><p>However, set comparison validates only membership of unique values. It does not tell you whether the target contains the correct number of duplicate records, whether column values match, or whether records meet business rules. Those checks require additional logic.</p><h3>Why can sets be faster?</h3><p>Checking whether an item exists in a list generally requires scanning elements until a match is found. Its worst-case time complexity is (O(n)).</p><p>Set membership testing is (O(1)) on average, although collisions and other implementation details can affect performance.</p><p>If you need to perform thousands of membership checks, converting a list to a set once can be substantially more efficient than repeatedly scanning the list.</p><p>For example:</p><pre># Repeated list membership checks<br>if &quot;C103&quot; in source_ids:<br>    print(&quot;Found&quot;)</pre><p>For many checks:</p><pre>source_set = set(source_ids)</pre><pre>if &quot;C103&quot; in source_set:<br>    print(&quot;Found&quot;)</pre><p>Building the set has a cost, so the advantage is most useful when you reuse it for multiple lookups.</p><p><strong>Key takeaway:</strong> Use set operations to compare unique values, reconcile datasets, and perform repeated membership checks. Do not use sets when duplicate counts or ordering are important.</p><h3>5. Replace Unnecessary Loops with Built-in Functions</h3><p>Loops are not bad. They are essential for many programming tasks.</p><p>The problem arises when we use explicit loops for operations that Python already provides through built-in functions or specialized libraries.</p><p>Consider a dataset containing daily sales figures for several stores.</p><pre>sales = [<br>    [120, 150, 130],<br>    [200, 180, 220],<br>    [90, 110, 100]<br>]</pre><p>Each inner list represents the sales recorded for one store over three days.</p><p>We want to calculate the total sales for every store.</p><h3>Using a loop</h3><pre>totals = []</pre><pre>for store_sales in sales:<br>    total = 0</pre><pre>    for amount in store_sales:<br>        total += amount</pre><pre>    totals.append(total)</pre><pre>print(totals)</pre><p>Output:</p><pre>[400, 600, 300]</pre><p>This is valid code, but Python already provides the sum() function.</p><h3>Using sum()</h3><pre>totals = []</pre><pre>for store_sales in sales:<br>    totals.append(sum(store_sales))</pre><pre>print(totals)</pre><p>Output:</p><pre>[400, 600, 300]</pre><p>We still need a loop to process each store, but we have eliminated the inner loop.</p><p>We can make the code more concise with a list comprehension:</p><pre>totals = [sum(store_sales) for store_sales in sales]</pre><p>The result is the same.</p><h3>Why is this useful?</h3><p>Built-in functions such as sum(), min(), max(), any(), and all() express common operations directly.</p><p>They often improve readability and can perform better than manually implemented equivalents because their core operations are implemented efficiently in Python.</p><p>But the most important benefit is clarity: the code communicates what we want to calculate rather than the mechanics of calculating it.</p><h3>When not to eliminate loops</h3><p>Sometimes a loop is the clearest choice.</p><p>For example, if every record requires conditional validation, logging, error handling, and different transformation rules, an explicit loop may be easier to maintain.</p><p>The goal is not to remove every loop. It is to remove unnecessary complexity.</p><p><strong>Key takeaway:</strong> Prefer built-in functions for standard operations, but keep explicit loops when they make complex transformation logic easier to understand.</p><h3>6. Improve Loops by Moving Repeated Calculations</h3><p>One of the most useful performance improvements is to identify calculations that do not change between iterations.</p><p>Suppose we have a list of product prices and want to compare each price with the average price.</p><pre>prices = [10, 20, 30, 40, 50]</pre><p>A less efficient implementation might calculate the average every time through the loop.</p><pre>for price in prices:<br>    average_price = sum(prices) / len(prices)</pre><pre>    if price &gt; average_price:<br>        print(price)</pre><p>The average is the same on every iteration. Recalculating it is unnecessary.</p><h3>A better approach</h3><pre>prices = [10, 20, 30, 40, 50]</pre><pre>average_price = sum(prices) / len(prices)</pre><pre>for price in prices:<br>    if price &gt; average_price:<br>        print(price)</pre><p>Output:</p><pre>40<br>50</pre><p>The calculation now happens only once.</p><h3>Understanding the complexity</h3><p>Let (n) be the number of prices.</p><p>In the first version, sum(prices) scans the list on every iteration. The repeated work takes (O(n^2)) time overall.</p><p>In the second version, calculating the average takes (O(n)), and checking each price takes another (O(n)). The total time complexity is therefore (O(n)).</p><p>This distinction becomes important as datasets grow.</p><p>For example, the difference between an (O(n)) and an (O(n²)) algorithm can become substantial when processing hundreds of thousands of records.</p><h3>Data-engineering applications</h3><p>The same principle applies when processing:</p><ul><li>API responses with a fixed configuration</li><li>Batch records with shared lookup tables</li><li>Data validation against constant thresholds</li><li>Transformations requiring the same schema or mapping</li><li>Repeated calculations based on the same dataset</li></ul><p>If a calculation does not depend on the current record, ask whether it can be performed once before the loop.</p><p><strong>Key takeaway:</strong> Keep invariant calculations outside loops. Avoid repeating work whose result cannot change between iterations.</p><h3>7. Measure Performance with timeit</h3><p>We can make reasonable assumptions about which code is faster, but assumptions are not measurements.</p><p>Python provides the timeit module to measure the execution time of small pieces of code.</p><p>The supplied learning material demonstrates the %timeit magic command in Jupyter notebooks.</p><h3>Measuring a single line</h3><pre>%timeit sum(range(1000))</pre><p>This executes the expression repeatedly and reports a timing summary.</p><p>The exact output depends on the machine, Python version, system load, and measurement conditions.</p><h3>Measuring multiple lines</h3><p>In a Jupyter notebook, use %%timeit at the beginning of a cell.</p><pre>%%timeit</pre><pre>numbers = []</pre><pre>for number in range(1000):<br>    numbers.append(number)</pre><p>This measures the execution time of the cell’s code.</p><h3>Comparing two approaches</h3><p>Let’s compare an explicit loop with a list comprehension.</p><pre># Approach 1: Explicit loop<br>def using_loop(n):<br>    result = []</pre><pre>    for number in range(n):<br>        result.append(number)</pre><pre>    return result</pre><pre># Approach 2: List comprehension<br>def using_comprehension(n):<br>    return [number for number in range(n)]</pre><p>In a Jupyter notebook:</p><pre>%timeit using_loop(1000)<br>%timeit using_comprehension(1000)</pre><p>Compare the results rather than assuming one approach will always win.</p><h3>Using timeit outside Jupyter</h3><p>The %timeit syntax is specific to IPython and Jupyter. In a regular Python script, use the standard-library module:</p><pre>import timeit</pre><pre>loop_time = timeit.timeit(<br>    lambda: using_loop(1000),<br>    number=1000<br>)</pre><pre>comprehension_time = timeit.timeit(<br>    lambda: using_comprehension(1000),<br>    number=1000<br>)</pre><pre>print(&quot;Loop:&quot;, loop_time)<br>print(&quot;Comprehension:&quot;, comprehension_time)</pre><p>This measures 1,000 executions of each function.</p><h3>What should you remember about benchmarks?</h3><ul><li>Compare equivalent operations.</li><li>Use representative input sizes.</li><li>Run measurements more than once.</li><li>Avoid comparing results collected under very different system conditions.</li><li>Separate setup work from the operation you intend to measure.</li><li>Do not treat a small benchmark improvement as proof of a major production improvement.</li></ul><p>For example, saving a few microseconds in a transformation that runs once may not matter. Improving a transformation that runs millions of times per batch could be much more valuable.</p><p><strong>Key takeaway:</strong> Measure performance before and after optimization. The fastest approach depends on the workload and execution environment.</p><h3>8. Profile Runtime to Find Bottlenecks</h3><p>Timing an entire function tells us how long it takes to run, but it does not necessarily explain where the time is spent.</p><p>For more detailed investigation, we can use profiling.</p><p>Profiling helps us identify which functions or lines consume the most execution time.</p><h3>Example: A data transformation function</h3><pre>def process_records(records):<br>    cleaned = []</pre><pre>    for record in records:<br>        name = record[&quot;name&quot;].strip().lower()<br>        amount = float(record[&quot;amount&quot;])</pre><pre>        cleaned.append({<br>            &quot;name&quot;: name,<br>            &quot;amount&quot;: amount<br>        })</pre><pre>    return cleaned</pre><p>We can measure the complete function using timeit:</p><pre>%timeit process_records(records)</pre><p>If the function is slow, however, we may need to investigate individual operations or function calls.</p><h3>Function-level profiling</h3><p>Python’s built-in cProfile module provides information about function-call frequency and execution time.</p><pre>import cProfile</pre><pre>cProfile.run(&quot;process_records(records)&quot;)</pre><p>The output helps identify functions that consume substantial cumulative time or are called very frequently.</p><h3>Line-by-line profiling</h3><p>The supplied learning material also introduces line_profiler, which measures execution time at the line level.</p><p>In a suitable IPython environment, the setup is typically:</p><pre>%load_ext line_profiler</pre><p>You can then profile a function with:</p><pre>%lprun -f process_records process_records(records)</pre><p>This requires the line_profiler package to be installed and the function to be available in the notebook environment.</p><h3>When should data engineers use profiling?</h3><p>Consider a pipeline with these stages:</p><ol><li>Extract records from an API.</li><li>Normalize JSON responses.</li><li>Convert timestamps.</li><li>Validate required fields.</li><li>Write the output to a data warehouse.</li></ol><p>If the entire pipeline takes ten minutes, profiling can help determine whether the expensive part is a Python transformation, repeated function calls, or another operation.</p><p>Profiling does not automatically fix performance problems. It provides evidence to guide the next optimization.</p><p>Also, a Python profiler cannot by itself explain every delay caused by external API requests, database queries, network latency, or distributed execution. Those components may require their own monitoring and tracing tools.</p><p><strong>Key takeaway:</strong> Use timing to detect a performance problem and profiling to investigate where the time is being spent.</p><h3>9. Measure Memory Usage, Not Just Execution Time</h3><p>Fast code is not necessarily memory-efficient code.</p><p>This matters when processing large JSON payloads, API extracts, CSV files, and other datasets that can consume substantial memory.</p><h3>Inspecting object size</h3><p>Python’s sys.getsizeof() provides the shallow size of an object in bytes.</p><pre>import sys</pre><pre>numbers = list(range(1000))</pre><pre>print(sys.getsizeof(numbers))</pre><p>This reports the size of the list object itself, including the space allocated for its references. It does not recursively include the memory occupied by all the referenced integers.</p><p>Therefore, it is useful for inspecting individual objects, but it is not a complete measurement of total memory consumption.</p><h3>Understanding iterators and lists</h3><p>Consider these examples:</p><pre>numbers = range(1_000_000)</pre><pre>numbers = list(range(1_000_000))</pre><p>The range object represents a sequence without storing all one million integer values as a list. The list, on the other hand, stores references to its elements and requires substantially more memory.</p><p>The best choice depends on how the data will be used.</p><p>For example, if you only need to iterate over the values once, materializing the entire sequence may be unnecessary.</p><h3>Use generators when appropriate</h3><p>Suppose we want to process records one at a time.</p><pre>def read_records(records):<br>    for record in records:<br>        yield record</pre><p>A generator yields values as they are requested rather than building a complete output list upfront.</p><p>This can help reduce peak memory usage when processing large datasets incrementally.</p><p>However, generators do not make every operation memory-free. If your code later converts the generator into a list, the results will still be materialized in memory.</p><h3>Memory profiling</h3><p>The supplied material also introduces the memory_profiler package for examining memory usage line by line.</p><p>This can help investigate which parts of a function are associated with increases in memory consumption.</p><p>Remember that memory measurements depend on the environment and measurement method. Small allocations may be difficult to distinguish, and reported process memory is not necessarily the same as the exact size of a Python object.</p><p><strong>Key takeaway:</strong> Consider both runtime and memory consumption. Use iterators and generators when incremental processing fits the task, and profile memory when large datasets cause resource problems.</p><h3>10. A Practical Optimization Checklist for Data Engineers</h3><p>Before optimizing a Python transformation or ETL job, ask the following questions.</p><p><strong>Data structures</strong></p><ul><li>Am I using a dictionary or Counter when counting values?</li><li>Can a set simplify unique-value comparisons?</li><li>Can zip() combine aligned collections more clearly?</li></ul><p><strong>Iteration</strong></p><ul><li>Can a built-in function replace a manual loop?</li><li>Can itertools simplify combinations or iterator operations?</li><li>Am I generating results that I do not actually need?</li></ul><p><strong>Repeated work</strong></p><ul><li>Am I recalculating values that remain constant?</li><li>Can configuration, mappings, or reference data be prepared once outside a loop?</li></ul><p><strong>Performance</strong></p><ul><li>Have I measured the execution time?</li><li>Have I profiled the code to locate the bottleneck?</li><li>Have I tested with a realistic data volume?</li></ul><p><strong>Memory</strong></p><ul><li>Am I creating unnecessary intermediate lists?</li><li>Could an iterator or generator help?</li><li>Am I materializing more data than the next pipeline stage requires?</li></ul><p><strong>Correctness</strong></p><ul><li>Does the optimized code produce the same expected results?</li><li>Could a set silently remove meaningful duplicates?</li><li>Could zip() discard unmatched records?</li><li>Have I preserved null handling, ordering, and business rules?</li></ul><p>Performance optimization should never come at the expense of data correctness.</p><h3>Conclusion</h3><p>Writing efficient Python is not about making every line shorter or eliminating every loop. It is about choosing the right tool for the task and understanding the cost of the operations we perform.</p><p>For data engineers, a few habits can make a meaningful difference:</p><ul><li>Use zip() to combine aligned iterables.</li><li>Use collections.Counter to count occurrences.</li><li>Use itertools.combinations() to generate unique pairs.</li><li>Use set operations to compare unique values between datasets.</li><li>Prefer built-in functions when they express the intended operation clearly.</li><li>Move repeated, invariant calculations outside loops.</li><li>Measure runtime before drawing conclusions about performance.</li><li>Profile execution time and memory when a pipeline becomes expensive.</li></ul><p>Start with readable code, validate that it produces the correct results, and measure before optimizing.</p><p>As data volumes grow, these small decisions can help keep your Python transformations simpler to maintain and easier to scale.</p><h3>Further reading</h3><ul><li><a href="https://docs.python.org/3/library/functions.html#zip">Python documentation: </a><a href="https://docs.python.org/3/library/functions.html#zip">zip()</a></li><li><a href="https://docs.python.org/3/library/collections.html#collections.Counter">Python documentation: </a><a href="https://docs.python.org/3/library/collections.html#collections.Counter">collections.Counter</a></li><li><a href="https://docs.python.org/3/library/itertools.html">Python documentation: </a><a href="https://docs.python.org/3/library/itertools.html">itertools</a></li><li><a href="https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset">Python documentation: Set types</a></li><li><a href="https://docs.python.org/3/library/timeit.html">Python documentation: </a><a href="https://docs.python.org/3/library/timeit.html">timeit</a></li><li><a href="https://docs.python.org/3/library/profile.html">Python documentation: </a><a href="https://docs.python.org/3/library/profile.html">cProfile</a></li><li><a href="https://docs.python.org/3/library/sys.html#sys.getsizeof">Python documentation: </a><a href="https://docs.python.org/3/library/sys.html#sys.getsizeof">sys.getsizeof()</a></li></ul><p><em>This article was written while I was exploring optimization opportunities for my project workflows and found it helpful to be posted.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4af8583786e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Identify Window Function Problems in SQL — and Prove Your Solution Is Correct]]></title>
            <link>https://medium.com/@charankumarkharade2003/how-to-identify-window-function-problems-in-sql-and-prove-your-solution-is-correct-c1b2ff614b47?source=rss-25cfd879d39e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1b2ff614b47</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[sql-window-functions]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Charan Kumar Kharade Somoji Rao]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 15:43:52 GMT</pubDate>
            <atom:updated>2026-10-04T15:43:52.493Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started learning SQL window functions, I focused on one thing:</p><p><strong>learning the syntax.</strong></p><p>I knew that I could write:</p><pre>SUM(amount) OVER (...)</pre><p>or:</p><pre>ROW_NUMBER() OVER (...)</pre><p>But I eventually realized that knowing the syntax wasn’t the difficult part.</p><p>The difficult part was recognizing:</p><blockquote><strong><em>When should I actually use a window function?</em></strong></blockquote><p>A SQL interview question rarely says:</p><blockquote><em>“Use a window function.”</em></blockquote><p>Instead, it gives you a business problem and expects you to figure out the right approach.</p><p>So in this article, I want to focus on the way I now think about window functions:</p><p><strong>How do I recognize the problem?</strong></p><p><strong>How do I construct the window?</strong></p><p><strong>And how do I prove that my query is actually correct?</strong></p><h3>1. Let’s Start With a Simple Dataset</h3><p>Throughout this article, I’ll use the same orders table.</p><p>| order_id | customer_id | order_date | amount |<br>| — — — — — | — — — — — — -| — — — — — — | — — — -:|<br>| 1 | 101 | 2026–01–01 | 100 |<br>| 2 | 101 | 2026–01–05 | 200 |<br>| 3 | 101 | 2026–01–10 | 300 |<br>| 4 | 102 | 2026–01–02 | 150 |<br>| 5 | 102 | 2026–01–08 | 250 |<br>| 6 | 103 | 2026–01–03 | 500 |</p><p>Imagine I’m working as a data analyst and someone asks:</p><blockquote><strong><em>“What is the total amount spent by each customer?”</em></strong></blockquote><p>My first instinct would probably be:</p><pre>SELECT<br>    customer_id,<br>    SUM(amount) AS total_spend<br>FROM orders<br>GROUP BY customer_id;</pre><p>The result is:</p><p>| customer_id | total_spend |<br>| — — — — — — -| — — — — — — :|<br>| 101 | 600 |<br>| 102 | 400 |<br>| 103 | 500 |</p><p>Perfect.</p><p>But notice what happened.</p><p>We started with <strong>6 rows</strong> and ended with <strong>3 rows</strong>.</p><p>GROUP BY combined the rows.</p><h3>2. What If I Don’t Want to Lose the Rows?</h3><p>Now imagine the question changes:</p><blockquote><strong><em>“Show every order together with the customer’s total spending.”</em></strong></blockquote><p>Now GROUP BY isn&#39;t enough.</p><p>I still want to see:</p><ul><li>the individual order</li><li>the order date</li><li>the amount</li></ul><p>But I also want:</p><ul><li>the customer’s total spending</li></ul><p>This is where a window function becomes useful.</p><pre>SELECT<br>    order_id,<br>    customer_id,<br>    order_date,<br>    amount,<br>    SUM(amount) OVER (<br>        PARTITION BY customer_id<br>    ) AS customer_total<br>FROM orders;</pre><p>The result:</p><p>| order_id | customer_id | order_date | amount | customer_total |<br>| — — — — — | — — — — — — -| — — — — — — | — — — -:| — — — — — — — -:|<br>| 1 | 101 | 2026–01–01 | 100 | 600 |<br>| 2 | 101 | 2026–01–05 | 200 | 600 |<br>| 3 | 101 | 2026–01–10 | 300 | 600 |<br>| 4 | 102 | 2026–01–02 | 150 | 400 |<br>| 5 | 102 | 2026–01–08 | 250 | 400 |<br>| 6 | 103 | 2026–01–03 | 500 | 500 |</p><p>Now we still have <strong>6 rows</strong>.</p><p>The window function calculated something across the rows without collapsing them.</p><h3>This gives me my first rule:</h3><blockquote><strong><em>GROUP BY reduces rows. Window functions preserve rows.</em></strong></blockquote><p><strong>Visual suggestion:</strong><br>Create a simple image showing:</p><pre>GROUP BY<br>6 rows<br>   ↓<br>3 rows<br><br><br>Window Function<br>6 rows<br>   ↓<br>6 rows + additional information</pre><h3>3. The Question I Ask Before Using a Window Function</h3><p>When I see a SQL problem, I now ask:</p><blockquote><strong><em>“Do I need information from other rows while still keeping my current row?”</em></strong></blockquote><p>If the answer is <strong>yes</strong>, a window function is a strong candidate.</p><p>For example:</p><blockquote><em>“Show every employee’s salary and the average salary of their department.”</em></blockquote><p>I don’t want to turn 20 employees into a few department-level rows.</p><p>I want every employee to remain visible.</p><p>So:</p><pre>AVG(salary) OVER (<br>    PARTITION BY department<br>)</pre><p>makes sense.</p><h3>4. Understanding the Anatomy of a Window Function</h3><p>Most window functions follow this general structure:</p><pre>FUNCTION(column) OVER (<br>    PARTITION BY ...<br>    ORDER BY ...<br>    ROWS BETWEEN ...<br>)</pre><p>Not every part is required.</p><p>For example:</p><pre>SUM(amount) OVER ()</pre><p>uses the entire result set.</p><p>Or:</p><pre>SUM(amount) OVER (<br>    PARTITION BY customer_id<br>)</pre><p>calculates separately for each customer.</p><p>Or:</p><pre>SUM(amount) OVER (<br>    PARTITION BY customer_id<br>    ORDER BY order_date<br>)</pre><p>calculates within each customer while respecting the order of the rows.</p><p>I like to break the window down into three questions:</p><pre>WINDOW FUNCTION<br>                    |<br>       ┌────────────┼────────────┐<br>       ↓            ↓            ↓<br>  PARTITION BY    ORDER BY     WINDOW FRAME<br>       |            |            |<br> &quot;Who belongs?&quot; &quot;What order?&quot; &quot;Which rows?&quot;</pre><p>And then the function itself answers:</p><pre>&quot;What calculation do I want?&quot;</pre><h3>5. PARTITION BY — Who Belongs Together?</h3><p>Let’s go back to:</p><pre>SUM(amount) OVER (<br>    PARTITION BY customer_id<br>)</pre><p>The important part is:</p><pre>PARTITION BY customer_id</pre><p>This tells SQL:</p><blockquote><strong><em>“Calculate separately for each customer.”</em></strong></blockquote><p>For customer 101:</p><pre>100<br>200<br>300</pre><p>The total is:</p><pre>600</pre><p>For customer 102:</p><pre>150<br>250</pre><p>The total is:</p><pre>400</pre><p>And because this is a window function, SQL puts the result back onto the original rows.</p><h3>Mental model</h3><p>Think of PARTITION BY as creating temporary groups <strong>for the calculation</strong>, without actually collapsing the result.</p><p><strong>Visual suggestion:</strong></p><p>Create an image where the six orders are separated visually into:</p><pre>Customer 101<br>────────────<br>100<br>200<br>300<br>  ↓<br>600<br></pre><pre>Customer 102<br>────────────<br>150<br>250<br>  ↓<br>400<br></pre><pre>Customer 103<br>────────────<br>500<br>  ↓<br>500</pre><p>Then show that the result is attached back to each original row.</p><h3>6. ORDER BY — In What Order?</h3><p>Now let’s change the question:</p><blockquote><strong><em>“Show each order together with the customer’s running total.”</em></strong></blockquote><p>Now order matters.</p><p>For customer 101:</p><p>| Date | Amount |<br>| — — — | — — — -:|<br>| Jan 1 | 100 |<br>| Jan 5 | 200 |<br>| Jan 10 | 300 |</p><p>The running total should be:</p><p>| Date | Amount | Running Total |<br>| — — — | — — — -:| — — — — — — — :|<br>| Jan 1 | 100 | 100 |<br>| Jan 5 | 200 | 300 |<br>| Jan 10 | 300 | 600 |</p><p>So we need:</p><pre>SUM(amount) OVER (<br>    PARTITION BY customer_id<br>    ORDER BY order_date<br>    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW<br>) AS running_total</pre><p>The important addition is:</p><pre>ORDER BY order_date</pre><p>It tells SQL:</p><blockquote><strong><em>“Evaluate these rows in this order.”</em></strong></blockquote><p>This is why ORDER BY becomes important for:</p><ul><li>Running totals</li><li>Rankings</li><li>Previous/next row comparisons</li><li>Time-series calculations</li></ul><h3>7. Window Frames — Which Rows Should Be Included?</h3><p>This is probably one of the more confusing parts of window functions.</p><p>Consider:</p><pre>ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW</pre><p>It means:</p><blockquote><em>Start at the first row and continue through the current row.</em></blockquote><p>For our customer:</p><pre>100<br>200<br>300</pre><p>The calculation becomes:</p><pre>Row 1:<br>100</pre><pre>Row 2:<br>100 + 200 = 300</pre><pre>Row 3:<br>100 + 200 + 300 = 600</pre><p>So:</p><p>| Date | Amount | Running Total |<br>| — — — — | — — — -:| — — — — — — — :|<br>| Jan 1 | 100 | 100 |<br>| Jan 5 | 200 | 300 |<br>| Jan 10 | 300 | 600 |</p><p>Another example</p><p>Suppose we write:</p><pre>ROWS BETWEEN 2 PRECEDING AND CURRENT ROW</pre><p>This means:</p><blockquote><em>Include the current row and the two rows before it.</em></blockquote><p>That can be useful for a moving average:</p><pre>AVG(amount) OVER (<br>    ORDER BY order_date<br>    ROWS BETWEEN 2 PRECEDING AND CURRENT ROW<br>) AS moving_average</pre><h3>8. SUM() — Total vs Running Total</h3><p>SUM() is one of the easiest window functions to understand.</p><h3>Total per customer</h3><pre>SUM(amount) OVER (<br>    PARTITION BY customer_id<br>) AS customer_total</pre><p>Think:</p><blockquote><strong><em>“What is the customer’s total?”</em></strong></blockquote><h3>Running total</h3><pre>SUM(amount) OVER (<br>    PARTITION BY customer_id<br>    ORDER BY order_date<br>    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW<br>) AS running_total</pre><p>Think:</p><blockquote><strong><em>“How much has the customer spent up to this point?”</em></strong></blockquote><p>The words in the question are important.</p><p>If you see:</p><ul><li>total</li><li>cumulative</li><li>running</li><li>accumulated</li><li>up to this point</li></ul><p>you should start thinking about SUM() OVER().</p><h3>9. AVG() — Compare a Row With a Group</h3><p>Suppose we have:</p><pre>employees</pre><p>with:</p><pre>employee_id<br>department<br>salary</pre><p>The question is:</p><blockquote><em>“Show each employee’s salary and the average salary in their department.”</em></blockquote><p>We can write:</p><pre>SELECT<br>    employee_id,<br>    department,<br>    salary,<br>    AVG(salary) OVER (<br>        PARTITION BY department<br>    ) AS department_avg<br>FROM employees;</pre><p>Now every employee can be compared against the department average.</p><p>We can even calculate the difference:</p><pre>salary -<br>AVG(salary) OVER (<br>    PARTITION BY department<br>) AS difference_from_average</pre><p>This is a very common analytics pattern:</p><pre>Individual value<br>       ↓<br>Group average<br>       ↓<br>Compare</pre><h3>10. COUNT() — Count Without Losing Rows</h3><p>Suppose I want to know how many orders each customer has made.</p><p>With GROUP BY:</p><pre>SELECT<br>    customer_id,<br>    COUNT(*) AS order_count<br>FROM orders<br>GROUP BY customer_id;</pre><p>This gives:</p><p>| customer_id | order_count |<br>| — — — — — — -| — — — — — — :|<br>| 101 | 3 |<br>| 102 | 2 |<br>| 103 | 1 |</p><p>But if I want the count attached to every order:</p><pre>COUNT(*) OVER (<br>    PARTITION BY customer_id<br>) AS order_count</pre><p>Result:</p><p>| order_id | customer_id | amount | order_count |<br>| — — — — — | — — — — — — -| — — — -:| — — — — — — :|<br>| 1 | 101 | 100 | 3 |<br>| 2 | 101 | 200 | 3 |<br>| 3 | 101 | 300 | 3 |<br>| 4 | 102 | 150 | 2 |<br>| 5 | 102 | 250 | 2 |<br>| 6 | 103 | 500 | 1 |</p><p>Again:</p><blockquote><strong><em>The calculation happens across rows, but the rows remain.</em></strong></blockquote><h3>11. ROW_NUMBER() — Give Every Row a Position</h3><p>Now imagine the question:</p><blockquote><em>“Number each customer’s orders chronologically.”</em></blockquote><p>We can use:</p><pre>ROW_NUMBER() OVER (<br>    PARTITION BY customer_id<br>    ORDER BY order_date<br>) AS order_number</pre><p>Result:</p><p>| customer_id | order_date | amount | order_number |<br>| — — — — — — -| — — — — — — | — — — -:| — — — — — — -:|<br>| 101 | Jan 1 | 100 | 1 |<br>| 101 | Jan 5 | 200 | 2 |<br>| 101 | Jan 10 | 300 | 3 |<br>| 102 | Jan 2 | 150 | 1 |<br>| 102 | Jan 8 | 250 | 2 |</p><p>Notice that the numbering starts again at 1 for every customer.</p><p>That’s because of:</p><pre>PARTITION BY customer_id</pre><h3>12. Finding the Latest Record With ROW_NUMBER()</h3><p>This is one of the patterns I find especially useful.</p><p>Suppose the question is:</p><blockquote><strong><em>“Find the latest order for every customer.”</em></strong></blockquote><p>First, number the orders in descending order:</p><pre>WITH ranked_orders AS (<br>    SELECT<br>        *,<br>        ROW_NUMBER() OVER (<br>            PARTITION BY customer_id<br>            ORDER BY order_date DESC<br>        ) AS rn<br>    FROM orders<br>)<br>SELECT *<br>FROM ranked_orders<br>WHERE rn = 1;</pre><p>Why does this work?</p><p>For customer 101:</p><p>| order_date | amount | rn |<br>| — — — — — — | — — — -:| — -:|<br>| Jan 10 | 300 | 1 |<br>| Jan 5 | 200 | 2 |<br>| Jan 1 | 100 | 3 |</p><p>The latest order is simply:</p><pre>rn = 1</pre><p>This pattern is extremely common in SQL interviews and real-world data work.</p><h3>13. ROW_NUMBER() vs RANK() vs DENSE_RANK()</h3><p>These three are easy to mix up.</p><p>Let’s use salaries:</p><p>| Employee | Salary |<br>| — — — — — | — — — -:|<br>| A | 100000 |<br>| B | 100000 |<br>| C | 90000 |<br>| D | 80000 |</p><h3>ROW_NUMBER()</h3><pre>ROW_NUMBER() OVER (<br>    ORDER BY salary DESC<br>)</pre><p>Result:</p><p>| Employee | Salary | Result |<br>| — — — — — | — — — -:| — — — -:|<br>| A | 100000 | 1 |<br>| B | 100000 | 2 |<br>| C | 90000 | 3 |<br>| D | 80000 | 4 |</p><p>Every row gets a unique number.</p><h3>RANK()</h3><pre>RANK() OVER (<br>    ORDER BY salary DESC<br>)</pre><p>Result:</p><p>| Employee | Salary | Result |<br>| — — — — — | — — — -:| — — — -:|<br>| A | 100000 | 1 |<br>| B | 100000 | 1 |<br>| C | 90000 | 3 |<br>| D | 80000 | 4 |</p><p>The tied rows share rank 1, so the next rank is 3.</p><h3>DENSE_RANK()</h3><pre>DENSE_RANK() OVER (<br>    ORDER BY salary DESC<br>)</pre><p>Result:</p><p>| Employee | Salary | Result |<br>| — — — — — | — — — -:| — — — -:|<br>| A | 100000 | 1 |<br>| B | 100000 | 1 |<br>| C | 90000 | 2 |<br>| D | 80000 | 3 |</p><p>The tied rows share the same rank, but there is no gap.</p><h3>The easiest way I remember them</h3><p>FunctionTies?Gaps?</p><p>ROW_NUMBER()No shared rank:- No</p><p>RANK()Same rank :- Yes</p><p>DENSE_RANK()Same rank:- No</p><h3>14. LAG() — Look at the Previous Row</h3><p>Now let’s move into something very useful for analytics.</p><p>Suppose we have daily revenue:</p><p>| Date | Revenue |<br>| — — — | — — — — :|<br>| Jan 1 | 100 |<br>| Jan 2 | 150 |<br>| Jan 3 | 120 |<br>| Jan 4 | 200 |</p><p>The question:</p><blockquote><strong><em>“How did today’s revenue change compared with yesterday?”</em></strong></blockquote><p>We need the previous row.</p><p>That’s where LAG() comes in:</p><pre>LAG(revenue) OVER (<br>    ORDER BY date<br>) AS previous_day_revenue</pre><p>Result:</p><p>| Date | Revenue | Previous Revenue |<br>| — — — | — — — — :| — — — — — — — — -:|<br>| Jan 1 | 100 | NULL |<br>| Jan 2 | 150 | 100 |<br>| Jan 3 | 120 | 150 |<br>| Jan 4 | 200 | 120 |</p><p>Now we can calculate:</p><pre>revenue -<br>LAG(revenue) OVER (<br>    ORDER BY date<br>) AS revenue_change</pre><p>Result:</p><p>| Date | Revenue | Revenue Change |<br>| — — — | — — — — :| — — — — — — — -:|<br>| Jan 1 | 100 | NULL |<br>| Jan 2 | 150 | 50 |<br>| Jan 3 | 120 | -30 |<br>| Jan 4 | 200 | 80 |</p><p>Whenever you see:</p><blockquote><em>“Compare the current row with the previous row”</em></blockquote><p>think:</p><p><strong>LAG()</strong></p><p>This is useful for:</p><ul><li>Day-over-day analysis</li><li>Month-over-month analysis</li><li>Revenue changes</li><li>Customer behavior</li><li>Status changes</li></ul><h3>15. LEAD() — Look at the Next Row</h3><p>LEAD() is essentially the opposite of LAG().</p><pre>LEAD(revenue) OVER (<br>    ORDER BY date<br>) AS next_day_revenue</pre><p>The easiest way to remember them:</p><pre>LAG<br> ↓<br>Look backward</pre><pre>LEAD<br> ↓<br>Look forward</pre><h3>16. FIRST_VALUE() and LAST_VALUE()</h3><p>These functions let us retrieve a value from another row within the window.</p><p>For example:</p><pre>FIRST_VALUE(salary) OVER (<br>    PARTITION BY department<br>    ORDER BY salary DESC<br>) AS highest_salary</pre><p>Now every employee can see the highest salary in their department.</p><p>These are useful when a problem asks you to compare the current row with:</p><ul><li>The first value</li><li>The initial value</li><li>The latest value</li><li>Another reference value within the group</li></ul><p>One important thing to remember with LAST_VALUE() is that <strong>the window frame matters</strong>. It is a function where explicitly defining the frame can prevent surprising results.</p><h3>17. How Do I Prove My Window Function Is Correct?</h3><p>This is probably the most important part of the article for me.</p><p>When learning SQL, it’s easy to write a query, see a result, and assume:</p><blockquote><em>“Looks right.”</em></blockquote><p>But that’s not enough.</p><p>I want to be able to <strong>prove the logic</strong>.</p><p>Let’s take:</p><pre>SUM(amount) OVER (<br>    PARTITION BY customer_id<br>)</pre><p>I’ll create a tiny dataset:</p><p>| customer_id | amount |<br>| — — — — — — -| — — — -:|<br>| 101 | 100 |<br>| 101 | 200 |<br>| 101 | 300 |</p><p>I can calculate manually:</p><pre>100 + 200 + 300 = 600</pre><p>Therefore, I expect:</p><p>| customer_id | amount | customer_total |<br>| — — — — — — -| — — — -:| — — — — — — — -:|<br>| 101 | 100 | 600 |<br>| 101 | 200 | 600 |<br>| 101 | 300 | 600 |</p><p>If SQL produces that result, the basic logic is correct.</p><h3>Proving a Running Total</h3><p>Now:</p><pre>SUM(amount) OVER (<br>    PARTITION BY customer_id<br>    ORDER BY order_date<br>    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW<br>)</pre><p>For:</p><p>| Date | Amount |<br>| — — — | — — — -:|<br>| Jan 1 | 100 |<br>| Jan 5 | 200 |<br>| Jan 10 | 300 |</p><p>I manually calculate:</p><pre>Jan 1<br>100</pre><pre>Jan 5<br>100 + 200 = 300</pre><pre>Jan 10<br>100 + 200 + 300 = 600</pre><p>Therefore I expect:</p><p>| Date | Amount | Running Total |<br>| — — — | — — — -:| — — — — — — — :|<br>| Jan 1 | 100 | 100 |<br>| Jan 5 | 200 | 300 |<br>| Jan 10 | 300 | 600 |</p><p>This is a simple but powerful way to validate a window function.</p><h3>18. My Window Function Checklist</h3><p>When I see a SQL problem, I now go through these questions.</p><h3>Question 1: Do I need information from other rows?</h3><p>If no, I probably don’t need a window function.</p><p>If yes, continue.</p><h3>Question 2: Do I need to keep the current row?</h3><p>If yes, a window function is a strong candidate.</p><h3>Question 3: Which rows belong together?</h3><p>Think:</p><pre>PARTITION BY</pre><h3>Question 4: Does the calculation depend on order?</h3><p>Think:</p><pre>ORDER BY</pre><h3>Question 5: Do I need to control exactly which rows participate?</h3><p>Think:</p><pre>ROWS BETWEEN ...</pre><h3>Question 6: What calculation am I actually trying to perform?</h3><p>RequirementFunctionTotalSUM()AverageAVG()CountCOUNT()MinimumMIN()MaximumMAX()Unique positionROW_NUMBER()Ranking with gapsRANK()Ranking without gapsDENSE_RANK()Previous rowLAG()Next rowLEAD()First valueFIRST_VALUE()Last valueLAST_VALUE()</p><h3>19. The Mental Model That Helped Me</h3><p>I no longer try to memorize window functions as a long list.</p><p>Instead, I break the problem down.</p><pre>WINDOW FUNCTION<br>                           |<br>             ┌─────────────┼─────────────┐<br>             ↓             ↓             ↓<br>        PARTITION BY     ORDER BY      FRAME<br>             |             |             |<br>       &quot;Who belongs?&quot;  &quot;What order?&quot;  &quot;Which rows?&quot;<br>                           |<br>                           ↓<br>                   What calculation?<br>                           |<br>          ┌────────┬───────┼───────┬────────┐<br>          ↓        ↓       ↓       ↓        ↓<br>         SUM      AVG     COUNT    RANK     LAG<br>                                   ↓        ↓<br>                              ROW_NUMBER   LEAD</pre><p>Once I started thinking this way, window functions became much less intimidating.</p><p>Instead of asking:</p><blockquote><em>“Which syntax do I remember?”</em></blockquote><p>I started asking:</p><blockquote><em>“What relationship between rows am I trying to express?”</em></blockquote><p>That’s a much better question.</p><h3>20. Common Problem → Window Function Mapping</h3><p>Here’s the cheat sheet I now use mentally:</p><p>If the question says…Think about…</p><p>Total for each customer, but keep every orderSUM() OVER(PARTITION BY...)</p><p>Running totalSUM() OVER(ORDER BY...)</p><p>Average within a groupAVG() OVER(PARTITION BY...)</p><p>Number of rows within a groupCOUNT() OVER(PARTITION BY...)</p><p>First/latest recordROW_NUMBER()</p><p>Rank employees by salaryRANK() / DENSE_RANK()</p><p>Previous day&#39;s valueLAG()</p><p>Next day&#39;s valueLEAD()</p><p>Compare current value with group averageAVG() OVER(...)</p><p>Moving averageAVG() OVER(... ROWS BETWEEN...)</p><h3>Final Thoughts</h3><p>The biggest lesson I’ve learned is that SQL isn’t just about remembering functions.</p><p>It’s about recognizing patterns.</p><p>When you see:</p><blockquote><strong><em>“Calculate the total but keep every transaction.”</em></strong></blockquote><p>Think:</p><p>SUM() OVER()</p><p>When you see:</p><blockquote><strong><em>“Find the latest record for every customer.”</em></strong></blockquote><p>Think:</p><p>ROW_NUMBER()</p><p>When you see:</p><blockquote><strong><em>“Compare today’s value with yesterday’s.”</em></strong></blockquote><p>Think:</p><p>LAG()</p><p>When you see:</p><blockquote><strong><em>“Calculate a cumulative total.”</em></strong></blockquote><p>Think:</p><p>SUM() OVER(ORDER BY ...)</p><p>And when you’re unsure whether your query is correct:</p><blockquote><strong><em>Create a tiny dataset and prove the result manually.</em></strong></blockquote><p>For me, that’s the difference between:</p><p><strong>“I know window-function syntax.”</strong></p><p>and:</p><p><strong>“I understand window functions.”</strong></p><h3>One final mental model</h3><p>If I had to summarize window functions in one picture, it would be this:</p><pre>Do I need another row&#39;s information?<br>                            |<br>                           YES<br>                            ↓<br>                 Do I need to keep my row?<br>                            |<br>                           YES<br>                            ↓<br>                     WINDOW FUNCTION<br>                            |<br>              ┌─────────────┼─────────────┐<br>              ↓             ↓             ↓<br>         PARTITION BY     ORDER BY       FRAME<br>              ↓             ↓             ↓<br>         Who belongs?    What order?   Which rows?<br>                            |<br>                            ↓<br>                      Choose function<br>                            |<br>       ┌──────────┬────────┼────────┬──────────┐<br>       ↓          ↓        ↓        ↓          ↓<br>      SUM        AVG      COUNT    RANK       LAG<br>      ↓          ↓        ↓        ↓          ↓<br>   totals     averages   counts  ranking   previous</pre><p>Once you can answer those questions, you don’t have to memorize every window-function problem.</p><p>You can <strong>build the solution from the problem itself</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1b2ff614b47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digital Analytics : A Beginner’s Guide to Reading Your Website’s Mind]]></title>
            <link>https://medium.com/@charankumarkharade2003/digital-analytics-a-beginners-guide-to-reading-your-website-s-mind-07124446ab30?source=rss-25cfd879d39e------2</link>
            <guid isPermaLink="false">https://medium.com/p/07124446ab30</guid>
            <category><![CDATA[digital-marketing-analyst]]></category>
            <category><![CDATA[ga4]]></category>
            <category><![CDATA[social-media-marketing]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[gtm]]></category>
            <dc:creator><![CDATA[Charan Kumar Kharade Somoji Rao]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 05:47:38 GMT</pubDate>
            <atom:updated>2026-08-16T05:47:38.717Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine opening a brick-and-mortar clothing shop. Every day, people walk through the door. Some browse the sweater rack, some try on jeans, and a few buy something at the register.</p><p>Now imagine you are blindfolded. You can hear the cash register ring, but you have no idea which rack people visited, how long they stayed, or why half of them walked out without buying a thing.</p><p>That is what running a website without <strong>digital analytics</strong> feels like.</p><p>At its simplest, digital analytics is the process of collecting and understanding user behavior online. It turns invisible web visitors into real insights so you can stop guessing what works and start knowing.</p><h3>1. UTM Parameters: Giving Your Links “Name Tags”</h3><p>Before you can analyze what people do on your site, you need to know <strong>how they got there</strong>.</p><p>If 50 people visit your website today, did they find you on Google? Did they click an Instagram bio link? Or did they open your weekly email?</p><p>To answer this, marketers use <strong>UTM parameters</strong> (short for Urchin Tracking Module — a fancy name for a simple concept). A UTM is just a extra bit of text added to the end of a regular link, like a digital name tag.</p><p>A tagged link looks like this:</p><blockquote>[yoursite.com/?utm_source=instagram&amp;utm_medium=social&amp;utm_campaign=summer_sale](https://yoursite.com/?utm_source=instagram&amp;utm_medium=social&amp;utm_campaign=summer_sale)</blockquote><p>Think of it as filling out three quick labels:</p><ul><li><strong>Source (</strong><strong>utm_source):</strong> <em>Where did they come from?</em> (e.g., instagram, google, newsletter)</li><li><strong>Medium (</strong><strong>utm_medium):</strong> <em>How did they get here?</em> (e.g., social, email, paid-ad)</li><li><strong>Campaign (</strong><strong>utm_campaign):</strong> <em>Why are we sending them?</em> (e.g., summer_sale, product_launch)</li></ul><p>When someone clicks a UTM link, your analytics software reads the label and records exactly which effort brought that visitor to your door.</p><h3>2. The Beginner’s Toolkit: Who Does What?</h3><p>The world of analytics tools can feel overwhelming, but most beginner tools fall into three simple categories:</p><h3>Google Analytics 4 (GA4) — The Big Picture</h3><p>GA4 is the free industry standard. It answers high-level questions: How many people visited today? Which pages are most popular? Did visitors actually buy something or sign up? GA4 tracks everything as “events” (clicks, page scrolls, downloads).</p><h3>Hotjar or Microsoft Clarity — The Visual Heatmaps</h3><p>While GA4 gives you numbers, heatmap tools give you <strong>pictures</strong>. They show you a color-coded map of where users actually move their mouse, where they scroll, and where they click. If users keep clicking an image thinking it’s a button, a heatmap will show you instantly.</p><h3>Google Tag Manager (GTM) — The Helper Tool</h3><p>Normally, adding tracking codes to a website requires editing website code. GTM acts as a middleman — a single container where you can add or remove tracking tools without having to ask a web developer for help every time.</p><h3>3. How It All Fits Together (A Quick Example)</h3><p>Here is a 30-second look at how a beginner uses analytics in real life:</p><ol><li><strong>You share a link:</strong> You post a new blog link on LinkedIn using a <strong>UTM tag</strong> (utm_source=linkedin).</li><li><strong>You track the visit:</strong> A user clicks it. <strong>GA4</strong> logs a new visitor from LinkedIn and tracks that they stayed on the page for 2 minutes.</li><li><strong>You spot a problem:</strong> You check <strong>Hotjar</strong> and notice users keep scrolling down to a button, but 80% stop scrolling before reaching it.</li><li><strong>You fix it:</strong> You move the button higher up the page. Now, twice as many people click it.</li></ol><p>Digital analytics isn’t about mastering complex math or staring at spreadsheets all day — it’s simply about listening to what your visitors are doing so you can make their experience better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07124446ab30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Apache Spark: A Deep Dive into RDDs]]></title>
            <link>https://medium.com/@charankumarkharade2003/demystifying-apache-spark-a-deep-dive-into-rdds-ba7e30dc41b5?source=rss-25cfd879d39e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba7e30dc41b5</guid>
            <dc:creator><![CDATA[Charan Kumar Kharade Somoji Rao]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 18:37:05 GMT</pubDate>
            <atom:updated>2026-06-20T18:37:05.295Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why every Spark developer — even one who never writes a line of RDD code — needs to understand what’s running underneath their DataFrames.</em></p><p>If you’re stepping into Big Data, you’ll quickly meet Apache Spark, and with it, terms like DataFrames, Datasets, and Spark SQL. But to really master Spark — and to avoid the performance traps that catch junior developers — you need to understand its foundational unit: the <strong>Resilient Distributed Dataset (RDD)</strong>.</p><p>This guide breaks down what an RDD is, why it exists, how it works under the hood, and when you’d actually reach for one today.</p><h3>What is an RDD? Breaking down the acronym</h3><p>Before any code or architecture, let’s unpack the three letters:</p><ul><li><strong>Resilient (fault-tolerant):</strong> if a machine holding part of your data fails, Spark can recreate the lost data instantly, without restarting the whole job.</li><li><strong>Distributed (parallel):</strong> your data isn’t sitting on one laptop. It’s sliced into <strong>partitions</strong> and spread across a cluster of machines, all processing simultaneously.</li><li><strong>Dataset (the collection):</strong> at its core, it’s just a collection of objects — lines from a log file, tuples, rows of numbers, anything.</li></ul><p><strong>In one line:</strong> an RDD is a large collection of data, sliced into pieces, spread across a network of computers, with a built-in safety net so it’s never truly lost.</p><h3>Where an RDD lives: the driver–executor architecture</h3><p>To understand how RDDs move through a cluster, picture three layers:</p><ol><li><strong>The driver program</strong> — the brain of your application. It holds the SparkSession, turns your code into an execution plan, and coordinates the work.</li><li><strong>The cluster manager</strong> — an external orchestrator (YARN, Kubernetes, or Spark Standalone) that hands the driver physical resources.</li><li><strong>Worker nodes and executors</strong> — the physical machines (workers) run executor processes, which pull tasks from the driver, load RDD partitions into memory, and run the actual computation.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*7OuVLYxTDfkIDmSjDpMz6Q.png" /></figure><p>The diagram above shows this flow: the driver requests resources from the cluster manager, which allocates worker nodes; the driver then schedules tasks directly onto the executors holding the relevant partitions. If an executor goes down, the driver doesn’t restart everything — it just recomputes the lost partitions.</p><h3>The five pillars of an RDD</h3><p>Internally, every RDD tracks five things to manage its distributed life. Understanding these is understanding Spark’s real mechanics.</p><h3>1. A list of partitions</h3><p>An RDD is physically made of partitions — atomic chunks of data assigned to executors. Partition count determines parallelism: 10 cores but only 2 partitions means 8 cores sit idle.</p><h3>2. A function for computing each split</h3><p>Every RDD knows exactly what computation to apply to its partitions — a map, a filter, whatever the operation is — and carries that logic with it.</p><h3>3. A list of dependencies — the lineage graph</h3><p>This is the core trick. RDDs are <strong>immutable</strong>: once created, they never change. Transform one, and Spark builds a brand-new RDD that records its parent as a dependency. Chain enough of these and you get a <strong>lineage graph</strong>, a directed acyclic graph (DAG) of how every RDD was derived.</p><p>If a partition is lost to a hardware failure, Spark doesn’t recompute the whole dataset — it walks the lineage graph back to the parent partition and the function that produced the lost one, and recomputes <em>only that partition</em>. That’s the “resilient” in RDD, made concrete.</p><h3>4. A partitioner (optional, for key-value RDDs)</h3><p>For key-value data, an optional partitioner (like a hash partitioner) decides which keys land on which partition — important for controlling joins and avoiding data skew.</p><h3>5. Preferred locations</h3><p>Spark follows the principle of <strong>data locality</strong>: moving a small piece of code to where data already lives is far cheaper than moving the data across the network. RDDs store metadata about where their underlying data physically resides (e.g. which HDFS nodes), so the driver can schedule tasks close to the data.</p><h3>Transformations vs. actions</h3><p>Two operation types govern how you work with RDDs, and confusing them is the most common cause of slow Spark jobs.</p><p><strong>Transformations</strong> (the recipe builders) take an RDD and return a new RDD — but do nothing immediately. Spark uses <strong>lazy evaluation</strong>: it just records the operation in a lineage “recipe.” Examples: map(), filter(), flatMap(), groupByKey(), reduceByKey().</p><p><strong>Actions</strong> (the chefs) demand a concrete result. When you call an action, Spark stops procrastinating — it optimizes the recorded lineage, fires up the executors, and runs the actual computation, either returning a result to the driver or writing data to storage. Examples: collect(), count(), first(), take(n), saveAsTextFile().</p><h3>Narrow vs. wide dependencies</h3><p>When Spark compiles your transformations, it classifies them by how data moves across the network — and this decides how your job is split into execution <strong>stages</strong>.</p><ul><li><strong>Narrow dependencies (no shuffle):</strong> each parent partition feeds at most one child partition. map() and filter() are narrow — data stays in the same executor&#39;s memory, with zero network overhead.</li><li><strong>Wide dependencies (the shuffle):</strong> multiple child partitions depend on a single parent partition. Operations like groupByKey() or join() force a <strong>shuffle</strong> — data gets redistributed across the network so matching keys land together. Shuffling is expensive, and it&#39;s the main bottleneck in most distributed Spark jobs.</li></ul><h3>So why learn RDDs if everyone uses DataFrames?</h3><h3>The truth under the hood</h3><p>To the executors, <strong>DataFrames don’t exist at runtime.</strong> A DataFrame is a developer-friendly abstraction with schemas — rows and named columns. When you run a DataFrame operation, Spark’s <strong>Catalyst optimizer</strong> reorders and optimizes your query, then compiles it down into the exact same thing every Spark job ultimately is: an <strong>RDD lineage graph</strong> of bytecode. Down at the execution layer, the cluster is exclusively computing RDD partitions in memory.</p><h3>When to write RDDs explicitly</h3><p>Default to DataFrames — Catalyst usually beats hand-written RDD code. Drop down to RDDs when:</p><ol><li><strong>Your data is unstructured</strong> — raw media, binary streams, unstructured text with no fixed schema.</li><li><strong>You need low-level control</strong> — passing raw domain objects through custom map functions, or building a custom partitioner for precise data placement.</li><li><strong>You’re maintaining legacy pipelines</strong> — older Spark 1.x-era code or libraries that predate the DataFrame API.</li></ol><h3>Cheat sheet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DM0QKQtdkOw0AGV2s28dwg.png" /></figure><h3>Takeaway</h3><p>Treat DataFrames as your everyday language, and RDDs as the ground truth underneath them. Once you understand partitions, lineage graphs, and the narrow/wide dependency split, you have an accurate mental model of exactly how your data moves — and fails over — across a Spark cluster.</p><p><em>If you found this useful, give it a clap and follow for more deep dives into distributed systems.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba7e30dc41b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding DataWarehouse, Data Lake and Data Lakehouse]]></title>
            <link>https://medium.com/@charankumarkharade2003/understanding-datawarehouse-data-lake-and-data-lakehouse-88b7d90c21e1?source=rss-25cfd879d39e------2</link>
            <guid isPermaLink="false">https://medium.com/p/88b7d90c21e1</guid>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[data-lake]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <dc:creator><![CDATA[Charan Kumar Kharade Somoji Rao]]></dc:creator>
            <pubDate>Wed, 06 May 2026 16:50:52 GMT</pubDate>
            <atom:updated>2026-05-06T16:59:08.350Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Most Data Champs often get confused between Data Warehouse, Data Lake and Data Lakehouse. I often used to get confused every time someone mentioned these terms as they all sounded a bit similar and knowing the differences is very important. So, lets break this confusion.</blockquote><p>Consider a company that’s been around for a few years. At the beginning, everything is simple — sales data, customer info, maybe some reports. Nothing too crazy.</p><p>As the company grows, data starts coming from other sources:-</p><ul><li>Website clicks</li><li>Mobile apps</li><li>Customer support chats</li><li>Marketing campaigns</li><li>Even random CSV files people forget about</li></ul><p>Now the question is: <strong>where does all this data go?</strong></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>First Attempt: The Data WareHouse</strong></p><p>The company decides to be disciplined.</p><p>“Let’s only store clean, structured, reliable data.”</p><p>So they build a <strong>Data Warehouse</strong>.</p><p>Before anything goes in, the data is cleaned, transformed, and structured. This process is usually done using <strong>ETL (Extract, Transform, Load)</strong> pipelines.</p><h3>Common tools used</h3><ul><li><strong>Snowflake</strong></li><li><strong>Amazon Redshift</strong></li><li><strong>Google BigQuery</strong></li><li>ETL tools like <strong>Apache Airflow</strong> or <strong>Informatica</strong></li></ul><h3>Languages used</h3><ul><li><strong>SQL (very important here)</strong></li><li>Sometimes Python for ETL scripts</li></ul><h3>Real-life example</h3><ul><li>Sales transactions from POS systems are cleaned and loaded daily</li><li>Customer data is standardized (same format for names, emails, etc.)</li><li>Finance dashboards are built using SQL queries in BigQuery or Snowflake</li><li>BI tools like <strong>Tableau</strong> or Power BI consume this data</li></ul><p>Analysts love it because:</p><ul><li>Queries are fast</li><li>Reports are consistent</li><li>Business KPIs match everywhere</li></ul><p>But there’s a catch.</p><p>Getting new data in takes time. Everything must be structured first.</p><p>So it’s great for reporting… but not flexible.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>Second Attempt: The Data Lake</strong></p><p>The company gets tired of delays.</p><p>“Why don’t we just store everything as it is?”</p><p>So they build a <strong>Data Lake</strong>.</p><p>Now data flows in raw, without strict structure.</p><h3>Common tools used</h3><ul><li><strong>Amazon S3</strong></li><li><strong>Azure Data Lake Storage</strong></li><li><strong>Hadoop HDFS</strong></li></ul><h3>Languages used</h3><ul><li>Python (very common for data processing)</li><li>PySpark / <strong>Apache Spark</strong></li><li>Java/Scala (for Spark/Hadoop ecosystems)</li></ul><h3>Real-life example</h3><ul><li>Website clickstream logs stored in S3 as JSON files</li><li>Mobile app events stored as raw event streams</li><li>Customer chat logs stored as text files</li><li>IoT sensor data dumped continuously</li></ul><p>Data scientists love this because they can experiment freely using:</p><ul><li>Python</li><li>Pandas</li><li>Spark MLlib</li></ul><p>But after some time, problems appear:</p><ul><li>Duplicate datasets</li><li>No clear ownership</li><li>Hard to know which data is reliable</li></ul><p>The lake slowly becomes a <strong>data swamp</strong>.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_pQhvzsSuvrbMBNHJO1jiQ.png" /><figcaption>Generated from AI</figcaption></figure><h3>The Turning Point: The Data Lakehouse</h3><p>Eventually, companies realize:</p><ul><li>Warehouse = too rigid</li><li>Lake = too messy</li></ul><p>So they combine both ideas into a <strong>Data Lakehouse</strong>.</p><h3>Common tools used</h3><ul><li><strong>Databricks</strong></li><li>Apache Spark (core engine again)</li><li>Delta Lake / Iceberg / Hudi (table formats)</li><li>Cloud storage like S3 or ADLS underneath</li></ul><h3>Languages used</h3><ul><li>SQL (for analytics)</li><li>Python (for ML &amp; processing)</li><li>Scala (in Spark ecosystems)</li></ul><h3>Real-life example</h3><ul><li>Raw data lands in S3 (like a lake)</li><li>Databricks organizes it into structured “Delta tables”</li><li>Analysts run SQL dashboards on the same data</li><li>Data scientists train ML models directly on it</li></ul><p>Now:</p><ul><li>Analysts get clean, reliable data</li><li>Engineers still access raw data</li><li>ML teams don’t need separate pipelines</li></ul><p>It brings everything into one system.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>So What’s the real Unterschied?</p><p>Here’s how I think about it now:</p><ul><li><strong>Data Warehouse → </strong>Clean, structured, reliable (but slower to adapt)</li><li><strong>Data Lake → </strong>Flexible, raw, scalable (but can get messy)</li><li><strong>Data Lakehouse →</strong>A balance of both (still evolving, but promising)</li></ul><p><strong>Final Though</strong></p><p>It depends on what the usecase needs:</p><ul><li>If reporting and dashboards is your priority → warehouse works great</li><li>If exploration and ML experiments matter → lake makes sense</li><li>If you want both → lakehouse</li></ul><p>And once you see it in real tools and real workflows, these terms stop sounding abstract… and start making practical sense.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88b7d90c21e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Data Factory: Understanding the 5 Roles That Power Modern Tech]]></title>
            <link>https://medium.com/@charankumarkharade2003/the-data-factory-understanding-the-5-roles-that-power-modern-tech-a17c257f7989?source=rss-25cfd879d39e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a17c257f7989</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[microsoft-fabric]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Charan Kumar Kharade Somoji Rao]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 12:08:51 GMT</pubDate>
            <atom:updated>2026-04-29T21:47:42.211Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Imagine walking into a massive, high-tech factory. Most visitors only see the gleaming finished data products — the colorful dashboards used by <strong>Data Analyst </strong>to answer “What happened?” or the complex AI inventions created by <strong>Data Scientists </strong>to predict “What will happen next?”. But before a single product can be made, someone has to build the machines, lay the pipes, and ensure the raw material — the data — actually arrives and make it useful for others put into production. Most importantly we should also have one person who tells how to build the data products!</blockquote><p><strong><em>The Visionary: The Data Architect</em></strong></p><p>Before a single pipe is laid, the data architect is the visionary who draws the master blueprints for the entire factory. They do not just look at one machine; they decide where the entire factory should be built and ensure every part connects according to long-term standards. They use high-level data models to ensure the system can scale for years to come.</p><p><strong><em>The Builder: The Data Engineer</em></strong></p><p>Once the Architect hands over the blueprints, the Data Engineer brings them to life in the factory basement. Known as the “<em>architect of the plumbing</em>”, this is the core of the operation. You use <em>SQL</em> like a master key to unlock raw data and <em>Python </em>to build high-speed assembly lines(pipelines) that move and clean data before anyone else can touch it. To show your expertise, you write “robust” code — like Python <em>try-except-blocks — </em>to keep the pipes from bursting when data gets messy.</p><p><strong><em>The Refiner: The Analytics Engineer</em></strong></p><p>As your assembly lines start moving, the Analytics Engineer takes over on the middle floor. They are the bridge between raw engineering and final product design. They take the raw materials you’ve delivered and use SQL to transform and refine them within the warehouse, making the data perfect for the specialists upstairs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jvw-9QWLr9EOPYOgCrAQRw.png" /><figcaption>Data Journey(Generated from Gem AI)</figcaption></figure><p><strong><em>The Storyteller: The Data Analyst</em></strong></p><p>On the main factory floor, the Data Analyst creates the storefront. They are the quality control and the primary communicators of the factory’s output. They inspect the refined data to create beautiful dashboards that answer the critical question: “What happened in the factory today?”</p><p><strong><em>The Inventor: The Data Scientist</em></strong></p><p>In the high-tech laboratory at the top, the Data Scientist experiments with the data. They are the factory’s inventors and future-thinkers. They use the data to build predictive models and perform advanced analysis to answer:”What will happen in our factory tomorrow?”</p><p>If you have any further questions or if you would like to make adjustments to this blog post or the workflow image, please feel free to message me below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a17c257f7989" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>