<?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 Alessandro Pizzini on Medium]]></title>
        <description><![CDATA[Stories by Alessandro Pizzini on Medium]]></description>
        <link>https://medium.com/@pizzini.alessandro?source=rss-86765ed9024------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4p4mvmOHoWBwnzeiNI-ZEg.jpeg</url>
            <title>Stories by Alessandro Pizzini on Medium</title>
            <link>https://medium.com/@pizzini.alessandro?source=rss-86765ed9024------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 18:03:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pizzini.alessandro/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[The SQL Techniques I Use the Most as a Data Engineer (And Why They Matter)]]></title>
            <link>https://medium.com/learning-sql/the-sql-techniques-i-use-the-most-as-a-data-engineer-and-why-they-matter-06f1fcc56cf2?source=rss-86765ed9024------2</link>
            <guid isPermaLink="false">https://medium.com/p/06f1fcc56cf2</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Alessandro Pizzini]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 08:02:03 GMT</pubDate>
            <atom:updated>2025-02-07T18:39:12.593Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PXYeSpQARwiwFugh" /><figcaption>Photo by <a href="https://unsplash.com/@lucabravo?utm_source=medium&amp;utm_medium=referral">Luca Bravo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a Data Engineer, SQL is an indispensable tool for <strong>transforming, optimizing, and managing large-scale data</strong>. From efficiently merging datasets with <strong>JOINs</strong> to handling <strong>semi-structured data with JSON processing</strong>, mastering SQL techniques is critical for <strong>ETL pipelines, data warehousing, and performance tuning</strong>.</p><p>In this article, we’ll explore the <strong>3</strong> <strong>most impactful SQL techniques</strong> — including <strong>Pivot-Unpivot transformations</strong>,<strong> Window Functions</strong>, and<strong> Except Distinct </strong>— and explain why they are crucial for scalable and efficient data engineering workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uNO7KcDgkOJYumEz" /><figcaption>Photo by <a href="https://unsplash.com/@daybrandon?utm_source=medium&amp;utm_medium=referral">Brandon Day</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, I’ll be using the <strong>public NYC Taxi Trips dataset</strong> from BigQuery to demonstrate these SQL techniques in action. This dataset, which contains millions of real taxi trip records, is perfect for showcasing data transformations, optimizations, and analytical queries at scale.</p><p>If you do not know how to use it, I’ve written one article that could help you about it.</p><p><a href="https://medium.com/@pizzini.alessandro/master-sql-for-free-on-gcp-bigquery-with-real-world-data-801c42944319">Master SQL for Free on GCP BigQuery with Real-World Data</a></p><h4>#1. <strong>Pivot-Unpivot Transformation with Key-Value Pair Mapping</strong></h4><blockquote>It is a powerful SQL technique that allows to <strong>dynamically restructures categorical data</strong> by converting multiple columns into key-value pairs, mapping encoded values to readable labels, and pivoting them back into a wide format for improved data clarity and analysis.</blockquote><p>So this technique is particularly useful when working with <strong>categorical variables </strong>and<strong> data dictionaries</strong> that store mappings for numeric or encoded values. Let’s see this in action against NYC Taxi Trips Dataset in BigQuery.</p><p>Let’s have a look at how the data look like before doing any transformation. As you can see form the below image rate_code and payment_type are categorical and their value do not provide any information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pWi4FzT9cWD8C98inM0AtQ.png" /></figure><p>Here below what the final query will look like:</p><pre>WITH dict AS (<br>    -- Lookup table containing mappings of code values to labels<br>    SELECT <br>        table_name, <br>        column_name,<br>        code_value,<br>        code_label<br>    FROM `your_project.dataset.data_dictionary`  -- Replace with your actual mapping table<br>),<br>mapped AS (<br>    -- Unpivot categorical columns dynamically<br>    SELECT <br>        trips.trip_id,  <br>        col.column_name,<br>        d.code_label<br>    FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022` trips<br>    CROSS JOIN UNNEST([<br>        STRUCT(&#39;payment_type&#39; AS column_name, CAST(trips.payment_type AS STRING) AS code_value),<br>        STRUCT(&#39;rate_code&#39; AS column_name, CAST(trips.rate_code AS STRING) AS code_value)<br>    ]) col<br>    LEFT JOIN dict d<br>    ON col.column_name = d.column_name <br>    AND col.code_value = d.code_value<br>)<br>-- Pivot the results back into a wide format<br>SELECT <br>    trips.trip_id,<br>    MAX(CASE WHEN UPPER(column_name) = &#39;PAYMENT_TYPE&#39; THEN code_label END) AS payment_type_label,<br>    MAX(CASE WHEN UPPER(column_name) = &#39;RATE_CODE&#39; THEN code_label END) AS rate_code_label,<br>    MAX(CASE WHEN UPPER(column_name) = &#39;STORE_AND_FWD_FLAG&#39; THEN code_label END) AS store_and_fwd_label<br>FROM mapped<br>JOIN `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022` trips<br>ON mapped.trip_id = trips.trip_id</pre><p><strong>Step 1 — Create a Mapping Table (dict)<br></strong>The dictionary table holds the <strong>mapping of encoded values to readable labels</strong>. Since for this example it does not exists, let’s create one based on the metadata information of the <em>tlc_yellow_trips_2022</em> table</p><pre>CREATE TABLE `your_project.dataset.data_dictionary` (<br>    table_name STRING,      -- Name of the table<br>    column_name STRING,     -- Name of the column<br>    code_value STRING,      -- Encoded value (e.g., categorical code)<br>    code_label STRING       -- Human-readable label for the code<br>);<br><br>INSERT INTO `your_project.dataset.data_dictionary` (table_name, column_name, code_value, code_label)<br>VALUES<br>    (&#39;tlc_yellow_trips_2022&#39;, &#39;rate_code&#39;, &#39;1.0&#39;, &#39;Standard Rate&#39;),<br>    (&#39;tlc_yellow_trips_2022&#39;, &#39;rate_code&#39;, &#39;2.0&#39;, &#39;JFK&#39;),<br>    (&#39;tlc_yellow_trips_2022&#39;, &#39;rate_code&#39;, &#39;3.0&#39;, &#39;Newark&#39;),<br>    (&#39;tlc_yellow_trips_2022&#39;, &#39;rate_code&#39;, &#39;4.0&#39;, &#39;Nassau or Westchester&#39;),<br>    (&#39;tlc_yellow_trips_2022&#39;, &#39;rate_code&#39;, &#39;5.0&#39;, &#39;Negotiated&#39;),<br>    (&#39;tlc_yellow_trips_2022&#39;, &#39;rate_code&#39;, &#39;6.0&#39;, &#39;Group Ride&#39;),<br>    (&#39;tlc_yellow_trips_2022&#39;, &#39;payment_type&#39;, &#39;1&#39;, &#39;Credit Card&#39;),<br>    (&#39;tlc_yellow_trips_2022&#39;, &#39;payment_type&#39;, &#39;2&#39;, &#39;Cash&#39;),<br>    (&#39;tlc_yellow_trips_2022&#39;, &#39;payment_type&#39;, &#39;3&#39;, &#39;No Charge&#39;),<br>    (&#39;tlc_yellow_trips_2022&#39;, &#39;payment_type&#39;, &#39;4&#39;, &#39;Dispute&#39;),<br>    (&#39;tlc_yellow_trips_2022&#39;, &#39;payment_type&#39;, &#39;5&#39;, &#39;Unknown&#39;),<br>    (&#39;tlc_yellow_trips_2022&#39;, &#39;payment_type&#39;, &#39;6&#39;, &#39;Voided Trip&#39;)<br>;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VADc6GEt1-MCtV0i4jTcHQ.png" /><figcaption>data_dictionary table</figcaption></figure><p><strong>Step 2: Unpivot Categorical Columns (Key-Value Transformation)<br></strong>This is the step that really make the difference and could help us to scale the query as much as we want. Now, instead of multiple categorical columns, we have <strong>column_name, code_value</strong>. In order to do use and to avoid manually writing multiple LEFT JOINs for each column, we have <strong>dynamically generate the SQL query</strong> in BigQuery using <strong>ARRAYS and UNNEST()</strong>.</p><pre>WITH dict AS (<br>    -- Lookup table containing mappings of code values to labels<br>    SELECT <br>        table_name, <br>        column_name,<br>        code_value,<br>        code_label<br>    FROM `your_project.dataset.data_dictionary`  -- Replace with your actual mapping table<br>)<br>-- Unpivot categorical columns dynamically<br>SELECT <br>    trips.trip_id,  <br>    col.column_name,<br>    d.code_label<br>FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022` trips<br>CROSS JOIN UNNEST([<br>    STRUCT(&#39;payment_type&#39; AS column_name, trips.payment_type AS code_value),<br>    STRUCT(&#39;rate_code&#39; AS column_name, trips.rate_code AS code_value)<br>]) col<br>LEFT JOIN dict d<br>ON col.column_name = d.column_name <br>AND col.code_value = d.code_value<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6BsrwgaVPTe0UVPezlLuQ.png" /><figcaption>unpivoted data</figcaption></figure><p><strong>Step 3: Join with the Dictionary Table<br></strong>TheLEFT JOIN transforms encoded values into <strong>human-readable labels</strong>. As demonstrated, we successfully mapped encoded values to readable labels for two columns by joining them with the data_dictionary table. This approach becomes especially useful when dealing with multiple columns, allowing you to maintain both readability and scalability in your SQL code.</p><p><strong>Step 4: Pivot the Data Back (Wide Format)<br></strong>Uses MAX(CASE WHEN column_name = ‘X’ THEN label END) to reconstruct the dataset.</p><pre>-- Pivot the results back into a wide format<br>SELECT <br>    trips.trip_id,<br>    MAX(CASE WHEN UPPER(column_name) = &#39;PAYMENT_TYPE&#39; THEN code_label END) AS payment_type_label,<br>    MAX(CASE WHEN UPPER(column_name) = &#39;RATE_CODE&#39; THEN code_label END) AS rate_code_label,<br>    MAX(CASE WHEN UPPER(column_name) = &#39;STORE_AND_FWD_FLAG&#39; THEN code_label END) AS store_and_fwd_label<br>FROM mapped<br>JOIN `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022` trips<br>ON mapped.trip_id = trips.trip_id</pre><h4>#2. SQL Windows Function</h4><blockquote>Window functions in SQL are “specialized tools” that <strong>operate over a window (range of rows) </strong>defined using the OVER clause, offering a powerful way to analyze and manipulate data.</blockquote><p>The following are examples of what can be calculated using winodw functions:</p><ul><li><strong><em>Ranking — </em></strong>Assigns a unique rank to each row based on specified criteria, enabling the arrangement of data in a meaningful order.</li><li><strong><em>Running Totals — </em></strong>Computes the cumulative sum of a designated column, useful for tracking ongoing trends.</li><li><strong><em>Moving Average</em></strong> — Calculates the average of a specified column within a moving window of rows, useful to highlighting patterns in the data.</li></ul><p>If you want to read more about them, I’ve written a specific article on Windows Function <a href="https://medium.com/@pizzini.alessandro/data-engineers-arsenal-4-must-know-sql-window-functions-e45bf6ae8528">here on Medium</a></p><p><a href="https://medium.com/@pizzini.alessandro/data-engineers-arsenal-4-must-know-sql-window-functions-e45bf6ae8528">Data Engineer’s Arsenal: 4 Must-Know SQL Window Functions</a></p><p>Let see one function in action against NY Taxi Trips Data. The query below computes a running total of the trip distances for each taxi trip within its corresponding vendor category. The SUM() window function is applied over a specified partition defined by vendor_id and ordered by pickup_datetime, resulting in a dynamic running sum that accumulates the trip distances as rows are processed.</p><pre>SELECT<br>  vendor_id,<br>  pickup_datetime,<br>  dropoff_datetime,<br>  trip_distance,<br>  SUM(trip_distance) OVER (PARTITION BY vendor_id ORDER BY pickup_datetime) AS running_total_distance<br>FROM<br>  bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022<br>ORDER BY<br>  vendor_id, pickup_datetime</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*QAExyQK5wFfp_k2X.png" /></figure><h4>#3. EXCEPT DISTINCT (Finding Differences Between Tables)</h4><blockquote><em>It is used for </em><strong><em>comparing datasets and finding missing records</em></strong><em>. One of the most common use-case is </em><strong><em>Identifying discrepancies</em></strong><em> between source and destination tables after ETL.</em></blockquote><p>For the sake of completeness, let me demonstrate this technique in action using the <strong>New York Taxi Trips</strong> dataset. In this example, I compare the <strong>payment methods</strong> used in the tlc_yellow_trips tables for the years <strong>2022 and 2016</strong> to identify any trends or shifts in payment preferences over time.</p><pre>SELECT DISTINCT payment_type<br>FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022` <br><br>EXCEPT DISTINCT <br><br>SELECT DISTINCT payment_type<br>FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2016` </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*FmJ1nESQJRsIIdxS-29USw.png" /></figure><p>It seems like payment_type 0 is new in 2022 data, this seems more like a placeholder for NULL values instead.</p><h3>Conclusion:</h3><p>In my opinion, <strong>SQL is still the most important tool for any Data Engineer</strong>. We’ve explored three powerful techniques — <em>Pivot-Unpivot Transformations</em>, <em>Window Functions</em>, and <em>EXCEPT DISTINCT</em> — that keep queries clean, scalable, and efficient.</p><p>Mastering these techniques is a solid foundation for tackling complex data challenges and optimizing workflows. No matter how the data landscape evolves, <strong>a deep understanding of SQL will always be invaluable</strong>.</p><p>Now, go ahead and experiment with your own queries! 🚴‍♂️💨</p><p>Do you have any cool queries to share? Drop them in the comments! 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06f1fcc56cf2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learning-sql/the-sql-techniques-i-use-the-most-as-a-data-engineer-and-why-they-matter-06f1fcc56cf2">The SQL Techniques I Use the Most as a Data Engineer (And Why They Matter)</a> was originally published in <a href="https://medium.com/learning-sql">Learning SQL</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master SQL for Free on GCP BigQuery with Real-World Data]]></title>
            <link>https://medium.com/learning-sql/master-sql-for-free-on-gcp-bigquery-with-real-world-data-801c42944319?source=rss-86765ed9024------2</link>
            <guid isPermaLink="false">https://medium.com/p/801c42944319</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Alessandro Pizzini]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 15:50:00 GMT</pubDate>
            <atom:updated>2025-02-07T18:38:59.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lCNU6ysTtreVXGa4" /><figcaption>Photo by <a href="https://unsplash.com/@fakurian?utm_source=medium&amp;utm_medium=referral">Milad Fakurian</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Google Cloud Platform (GCP) offers an excellent way to <strong>practice SQL for free using its BigQuery public datasets</strong>. One such dataset that provides a rich playground for SQL exercises is the <a href="https://console.cloud.google.com/marketplace/product/city-of-new-york/nyc-tlc-trips?project=polished-engine-259016">New York City Taxi Trips</a> Dataset. This dataset contains <strong>detailed trip records of NYC taxis</strong>, including pickup and drop-off locations, timestamps, fares, passenger counts, trip distances, and payment types.</p><p>In this article, we will walk through the steps to access and analyze this dataset using SQL, all without incurring any costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uAe2CMv0SnCG10hL" /><figcaption>Photo by <a href="https://unsplash.com/@fecaetano?utm_source=medium&amp;utm_medium=referral">Fernanda Caetano</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Step 1: Setting Up a Free Google Cloud Account</h3><p>Before we begin, you need access to Google Cloud Platform (GCP). If you don’t already have an account, you can sign up and get <strong>$300 in free credits</strong> (which is more than enough for practicing SQL).</p><h4>Steps to Get Started:</h4><ol><li>Go to <a href="https://console.cloud.google.com/">Google Cloud Console</a>.</li><li>Sign in with your Google account.</li><li>If you are a new user, you will receive $300 in free credits.</li><li>Enable <strong>BigQuery</strong> from the GCP dashboard.</li></ol><p>For more details about GCP’s pricing and free tier, visit <a href="https://cloud.google.com/free">Google Cloud Pricing</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3tdtuJAHm0CLBaoZP0Dnw.png" /><figcaption>Google Cloud Console</figcaption></figure><p><strong>Important Notes:</strong></p><ul><li>You will need to set up a <strong>payment profile</strong> for identity verification, but you won’t be charged unless you exceed the free tier limits.</li><li>Accepted payment methods include debit cards, credit cards, or PayPal.</li><li>If your payment method is declined, try another option.</li></ul><h3>Step 2: Accessing the NY City Taxi Dataset</h3><p>GCP provides public datasets that are free to query up to <strong>1 TB per month</strong> (which is more than enough for SQL practice).</p><h4>Locating the Dataset:</h4><ol><li>Navigate to <strong>BigQuery Console</strong> (<a href="https://console.cloud.google.com/bigquery">BigQuery UI</a>).</li><li>In the Explorer panel digit Marketplace and then search<strong> </strong>for <a href="https://console.cloud.google.com/marketplace/product/city-of-new-york/nyc-tlc-trips?project=polished-engine-259016&amp;inv=1&amp;invt=AboU3A">NYC TLC Trips</a> and then finally click on view data set.</li><li>Now that is everything set-up you can click on the ny_taxi dataset table to see its schema and sample data.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JqjRXOVfniA9lNI-SMiFQ.png" /><figcaption>BigQuery Console</figcaption></figure><h3>Step 3: Running Queries and Exploring Results Instantly</h3><p>BigQuery allows you to run SQL queries directly against the dataset and see results in a blink of an eye. No setup is needed; just write your queries and get instant insights.</p><h4>#01 Example: Count Total Trips</h4><p>This query counts the total number of trips in the dataset.</p><pre>SELECT COUNT(*) AS total_trips<br>FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022`;</pre><h4>#02 Example: Find the Top 5 Most Popular Start Stations</h4><p>This query finds the five most popular starting stations based on the number of trips.</p><pre>SELECT pickup_, COUNT(*) AS trip_count<br>FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022`<br>WHERE 1=1<br>GROUP BY pickup_location_id<br>ORDER BY trip_count DESC<br>LIMIT 5;</pre><p>You can look at much more example of queries against NYC Taxi Dataset on some other article that I’ve wrote <a href="https://medium.com/@pizzini.alessandro/data-engineers-arsenal-4-must-know-sql-window-functions-e45bf6ae8528">here on Medium</a></p><p><a href="https://medium.com/@pizzini.alessandro/data-engineers-arsenal-4-must-know-sql-window-functions-e45bf6ae8528">Data Engineer’s Arsenal: 4 Must-Know SQL Window Functions</a></p><h3>Conclusion:</h3><p>Practicing SQL on GCP BigQuery with a public dataset is a great way to <strong>enhance your skills using real-world data</strong> — completely <strong>free of charge!</strong></p><p>By following the three simple steps in this guide, you’ll not only improve your SQL proficiency but also gain hands-on experience with Google BigQuery Console, one of the most widely used cloud-based data warehousing tools.</p><p>Now, go ahead and experiment with your own queries! 🚴‍♂️💨</p><p>Do you have any cool queries to share? Drop them in the comments! 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=801c42944319" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learning-sql/master-sql-for-free-on-gcp-bigquery-with-real-world-data-801c42944319">Master SQL for Free on GCP BigQuery with Real-World Data</a> was originally published in <a href="https://medium.com/learning-sql">Learning SQL</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling the Power of Ranking Functions in BigQuery]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@pizzini.alessandro/unveiling-the-power-of-ranking-functions-in-bigquery-e79568dcb126?source=rss-86765ed9024------2"><img src="https://cdn-images-1.medium.com/max/2600/1*yaWJcit9E-IFFHOh-I6w5g.jpeg" width="6000"></a></p><p class="medium-feed-snippet">In the dynamic landscape of SQL, ranking functions play a pivotal role in data analysis, offering a spectrum of tools to understand the&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@pizzini.alessandro/unveiling-the-power-of-ranking-functions-in-bigquery-e79568dcb126?source=rss-86765ed9024------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@pizzini.alessandro/unveiling-the-power-of-ranking-functions-in-bigquery-e79568dcb126?source=rss-86765ed9024------2</link>
            <guid isPermaLink="false">https://medium.com/p/e79568dcb126</guid>
            <category><![CDATA[window-functions]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Alessandro Pizzini]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 15:58:14 GMT</pubDate>
            <atom:updated>2024-01-31T16:02:19.044Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Data Engineer’s Arsenal: 4 Must-Know SQL Window Functions]]></title>
            <link>https://medium.com/@pizzini.alessandro/data-engineers-arsenal-4-must-know-sql-window-functions-e45bf6ae8528?source=rss-86765ed9024------2</link>
            <guid isPermaLink="false">https://medium.com/p/e45bf6ae8528</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[window-functions]]></category>
            <dc:creator><![CDATA[Alessandro Pizzini]]></dc:creator>
            <pubDate>Fri, 26 Jan 2024 12:32:22 GMT</pubDate>
            <atom:updated>2024-01-31T16:02:35.274Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9TwIxElUrxnQp2UQ43tQ_A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@christopher__burns?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Christopher Burns</a> on <a href="https://unsplash.com/photos/white-and-black-digital-wallpaper-Kj2SaNHG-hg?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>For a Data Engineer, the proficiency in SQL isn’t just a skill; it’s an essential tool that unlocks the ability to effortlessly manipulate and analyze data. However, delving deeper and <strong>mastering SQL window functions</strong> can elevate this expertise to <strong>superhero status</strong>.</p><p>In this article, we’ll explore the power of mastering <strong>4</strong> <strong>key SQL window functions</strong>. Through practical examples, we will show their impact and how you too can turn your queries into interesting data revelations.</p><h3>What are WINDOW functions</h3><p>Window functions in SQL are “specialized tools” that <strong>operate over a window (range of rows) </strong>defined using the OVER clause, offering a powerful way to analyze and manipulate data. The following are examples of what can be calculated using winodw functions:</p><ul><li><strong><em>Ranking — </em></strong>Assigns a unique rank to each row based on specified criteria, enabling the arrangement of data in a meaningful order.</li><li><strong><em>Running Totals — </em></strong>Computes the cumulative sum of a designated column, useful for tracking ongoing trends.</li><li><strong><em>Moving Average</em></strong> — Calculates the average of a specified column within a moving window of rows, useful to highlighting patterns in the data.</li></ul><p>Window function can be defined as follow:</p><pre>SELECT <br>  window_function() OVER( <br>      [PARTITION BY column_name1]<br>      [ORDER BY column_name2]) AS window_column_alias<br>FROM table_name</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RQlX1MkZaBrB9WpitcDNPA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@phoedobus?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Edoardo Busti</a> on <a href="https://unsplash.com/photos/yellow-sedan-on-gray-road-B40Coqg3KLI?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>WINDOW functions Examples</h3><p>In the following section we will explore 4 of the most commonly used<strong> window functions through some practical examples</strong>, and we will do so using the sample dataset from GCP <a href="https://console.cloud.google.com/marketplace/product/city-of-new-york/nyc-tlc-trips?project=polished-engine-259016">New York City Taxi Trips</a>.</p><h4>#1. ROW_NUMBER( )</h4><blockquote>It assigns a unique sequential integer to each row<strong> </strong>within a specified partition of a result set. The ROW_NUMBER() function in SQL is commonly used in scenarios where you need to assign a unique ranking or sequence to rows within a specified group or partition.</blockquote><p>We can use the function to <strong>rank the trip according the tip_amount</strong>.</p><p>This query aims to find and display the top 3 trips for each payment method based on the tip amount. The ROW_NUMBER() function is used to rank the trips within each payment type partition, and the final result set includes the payment method, tip amount rank, and tip amount for each qualifying trip.</p><pre>WITH RankedTrips AS (<br>  SELECT *,<br>    ROW_NUMBER() OVER (PARTITION BY payment_type ORDER BY tip_amount DESC) AS tip_amount_rank<br>  FROM<br>    bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022<br>)<br>SELECT<br>  payment_method,<br>  tip_amount_rank, <br>  tip_amount<br>FROM<br>  RankedTrips<br>WHERE<br>  tip_amount_rank &lt;= 3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*7t_iZsrIUg3KJ-SmgIOMYQ.png" /></figure><p>If you want to learn more about Ranking/Numbering functions read my article<a href="https://medium.com/@pizzini.alessandro/unveiling-the-power-of-ranking-functions-in-bigquery-e79568dcb126"> here on Medium</a></p><p><a href="https://medium.com/@pizzini.alessandro/unveiling-the-power-of-ranking-functions-in-bigquery-e79568dcb126">Unveiling the Power of Ranking Functions in BigQuery</a></p><h4>#2. FIRST_VALUE( )</h4><blockquote>It retrieves the first value of an expression within a specified partition or the entire result set, ordered by a specified column. The <em>FIRST_VALUE()</em> is particularly useful when you want to identify the first occurrence or the earliest value in a series, providing insights into the earliest occurrence of a certain attribute within distinct groups or the entire dataset.</blockquote><p>We can use the function to <strong>calculate the difference between all the trips and the most expensive one</strong>.</p><p>This query calculates the difference (‘delta’) between the total amount of each taxi trip and the total amount of the most expensive trip within the same vendor category. It uses the FIRST_VALUE() window function to identify the most expensive trip in each vendor category.</p><pre>SELECT<br>    vendor_id, <br>    pickup_datetime,<br>    dropoff_datetime, <br>    total_amount<br>    FIRST_VALUE(total_amount) OVER (PARTITION BY vendor_id ORDER BY total_amount DESC) -total_amount AS delta_most_expensive,<br>  FROM<br>    bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022<br>  ORDER BY total_amount DESC</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*QN1gZ0PhV9Z70KnQZwdZeQ.png" /></figure><h4>#3. SUM( ) OVER (PARTITION BY )</h4><blockquote>It calculates a running sum of a specified numeric column within a defined partition of the result set. The <em>SUM()</em>window function allows for the generation of a dynamic running sum that continuously accumulates the values of the designated column as it traverses the rows.</blockquote><p>We can leverage the function to calculate the <strong>running total distance covered by each taxi trip</strong> within its respective vendor category.</p><p>This query computes a running total of the trip distances for each taxi trip within its corresponding vendor category. The SUM() window function is applied over a specified partition defined by vendor_id and ordered by pickup_datetime, resulting in a dynamic running sum that accumulates the trip distances as rows are processed.</p><pre>SELECT<br>  vendor_id,<br>  pickup_datetime,<br>  dropoff_datetime,<br>  trip_distance,<br>  SUM(trip_distance) OVER (PARTITION BY vendor_id ORDER BY pickup_datetime) AS running_total_distance<br>FROM<br>  bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022<br>ORDER BY<br>  vendor_id, pickup_datetime</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*PWmollXGLillac-cKsQV2g.png" /></figure><h4>#4. LEAD</h4><blockquote>It evaluates the value of a specified column for the preceding row within a defined partition of the result set. The<em>LAG()</em> window function enables the retrieval of the value from the previous row, offering insights into the historical state of the designated column as the result set is processed.</blockquote><p>We can utilize the function to assess the <strong>difference in trip distances</strong>.</p><p>This query calculate the difference in trip distances between each taxi trip and its immediate predecessor within the same vendor category. The LAG() window function is applied over a specified partition defined by vendor_id and ordered by pickup_datetime, allowing for the retrieval of the previous trip’s distance.</p><pre>SELECT<br>  vendor_id,<br>  pickup_datetime,<br>  dropoff_datetime,<br>  trip_distance,<br>  LAG(trip_distance) OVER (PARTITION BY vendor_id ORDER BY pickup_datetime) AS previous_trip_distance<br>FROM<br>  bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022<br>ORDER BY<br>  vendor_id, pickup_datetime</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*L7WOvUlLs745LxIJqDeOLQ.png" /></figure><h3>Conclusion</h3><p>To sum up, knowing how to use SQL window functions is essential for data engineers since it gives them strong tools for efficient data manipulation and analysis. This article’s four main window functions — ROW_NUMBER(), FIRST_VALUE(), SUM(), and LAG() — provide useful functions for sorting, getting particular values, computing running sums, and evaluating previous states of data inside of designated partitions.</p><p>Feel free to <strong>reach to me on LinkedIn</strong> if you have any other question: <a href="https://www.linkedin.com/in/pizzinia/">Alessandro Pizzini | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e45bf6ae8528" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Data Pipeline: From IBM DB2 to Google BigQuery]]></title>
            <link>https://medium.com/@pizzini.alessandro/python-data-pipeline-from-ibm-db2-to-google-bigquery-a3253ac97f88?source=rss-86765ed9024------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3253ac97f88</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[etl]]></category>
            <dc:creator><![CDATA[Alessandro Pizzini]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 16:13:45 GMT</pubDate>
            <atom:updated>2023-10-19T16:13:45.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q2j4GUOkrXI-stMH" /></figure><p>The mission? Seamless, automatic data transfer from IBM DB2 FlashCopy straight into Google BigQuery using only Python.</p><p>The aim was straightforward but profound — <strong>ensuring that our GCP BigQuery and IBM DB2 FlashCopy were </strong>in perfect harmony, <strong>synchronized </strong>to dance to the same beat of time.</p><p>In this article, we’ll journey through the process of crafting an efficient data pipeline, <strong>transitioning data from DB2 to Google BigQuery</strong>.</p><ul><li><strong><em>DB2 FlashCopy Extraction</em></strong> — Utilizing Python to extract significant data snapshots from IBM DB2 FlashCopy, guided by specific criteria.</li><li><strong><em>BigQuery Data Transformation</em></strong> — Systematically adapting data through anonymization and type conversion to ensure compatibility.</li><li><strong><em>Data Movement in BigQuery</em> </strong>— Managing the data’s journey as it enters BigQuery and subsequently progresses through the DWH layers.</li></ul><h3>Python Environment Setup</h3><p>For the success of this project, it’s paramount to initialize a <strong>Python 3 environment, specifically Python 3.11 or newer</strong>. The core modules instrumental for the pipeline and their respective uses are outlined below:</p><ul><li><strong><em>ibm_db</em> </strong>: It enables the initiation of a secure connection, followed by the execution of SQL queries necessary for data extraction.</li><li><strong><em>google-cloud-bigquery</em>: </strong>It ensures that our transformed data seamlessly enters the Google ecosystem.</li><li><strong><em>Pandas </em></strong>: It facilitates the intricate handling and transformation of data once it’s pulled from IBM DB2 DB.</li></ul><p><a href="https://pandas.pydata.org/">pandas — Python Data Analysis Library (pydata.org)</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FBbkx9P3yMGT8Tme.png" /><figcaption>pandas — data analysis and manipulation tool</figcaption></figure><h3>Blueprints and Building Blocks — Data Pipeline Architecture</h3><p>In building our data pipeline, we’ve set up a clear system architecture. Here’s how the components fit together to move and process data from IBM DB2 to Google Cloud BigQuery:</p><ol><li><strong>IBM DB2 DB — </strong>Serves as the primary source of data.</li><li><strong>Google Cloud Big Query </strong>— Serve as the target DB for our data</li><li><strong>ETL Python Script DB2 to BigQuery</strong> — The lifeblood of our data transition process. This script ensures that data from the Flash Copy gracefully cascades into both the staging and landing datasets of BigQuery.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*aMo8bMF-ceuyGx7pi6U7Fg.png" /><figcaption>Data Flow Diagram</figcaption></figure><h3>Our Project Methodology Unfolded — From Extraction to BigQuery Datasets Propagation</h3><p>Charting our data journey isn’t simple, but we’ve found our way. Guided by IBM DB2 DB to access Flash Copy tables, targeting Google BQ for storage, and aided by Pandas for data wrangling, we’ve set a clear course.</p><ol><li><strong>Snap and Grab from IBM DB2 FlashCopy</strong>: Think of this as our data gathering stage. Using a Python script, we peek into the schema of interested, grabbing snapshots of the data we need. Whether we take it all or just bits of it depends on what the mission demands (we collected data in DELTA or FULL mode).</li><li><strong>BigQuery’s Transformation Dance</strong>: Now, the gathered data gets a makeover. We ensure it plays nice with BigQuery’s standards by anonymizing it and converting its data type. Once it’s dressed to impress, up it goes into Google BigQuery, ready for its analytical debut.</li><li><strong>Data’s Journey Across the Datalake</strong>: The story doesn’t end with BigQuery. Our data continues its journey, moving gracefully through the different layers of our Data Lake. Here, it stands ready, waiting to offer insights to every corner of our business.</li></ol><p>There you have it — the method behind our data magic. With each step, we ensure that every piece of data finds its rightful place, serving our analytics needs just right.</p><h4>#1 <strong>Snap and Grab from IBM DB2 FlashCopy</strong></h4><p>Let’s dive into the heart of the operation: retrieving data from IBM DB2 FlashCopy.</p><p>With our configuration in hand, we move to establish a connection to our IBM DB2 FlashCopy. Using the ibm_db library and the details from our configuration file, we can seamlessly bridge our Python environment to the DB2 instance. This connection allows us to send queries, retrieve data, and manage our interactions with the database.</p><pre># Read the config file<br>with open(&quot;db_config.json&quot;, &quot;r&quot;) as f:<br>    config = json.load(f)<br><br>dsn = (<br>    f&quot;DRIVER={{IBM DB2 ODBC DRIVER}};&quot;<br>    f&quot;DATABASE={config[&#39;dsn_db&#39;]};&quot;<br>    f&quot;HOSTNAME={config[&#39;dsn_hostname&#39;]};&quot;<br>    f&quot;PORT={config[&#39;dsn_port&#39;]};&quot;<br>    f&quot;PROTOCOL=TCPIP;&quot;<br>    f&quot;UID={config[&#39;dsn_uid&#39;]};&quot;<br>    f&quot;PWD={config[&#39;dsn_pwd&#39;]};&quot;<br>)<br><br># Establish the connection<br>try:<br>    db2_conn = ibm_db.connect(dsn, &quot;&quot;, &quot;&quot;)<br>    print(&quot;Connected to the database!&quot;)<br>except:<br>    print(&quot;Failed to connect to the database.&quot;)<br>    exit(1)</pre><p>Working with large datasets often means high memory usage, especially with in-memory tools like Pandas. For instance, a 200MB raw data file can consume over 800MB in memory when loaded as a dataframe due to Pandas’ internal operations.</p><p><strong>The Chunking Approach</strong>: To mitigate this, we employ ‘chunking’, breaking the dataset into smaller sets for more efficient processing. The fetch_data_chunk function supports this strategy, fetching specified data chunks from the source database. This ensures the system memory remains stable, even with vast tables.</p><pre>def fetch_data_chunk(offset, chunk_size, table_name, where_condition, columns_table):<br>    &quot;&quot;&quot;<br>    Fetches a chunk of data from the database table.<br><br>    Parameters:<br>        offset (int): The offset from where to start fetching rows.<br>        chunk_size (int): The number of rows to fetch.<br>        table_name (str): The name of the table from which to fetch.<br>        where_condition (str): The WHERE condition for the SQL query.<br><br>    Returns:<br>        list: A list of dictionaries, each representing a row.<br>    &quot;&quot;&quot;<br>       <br>    query = f&quot;&quot;&quot;<br>        SELECT {&#39;, &#39;.join(columns_table)}<br>        FROM {db2_schema_name}.{table_name} <br>        {where_condition}<br>        OFFSET {offset} ROWS <br>        FETCH NEXT {chunk_size} ROWS ONLY<br>    &quot;&quot;&quot;<br>    stmt = ibm_db.exec_immediate(db2_conn, query)<br>    rows = []<br>    row = ibm_db.fetch_assoc(stmt)<br>    while row:<br>        rows.append(row)<br>        row = ibm_db.fetch_assoc(stmt)<br><br>    return rows</pre><p>Next, we’ll dive into the fetching_table function and its role in data extraction. The data are fetched from source database table by table, and the table is queries n times based on the size of the offset.</p><pre>def fetching_table(table_name, chunk_size, conn, db2_schema_name):<br>    &quot;&quot;&quot;<br>    Fetches data from a specified IBM DB2 source table in chunks and writes each chunk to GCP BigQuery.<br><br>    Parameters:<br>        row (dict): A dictionary containing row-level data, used to determine the table name                  <br>        chunk_size (int): The number of rows to fetch in each chunk.<br>        conn (object): The database connection object.<br>        db2_schema_name (str): The schema name in the DB2 database.<br>    &quot;&quot;&quot;<br>    <br>    try:<br>        offset = 0<br>        while True:<br>            where_condition = generate_where_condition(row)<br>            schema_name = get_table_schema_from_db2(table_name)<br>            columns_table = [column[0] for column in schema_name]<br><br>            rows = fetch_data_chunk(offset, chunk_size, table_name, where_condition, columns_table)<br>            if not rows:<br>                print(f&quot;There are no records to fetch for table {table_name}&quot;)<br>                break<br>            <br>            df_name = f&quot;{table_name}_{offset // chunk_size}&quot;<br>            df = pd.DataFrame(rows)<br><br>            memory_usage = df.memory_usage(deep=True).sum() / (1024 ** 2)<br>            print(f&quot;Fetched {len(df)} rows from {table_name}, offset {offset}, Memory Usage: from {df_name} : {memory_usage:.2f} MB&quot;)<br>                        <br>            df = apply_anonymization(df,table_name)<br>            df = convert_datetime_columns_to_utc(df)<br><br>                        <br>            if offset == 0: truncate_bigquery_table(table_name) <br>            write_to_bigquery(df, table_name)<br><br><br>    except Exception as e:<br>        print(f&quot;Skipping table {table_name}. Could not fetch data due to error: {e}&quot;)</pre><h4>#2 <strong>BigQuery’s Transformation Dance</strong></h4><p>Data transformation is an intricate dance, choreographed to the rhythm of BigQuery’s expectations. As <strong>data moves from source to destination</strong>, it’s crucial <strong>to ensure it harmonizes with the structure</strong>, datatype, and standards of the target environment. Let’s step into this dance and explore how we’ve tailored our data for BigQuery’s dancefloor.</p><p>check_schema_mismatching function is the vigilant stage manager, quickly <strong>spotting any schema mismatches between DB2 and BQ</strong>. If DB2 is flaunting additional columns, this function seamlessly integrates them into BQ&#39;s performance, ensuring the show goes on without a hitch.</p><pre>def check_schemas_mismatching(table_name):<br>    &quot;&quot;&quot;<br>    Checks for schema mismatches between a DB2 table and a BigQuery table, and handles missing columns.<br><br>    Parameters:<br>        table_name (str): The name of the table to compare and synchronize between DB2 and BigQuery.<br>    &quot;&quot;&quot;<br>    <br>    # Rest of your function code here...<br><br>    <br>    db2 = get_table_schema_from_db2(table_name)<br>    columns_db2 = set([col[0] for col in db2])<br>    <br>    load_process = get_process_mode(table_name)<br>    dataset_name, target_table_name = get_target_table_and_dataset(load_process, organization, table_name)<br>        <br>    bq = get_table_schema_from_bq(dataset_name, target_table_name)<br>    columns_bq = set([col.name for col in bq])<br>    <br>    missing_columns = set([col[0] for col in db2]) - set([col.name for col in bq])<br>    <br>    if missing_columns:  # Check if the set is not empty<br>        converted_datatypes = {}<br>        for col, data_type in db2:<br>            if col in missing_columns:<br>                new_col, new_data_type = transpile_datatype(col, data_type)<br>                converted_datatypes[new_col] = new_data_type<br><br>        print(&quot;Converted data types of missing columns: &quot;, converted_datatypes)<br><br>        for column_name, column_type in converted_datatypes.items():<br>            alter_table_add_column(dataset_name, target_table_name, column_name, column_type)</pre><p>Before our data even begins its cloud performance, we pull back the curtains and get it prepped, ensuring it’s anonymized. This is where the anonymization_table in BigQuery steps in, like a choreographer guiding each data point to maintain its essence while veiling its identity.</p><pre>def apply_anonymization(df, table_name):<br>    &quot;&quot;&quot;<br>    Applies data anonymization rules to specific columns of a DataFrame based on a configuration.<br><br>    Parameters:<br>        df (pd.DataFrame): The DataFrame containing the data to be anonymized.<br>        table_name (str): The name of the table for which anonymization rules are applied.<br><br>    Returns:<br>        pd.DataFrame: The DataFrame with selected columns anonymized according to the specified rules.<br>    &quot;&quot;&quot;<br><br>    full_table_name = f&#39;CCMS_{organization}_{table_name}&#39;<br>    condition_df = query_configuration_results[&#39;MASKING_TABLE&#39;]<br>    <br>    # Find matching rows in the condition DataFrame<br>    matching_rows = condition_df[condition_df[&#39;TABLE_LND_NAME&#39;] == full_table_name]<br><br>    for index, row in matching_rows.iterrows():<br>        field_datatype = row[&#39;FIELD_DATATYPE&#39;]  # New line to get the datatype<br>        field_name = row[&#39;FIELD_NAME&#39;]        <br>        logic = row[&#39;LOGIC&#39;]<br><br>       # Apply logic based on the type of logic you have<br>        if field_name in df.columns:<br>            print(f&quot;Anonymize {field_name}&quot;)<br>            if field_datatype == &#39;STRING&#39;:<br>                df[field_name] = logic<br>            elif  field_datatype == &#39;DATE&#39;:  # Replace this with your actual anonymization logic<br>                if &#39;YEAR&#39; in logic.upper():<br>                    df[field_name] = df[field_name].astype(str).str.extract(r&#39;(\d{4})&#39;)[0] + &#39;-01-01&#39;  # Extract year and set month and day to &#39;01&#39;<br>       <br>    <br>    clear_memory(matching_rows,f&quot;matching_rows_{table_name}&quot;)<br>    return df</pre><p>Enter our write_to_bigquery function, the unsung hero that takes our prepped data and ensures it&#39;s comfortably nested within BigQuery.</p><p>Thanks to BigQuery’s LoadJobConfig, most of the heavy lifting, in terms of data type definitions and transformations, is handled effortlessly. The code checks if the table already contains records, and depending on its state, it appends or creates new entries. This is possible because our target tables in BigQuery are pre-defined, allowing LoadJobConfig to intelligently adapt the data, if transformations are needed at all.</p><pre>def write_to_bigquery(df, table_name):<br>    &quot;&quot;&quot;<br>    Writes a DataFrame to a Google BigQuery table.<br><br>    Parameters:<br>        df (DataFrame): The DataFrame to write to BigQuery.<br>        table_name (str): The BigQuery table name.<br>    &quot;&quot;&quot;<br>    <br>    load_process = get_process_mode(table_name)<br>    dataset_name, target_table_name = get_target_table_and_dataset(load_process, organization, table_name)<br>    <br>    # Specify the BigQuery Dataset and Table<br>    table_id = f&quot;{bq_client.project}.{dataset_name}.{target_table_name}&quot;<br>    <br>    <br>    # Check if there are existing records in the table<br>    existing_records = int(bq_client.query(f&quot;SELECT COUNT(*) FROM {table_id}&quot;).result().to_dataframe().iloc[0, 0])<br>    write_disposition = &#39;WRITE_EMPTY&#39; if existing_records == 0 else &#39;WRITE_APPEND&#39;<br><br>    # Write the DataFrame to BigQuery<br>    job_config = bigquery.LoadJobConfig( <br>        schema = get_table_schema_from_bq(dataset_name, target_table_name),<br>        autodetect=False, # schema is inherited<br>        source_format = bigquery.SourceFormat.CSV,<br>        # skip_leading_rows=1,  # Skip the header row.<br>        # allow_jagged_rows=True,  # Allow missing values in delimited files<br>        allow_quoted_newlines = True,<br>        quote_character = &#39;&quot;&#39;,<br>        write_disposition = write_disposition )<br>    job = bq_client.load_table_from_dataframe(df, table_id, job_config=job_config)<br>    job.result()  # Wait for the job to complete<br><br>    print(f&quot;Written {len(df)} rows to table {table_id}&quot;)</pre><h4>#3 <strong>Data’s Journey Across the Datalake</strong></h4><p>When it comes to the datawarehouse, one size doesn’t fit all. The setup of layers (datasets) can vary based on structure and requirements. While we won’t delve deep into the intricate details here, it’s worth noting that our data’s orchestration across layers is driven by whether we’re reading in full or delta mode.</p><h3>Conclusion</h3><p>In wrapping up, we’ve detailed our data pipeline’s journey, from <strong>IBM DB2 FlashCopy extraction to its storage in Google BigQuery</strong>. Opting for a pipeline built in pure Python has granted us remarkable flexibility and advantages, allowing for more tailored adjustments and optimizations.</p><h3>Dive Deeper</h3><p>Intrigued by our data dance? Dive deeper into the depths of our analysis in my <a href="https://colab.research.google.com/drive/15Nte7a40UaAgfYcZy9cbstWz5ouqzS1O?usp=sharing"><strong><em>Google Colab Notebook</em></strong></a><em> </em>where I have all the</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*b82Pq4TdU1YlQkRk.png" /><figcaption>Full Code in Google Colab Notebook</figcaption></figure><p>If you have any thoughts, questions, or have embarked on a similar journey, feel free to connect or drop a comment below. The discourse around <strong>data pipelines Cloud Migration </strong>is as enriching as the data itself, and I’m eager to learn from and engage with this community. Let’s continue to unravel the stories our data shares!</p><blockquote>Link for full code → <a href="https://colab.research.google.com/drive/15Nte7a40UaAgfYcZy9cbstWz5ouqzS1O?usp=sharing"><strong>Google Colab Notebook</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3253ac97f88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Column Usage with SQLGlot: A Journey Towards Data Warehouse Optimization]]></title>
            <link>https://medium.com/@pizzini.alessandro/monitoring-column-usage-with-sqlglot-a-journey-towards-data-warehouse-optimization-299667aa44dc?source=rss-86765ed9024------2</link>
            <guid isPermaLink="false">https://medium.com/p/299667aa44dc</guid>
            <category><![CDATA[oracle]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[data-monitoring]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sqlglot]]></category>
            <dc:creator><![CDATA[Alessandro Pizzini]]></dc:creator>
            <pubDate>Fri, 13 Oct 2023 17:20:45 GMT</pubDate>
            <atom:updated>2024-06-19T14:03:05.984Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8h350G4O82bbTaWHrszr0g.png" /></figure><p>Identifying the Life-of-the-Party Columns: A Deep Dive into Optimizing Our Oracle Data Warehouse by Trimming the Fat with SQL Queries</p><p>The goal was simple yet mighty — figure out<strong> which tables and columns were the life of the party and which were wallflowers</strong>, all to give our data warehouse a slick makeover for better efficiency.</p><p>In this article, we’ll delve into the intricacies of optimizing a specific Data Platform by <strong>monitoring its usage through the queries executed on it</strong>.</p><ul><li><strong><em>Query Tracking with Oracle’s DBA Tables</em></strong><em> — </em>Utilizing Oracle DB’s DBA tables to extract the SQL text of queries executed by different users.</li><li><strong><em>Cracking the Code with SQLGlot </em></strong><em>— </em>Using the magic of <strong><em>SQLGlot to dissect the queries </em></strong>and fishing out the nuggets of info hiding in them</li><li><strong><em>Buzz Check </em></strong><em>— </em>Identifying what’s buzzing and what’s not in our data warehouse.</li></ul><h3>What is SQLGlot?</h3><p>Imagine having a <strong>tool that can dissect queries and fish out the goodies</strong> — the columns, aliases, and tables from your query. That’s where SQLGlot shines.</p><p>It can theoretically be used to trace back a <strong>column-level lineage of your warehouse by analyzing SQL files</strong>. SQLGlot was our <strong>pick to zoom into the column usage </strong>in our Oracle DB. It had the knack for breaking down queries to see which columns were in action.</p><p><a href="https://github.com/tobymao/sqlglot"><em>GitHub — tobymao/sqlglot: Python SQL Parser and Transpiler</em></a></p><figure><img alt="SQLGlot Github Repository (tobymao/sqlglot)" src="https://cdn-images-1.medium.com/max/1024/0*8kcHH-LeQ2sJKAwt" /><figcaption>SQLGlot Github Repository</figcaption></figure><h3>Our Project Methodology Unfolded — From Queries to Clarity</h3><p>Let’s dive into how we explored our data warehouse. Our toolkit? Oracle DB for raw data, SQLGlot to tackle the queries, and a BI tool to visualize it all.</p><ol><li><strong>Grabbing the Queries</strong>: First things first, we rolled up our sleeves and collected the SQL queries buzzing around in the database. We took a peek into the DBA tables over a certain period to grab logs of all the SQL activities going on there.</li><li><strong>Cracking Open the Queries</strong>: Now with a treasure trove of queries in hand, it was time to make sense of the jumble. Enter SQLGlot, our go-to for turning the query gibberish into something we could work with. It helped us break down the queries to see what’s what.</li><li><strong>Fishing Out the Good Stuff</strong>: With the queries parsed, we were on a mission to fish out the names of the tables and columns being hit. We sifted through the parsed queries, jotting down the table and column names like they were gold nuggets. Once we had the loot, we tallied it up to get the big picture of how our data warehouse was being used.</li></ol><p>And voila! Each of these steps took us closer to the treasure — a sleeker and more efficient data warehouse. Now, let’s take a closer look at how we navigated through each of these stages…</p><h3>#1. Grabbing the Queries</h3><p>Our first step is to <strong>gather logs of SQL queries</strong> executed on the Oracle database over a designated time period. We’ll be tapping into the <strong>DBA tables for these logs</strong>, as they hold a wealth of information regarding SQL statement executions.</p><pre>-- Select columns from multiple tables after performing joins<br>SELECT a.sql_text,             -- SQL text from the DBA_HIST_SQLTEXT table<br>       b.session_id,           -- Session ID from the DBA_HIST_ACTIVE_SESS_HISTORY table<br>       b.session_serial#,      -- Session Serial number from the DBA_HIST_ACTIVE_SESS_HISTORY table<br>       c.username,             -- Username from the DBA_USERS table<br>       b.sql_id,               -- SQL ID from the DBA_HIST_ACTIVE_SESS_HISTORY table<br>       b.program,              -- Program from the DBA_HIST_ACTIVE_SESS_HISTORY table<br>       b.sample_time           -- Sample time from the DBA_HIST_ACTIVE_SESS_HISTORY table<br>FROM (<br>    -- Sub-query to select unique rows based on specific conditions from the DBA_HIST_ACTIVE_SESS_HISTORY table<br>    SELECT DISTINCT session_id, session_serial#, user_id, sql_id, program, sample_time<br>    FROM DBA_HIST_ACTIVE_SESS_HISTORY<br>    WHERE sql_opcode = 3  -- Only include records where SQL are SELECT<br>    AND (<br>        sample_time &gt; trunc(sysdate-1)  -- Sample time should be greater than the start of yesterday<br>        AND sample_time &lt; trunc(sysdate)  -- and less than the start of today<br>    )<br>) b<br><br>INNER JOIN DBA_HIST_SQLTEXT a ON a.sql_id = b.sql_id<br>INNER JOIN DBA_USERS c ON b.user_id = c.user_id;</pre><h3>#2. <strong>Cracking Open the Queries</strong></h3><p>Each SQL query tells a tale, and with SQLGlot, we’ll translate these into structured narratives, either as an abstract syntax tree (AST). By<strong> dissecting the queries into core elements</strong> like SELECT, FROM, and WHERE clauses, we <strong>unveil the tables and columns each query touches</strong>, simplifying the analysis and understanding of the interactions within our data playground.</p><h4>Example SQL Statement</h4><p>For sake of simplicity in the article let’s consider we have just a single SQL Statement and we save it as a string in the variable sql_query .</p><pre>WITH SalesSummary AS (<br>    SELECT p.Product_Name, SUM(s.Quantity) AS Total_Sales<br>    FROM Products p<br>    JOIN Sales s ON p.Product_ID = s.Product_ID<br>    WHERE s.Sale_Date BETWEEN TO_DATE(&#39;2021-01-01&#39;, &#39;YYYY-MM-DD&#39;) AND TO_DATE(&#39;2021-12-31&#39;, &#39;YYYY-MM-DD&#39;)<br>    GROUP BY p.Product_Name<br>)<br>SELECT ss.Product_Name, ss.Total_Sales, c.Category_Name<br>FROM SalesSummary ss<br>JOIN Categories c ON ss.Product_Name = c.Product_Name<br>ORDER BY ss.Total_Sales DESC;<br></pre><h4>Parse SQL Statement</h4><p>The parse_one function in SQLGlot acts as a keen-eyed interpreter, dissecting a given SQL string and unveiling a syntax tree for the initial parsed SQL statement.</p><pre>ast = parse_one(sql_query, read=&#39;oracle&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*lCfr81VvIrxc-Ll7pMorrQ.png" /><figcaption>parse_one output (truncated)</figcaption></figure><p>In a nutshell, this snippet calls upon the parse_one function to sift through the given SQL query (sql_query), penned in Oracle SQL dialect, and nestles the resulting Abstract Syntax Tree (AST) into the variable ast.</p><h4>Qualifying Columns with SQLGlot</h4><p>To avoid ambiguity and ensure clarity, we’ll use SQLGlot to qualify the columns in our SQL statement with their respective table aliases:</p><pre>def qualify_columns(expression, schema):<br>    try:      <br>        expression = optimizer.qualify_tables.qualify_tables(expression)<br>        expression = optimizer.isolate_table_selects.isolate_table_selects(expression)<br>        expression = optimizer.qualify_columns.qualify_columns(expression, schema)<br><br>    except (OptimizeError) as e:<br>        pass  <br> <br>    return expression</pre><p>The schema parameter in the qualify_columns function helps handle queries where a column is referenced without a specified table, even amid multiple tables, it could be omitted.</p><pre>qualify_columns(ast, schema = None)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*JRSSr7q30_lm_MrmBOxf6A.png" /><figcaption>qualify_columns output (truncated)</figcaption></figure><h3>#3. Fishing Out the Good Stuff</h3><p>Now that we’ve peeled apart our SQL query, it’s time to fish out the juicy bits: the <strong>table names and their respective columns that are in action</strong>. Let’s wrap up what we’ve unveiled so far with the parse_statement function and see <strong>how we could extract info out of it</strong>.</p><pre>def parse_statement(sql_query, dialect):<br><br>    ast = parse_one(sql_query, read=dialect)<br>    ast = qualify_columns(ast, schema = None)<br>    <br>    physical_columns = []<br>    <br>    for scope in traverse_scope(ast):<br>        for c in scope.columns:<br>            if isinstance(scope.sources.get(c.table), exp.Table):<br>                physical_columns.append((scope.sources.get(c.table).name, c.name))<br>                <br>    return physical_columns</pre><pre>parse_statement(sql_query, &#39;oracle&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*V-xFtV0JcYEcjOMvrR2Ahg.png" /><figcaption>parse_statement output</figcaption></figure><p>The parse_statement function serves as a<strong> handy tool for dissecting our SQL query</strong>. It begins by parsing the query with parse_one, followed by a call to qualify_columns to ensure each column is distinctly associated with its table.</p><p>As it strides through the syntax tree using traverse_scope, it picks up the table names and their respective columns from each scope, bundling them into the physical_columns list.</p><p>At the journey’s end, <strong>it returns a list of tuples, each housing a table name and its corresponding column from the query,</strong> ready for any further analysis needed.</p><h3>Conclusion</h3><p>Sifting through SQL queries to spot exactly which tables, and crucially, which columns were getting some love, became a whole lot easier with SQLGlot.</p><p>This was a treasure trove for our project, as it <strong>helped us figure out which parts of our data warehouse were buzzing and which were just taking up space</strong>.</p><h3>Dive Deeper</h3><p>Curiosity piqued? Venture further into the analysis by exploring my <a href="https://colab.research.google.com/drive/1RikskrkwNfU6QMIUKRsrGZY6rZhk9tuT?usp=sharing"><strong><em>Google Colab Notebook</em></strong></a><em> </em>where I delve into a comprehensive examination of multiple SQL statements extracted from the Oracle DBA table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*b82Pq4TdU1YlQkRk.png" /><figcaption>Full Code in Google Colab Notebook</figcaption></figure><p>If you have any thoughts, questions, or have embarked on a similar journey, feel free to connect or drop a comment below. The discourse around <strong>optimizing data warehouse usage</strong> is as enriching as the data itself, and I’m eager to learn from and engage with this community. Let’s continue to unravel the stories our data shares!</p><blockquote>Link for full code → <a href="https://colab.research.google.com/drive/1HfApkf3qbqIHc5sPu7nhAwzkMEvSs_mJ?usp=sharing"><strong>Google Colab Notebook</strong></a></blockquote><p>Feel free to <strong>reach to me on LinkedIn</strong> if you have any other question: <a href="https://www.linkedin.com/in/pizzinia/">Alessandro Pizzini | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=299667aa44dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>