<?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 Tobi Sam on Medium]]></title>
        <description><![CDATA[Stories by Tobi Sam on Medium]]></description>
        <link>https://medium.com/@tobisam?source=rss-92fab82e0c7a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*YIa8FSsdEdAzbQQusuL84g.jpeg</url>
            <title>Stories by Tobi Sam on Medium</title>
            <link>https://medium.com/@tobisam?source=rss-92fab82e0c7a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:27:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tobisam/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[Part 1: dbt on Databricks — Working with profiles.yml]]></title>
            <link>https://medium.com/@tobisam/part-1-dbt-on-databricks-working-with-profiles-yml-a38c82faa1c4?source=rss-92fab82e0c7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a38c82faa1c4</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[databricks-asset-bundles]]></category>
            <dc:creator><![CDATA[Tobi Sam]]></dc:creator>
            <pubDate>Fri, 08 May 2026 13:26:01 GMT</pubDate>
            <atom:updated>2026-05-11T08:17:42.630Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep dive into working with profiles.yml on dbt core with Databricks Lakeflow Jobs , DABs and how credential injection works</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*u6SZDew1qxKTgm6zBEBNWw.png" /></figure><h3>Intro</h3><p>If you’ve used dbt for more than five minutes, you’ve met profiles.yml. And if, like me, you’ve used dbt with Databricks, you’ve likely encountered this file with a few extra questions attached:</p><ul><li>Which warehouse should I target?</li><li>How did my job run without any profiles.yml file?</li><li>Should the file live in ~/.dbt or inside my project? What actually happens when I use --profiles-dir?</li></ul><p>In this article, I’ll walk through what profiles.yml actually does, where dbt looks for it, and a few subtle behaviors on Databricks that tend to trip people up. It’s a summary of the things I’ve learned along the way, which I’ve found useful and hope you will too. <strong>I will be focusing on dbt core in this article.</strong></p><h3><strong>What the </strong><strong>profiles.yml actually is</strong></h3><p>The <a href="https://www.google.com/search?q=profiles.yml&amp;rlz=1C5GCCM_en&amp;oq=dbt+profiles.yml&amp;gs_lcrp=EgZjaHJvbWUyBwgAEEUYgAQyBwgBEAAYgAQyBwgCEAAYgAQyBwgDEAAYgAQyBwgEEAAYgAQyCAgFEAAYFhgeMggIBhAAGBYYHjIICAcQABgWGB4yCAgIEAAYFhgeMggICRAAGBYYHtIBCDc2NzZqMGo3qAIAsAIA&amp;sourceid=chrome&amp;ie=UTF-8&amp;ved=2ahUKEwjw78jbjvWTAxWF2wIHHaglDCIQgK4QegYIAQgAEAU">profiles.yml</a> file is a required YAML configuration file for dbt that stores database connection credentials and settings.</p><blockquote>The profiles.yml file basically allows dbt communicate with Databricks</blockquote><p>It usually lives outside the dbt project folder (typically in ~/.dbt/) to prevent sensitive credentials from being committed to version control, and it maps project-specific profiles to different environments.</p><p>Check out the <a href="https://docs.getdbt.com/docs/local/profiles.yml?version=1.10">dbt documentation </a>for more information.</p><p>Here’s a minimal Databricks example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onsEgp_m_hH1nUQkaXhc_A.png" /><figcaption>profiles.yml example</figcaption></figure><p>A few things to notice:</p><ul><li><strong>type</strong>: databricks tells dbt to use the dbt-databricks adapter.</li><li><strong>host</strong> and <strong>http_path</strong> come straight from your Databricks UI (more on that below).</li><li><strong>catalog </strong>and <strong>schema</strong> are the first two parts of the <a href="https://docs.databricks.com/aws/en/data-governance/unity-catalog/#-the-unity-catalog-object-model">3-level Unity Catalog namespace</a>.</li><li><strong>token</strong>: Secrets live in environment variables, not in the file.</li></ul><h4>Where dbt looks for profiles.yml</h4><p>To authenticate with your data platform, dbt Core checks these locations in order and uses the <strong>first one it finds</strong>:</p><ol><li>The -- profiles-dir flag passed on the command line</li><li>The DBT_PROFILES_DIR environment variable</li><li>The current project directory (i.e., next to your dbt_project.yml)</li><li>~/.dbt/ — the recommended default especially when running locally</li></ol><h4>What the “ — profiles-dir” command does</h4><p>Passing -- profiles-dir /path/to/dir tells dbt to skip its normal search and load profiles.yml from the directory you specify. It’s the cleanest way to run ad-hoc dbt jobs with new profile configs without affecting the others.</p><pre>dbt run --profiles-dir ./config/prod --target prod</pre><h3><strong>Authentication: PAT vs. OAuth</strong></h3><p>There are two authentication approaches most teams use, and both are supported in profiles.yml:</p><h4>Personal access token (PAT)</h4><p>Simplest to set up. You generate a token in Databricks (user settings → developer → access tokens), set token in your profile, and you’re done.</p><blockquote>As a security best practice when you authenticate with automated tools, systems, scripts, and apps, Databricks recommends that you use OAuth tokens.</blockquote><p>If you use personal access token authentication, Databricks recommends using personal access tokens belonging to service principals instead of workspace users. To create tokens for service principals, see <a href="https://docs.databricks.com/aws/en/admin/users-groups/manage-service-principals#tokens">here</a>.</p><pre>dev:<br>  type: databricks<br>  host: ...<br>  http_path: ...<br>  catalog: ...<br>  schema: ...<br>  token: &quot;{{ env_var(&#39;DBT_DATABRICKS_TOKEN&#39;) }}&quot;</pre><p>Tokens are long-lived, which is convenient but could pose a security risk; and that is why Databricks recommends OAuth. Don’t commit the token value to your code repository; use env_var and keep the actual value in your shell, a .env file, or your CI secret store.</p><h4>OAuth (recommended)</h4><p>OAuth comes in two flavours:</p><ul><li><strong>User-to-machine (U2M)</strong> for interactive local development. You set auth_type: oauth and client_id, and dbt opens a browser window the first time you run a command. The token is cached in your OS keychain and refreshed automatically.</li><li><strong>Machine-to-machine (M2M)</strong> for CI/CD and scheduled runs. A service principal authenticates with a client ID and client secret; dbt exchanges them for short-lived access tokens.</li></ul><pre>prod:<br>  type: databricks<br>  host: ...<br>  http_path: ...<br>  catalog: prod_catalog<br>  schema: analytics<br>  auth_type: oauth<br>  client_id: &quot;{{ env_var(&#39;DATABRICKS_CLIENT_ID&#39;) }}&quot;<br>  client_secret: &quot;{{ env_var(&#39;DATABRICKS_CLIENT_SECRET&#39;) }}&quot;</pre><p>Here too, ensure you do <strong>not</strong> put the client secret in profiles.yml directly; keep it in an environment variable. The U2M flow uses short-lived tokens (typically valid for an hour), which is a real security improvement over PATs.</p><h3>Running dbt as a Databricks Lakeflow Job</h3><p>When you create a <a href="https://docs.databricks.com/aws/en/jobs/dbt"><strong>dbt task</strong></a><strong> </strong>in a Databricks Lakeflow Job, the task configuration panel asks you to choose a SQL warehouse.<strong> What actually happens next depends on that choice.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXBlzkElbYbEAz9nCSmWkw.png" /><figcaption>Databricks Lakeflow Jobs’ UI when working with the dbt task type</figcaption></figure><h4>Case 1: You pick a SQL warehouse in the UI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*7O6ZlakwZsMJchPQ45Ts6w.png" /></figure><p>If you select a warehouse (plus optionally a catalog and schema) from the task’s drop-downs, Databricks generates the profiles.yml on your behalf. It populates the host, the http_path for the warehouse you picked, and handles authentication by injecting the DBT_ACCESS_TOKEN for the principal configured in the <strong>Run As</strong> field.</p><p>Because Databricks is constructing the profile itself, the “Profiles Directory” option isn’t shown in the UI.</p><blockquote>In this case, you do <strong>not</strong> need to commit a profiles.yml file to your repo or workspace ⚠️</blockquote><p>At first, this threw me off as I was used to providing a profiles.yml file for any dbt deployment.</p><h4>Case 2: You pick “None (Manual)” for the SQL warehouse</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mlxKxKSA5UrSfpKH_pBX2g.png" /></figure><p>The second option is selecting <strong>None (Manual)</strong> in the SQL warehouse dropdown and the UI changes: now you will notice that a <strong>Profiles Directory</strong> field appears. You provide a profiles.yml in your repo, and you tell the job where in the repo it lives (relative to the project root; leave blank to use the repo root).</p><p>What Databricks still does for you here is <strong>inject two environment variables</strong> into the task’s runtime, scoped to the job’s Run As identity:</p><ul><li><strong>DBT_HOST</strong>: the workspace hostname</li><li><strong>DBT_ACCESS_TOKEN</strong>: a short-lived access token for the Run As principal</li></ul><p>Your committed profiles.yml just has to reference them like this:</p><pre>jaffle_shop:<br>  target: dev<br>  outputs:<br>    dev:<br>      type: databricks<br>      method: http<br>      catalog: &lt;CATALOG-NAME&gt;<br>      schema: &lt;SCHEMA-NAME&gt;<br>      http_path: &lt;WAREHOUSE-PATH&gt;<br>      # The workspace host / token are provided by Databricks at runtime<br>      host: &quot;{{ env_var(&#39;DBT_HOST&#39;) }}&quot;<br>      token: &quot;{{ env_var(&#39;DBT_ACCESS_TOKEN&#39;) }}&quot;</pre><p>If you notice, the http_path is hardcoded (or templated however you like) because <em>you</em> are now picking the compute. The host and token come from environment variables that <strong>Databricks populates for you;</strong> you don’t create a PAT, you don’t manage a service principal secret, you don’t commit anything sensitive. The job runs as whatever principal is configured in Run As, and the token is issued for that principal.</p><h4>To summarise what happens:</h4><ul><li><strong>Pick a warehouse in the UI</strong> when you want the simplest possible setup and you’re happy with Databricks’s default profile shape. Great for quick jobs and standard pipelines. You don’t need to references any profiles.yml file.</li><li><strong>Pick None (Manual)</strong> when you need things the UI can’t express ; per-model compute overrides, custom connection settings, multiple targets driven by the same job, or an existing profiles.yml you want to keep as the source of truth. You get full control and you still don’t have to manage the workspace token.</li></ul><p>Databricks either writes the whole profiles.yml for you <em>or</em> writes the “auth” bits into the environment and lets you write the rest. It’s the same mechanism either way; injection into the runtime.</p><h3>What about when I use Declarative Automation Bundles (DABs)?</h3><p>Short answer: <strong>the behavior is identical to the UI, because </strong><a href="https://docs.databricks.com/aws/en/dev-tools/bundles"><strong>DABs</strong></a><strong> just allows you to perform the same task declaratively.</strong> When you define a dbt_task in a bundle, you’re configuring the same underlying job resource. Which means either Databricks generates the profile, or you bring your own profile.</p><p>Here’s a minimal DABs dbt task:</p><pre>resources:<br>  jobs:<br>    my-dbt-job:<br>      name: my-dbt-job<br>      tasks:<br>        - task_key: my-dbt-task<br>          dbt_task:<br>            commands:<br>              - &#39;dbt deps&#39;<br>              - &#39;dbt run&#39;<br>            project_directory: /Workspace/Users/me@example.com/my_project<br>            warehouse_id: 1a111111a1111aa1    # ← the important field<br>            catalog: prod<br>            schema: analytics</pre><h4>What happens when you specify warehouse_id in DABs?</h4><p>Same as picking a warehouse in the UI, Databricks generates the profiles.yml at runtime based on warehouse_id, catalog, and schema, and authenticates as the job’s Run As identity. You don’t need to commit a profiles.yml, or specify a profiles_directory.</p><h4>What happens when you omit warehouse_id from DABs?</h4><p>This is the DABs equivalent of “None (Manual)” in the UI. You need two things:</p><ol><li>A profiles.yml committed somewhere in your bundle’s project directory.</li><li>A profiles_directory field on the dbt_task pointing at the folder that contains it (relative to the dbt project directory; leave it unset to use the project root).</li></ol><pre>resources:<br>  jobs:<br>    my-dbt-job:<br>      name: my-dbt-job<br>      tasks:<br>        - task_key: my-dbt-task<br>          dbt_task:<br>            commands:<br>              - &#39;dbt deps&#39;<br>              - &#39;dbt run&#39;<br>            project_directory: /Workspace/Users/me@example.com/my_project<br>            profiles_directory: dbt_profiles/   # ← instead of warehouse_id<br>            catalog: prod<br>            schema: analytics</pre><p>Your dbt_profiles/profiles.yml will look exactly like the one in the Lakeflow Job UI section. You just reference DBT_HOST and DBT_ACCESS_TOKEN via env_var, set http_path yourself, and Databricks will inject the host and token for the Run As principal at runtime.</p><blockquote>The <a href="https://github.com/databricks/bundle-examples/tree/main/dbt_sql">dbt-sql DABs project template </a>is a good starting point to explore a good end-to-end example.</blockquote><h4>A short, opinionated list of things that have bitten me</h4><p>Below is a summary of key things to be aware of in general:</p><p><strong>1. The profile name in </strong><strong>profiles.yml must match the profile key in </strong><strong>dbt_project.yml.</strong> If they don’t match, dbt will tell you it can’t find a profile. It’s an easy typo to make when you rename things.</p><p><strong>2. </strong><strong>dbt debug is your best friend.</strong> It validates that profiles.yml is found, parses cleanly, and can actually open a connection. Run it whenever you change anything in the profile. dbt debug — config-dir will also print where dbt thinks profiles.yml lives, which is useful when you suspect a precedence issue.</p><p><strong>3. Environment variables in </strong><strong>profiles.yml are resolved at runtime on Databricks.</strong> If DBT_DATABRICKS_TOKEN isn’t set in the shell you run dbt from, you get an auth error. For CI/CD, this means your pipeline config has to inject the variable before calling dbt.</p><p><strong>4. In Databricks Lakeflow Jobs, the “Profiles Directory” field appears and disappears.</strong> It’s hidden when you pick a SQL warehouse in the task UI (Databricks generates the profile itself) and visible when you select “None (Manual)” (you bring your own). See the Lakeflow Jobs section above for why, and how DBT_HOST / DBT_ACCESS_TOKEN are injected for you.</p><h3>A realistic multi-target profile</h3><p>To tie it all together, here’s what a realisticprofiles.yml might look like with one profile, two targets, and different auth strategies per environment:</p><pre>my_project:<br>  target: dev<br>  outputs:<br>    dev:<br>      type: databricks<br>      host: &quot;{{ env_var(&#39;DATABRICKS_HOST&#39;) }}&quot;<br>      http_path: /sql/1.0/warehouses/dev_warehouse_id<br>      catalog: dev<br>      schema: &quot;{{ env_var(&#39;USER&#39;) }}_dev&quot;<br>      token: &quot;{{ env_var(&#39;DBT_DATABRICKS_TOKEN&#39;) }}&quot;<br>      threads: 4<br>      connect_retries: 3<br>      connect_timeout: 60<br><br>    prod:<br>      type: databricks<br>      host: &quot;{{ env_var(&#39;DATABRICKS_HOST&#39;) }}&quot;<br>      http_path: /sql/1.0/warehouses/prod_warehouse_id<br>      catalog: prod<br>      schema: analytics<br>      auth_type: oauth<br>      client_id: &quot;{{ env_var(&#39;DATABRICKS_CLIENT_ID&#39;) }}&quot;<br>      client_secret: &quot;{{ env_var(&#39;DATABRICKS_CLIENT_SECRET&#39;) }}&quot;<br>      threads: 8</pre><p>Hope you found this helpful. Let me know in the comments if you have other tips for working with dbt on Databricks.</p><h3>Further reading</h3><ul><li><a href="https://docs.databricks.com/aws/en/jobs/dbt-platform">Connect to dbt platform</a></li><li><a href="https://docs.databricks.com/aws/en/jobs/dbt">Configue a dbt task in Lakeflow jobs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a38c82faa1c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Databricks Guide to Managing Delta Table History, Data Retention and Data Recovery]]></title>
            <link>https://medium.com/data-science-collective/a-data-practitioners-guide-to-managing-delta-table-history-data-retention-and-data-recovery-6d806488a835?source=rss-92fab82e0c7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d806488a835</guid>
            <category><![CDATA[databricks-unity-catalog]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Tobi Sam]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 15:03:58 GMT</pubDate>
            <atom:updated>2025-11-24T18:35:55.899Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>A Databricks Guide to Managing Delta Table History, Data Retention and Data Recovery on Databricks</strong></h3><h4>Manage your table’s state in Databricks with Delta Lake</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*3n3sUGWrDI47duznpjqucA@2x.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@behy_studio?utm_source=medium&amp;utm_medium=referral">Behnam Norouzi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Meet Amira, a senior data engineer at a retail analytics company. Every day, she manages several Delta Lake tables that power dashboards, predictive models, and customer behaviour insights. Her team relies on Delta Lake for its reliability and scalability, but with frequent updates, deletes, and streaming jobs, Amira must constantly ensure the tables stay optimised, compliant, and recoverable.</p><p>Like many practitioners, she often faces questions such as:</p><ul><li>“Why is my cloud storage bill increasing?”</li><li>“How far back can I time-travel this dataset?”</li><li>“How can I undo an accidental overwrite?”</li></ul><p>These challenges ultimately boil down to understanding how Delta Lake manages its files and transaction logs, which form the backbone of a Delta table.</p><p>Delta Lake is an open-source storage layer that provides ACID transactions, scalable metadata handling, and unified governance for data lakes. This article explores the <strong>anatomy of a Delta table</strong>, focusing on how its data files and transaction logs enable operations like<strong> time travel, vacuuming, restoring</strong>, and <strong>change tracking.</strong></p><p>If you use <a href="https://docs.databricks.com/aws/en/tables/managed">managed tables</a> instead of <a href="https://docs.databricks.com/aws/en/tables/external">external tables</a>, many of these operations are automated. We will cover the benefits at the end. Still, understanding how they work helps practitioners like Amira fine-tune performance, troubleshoot issues, and maintain historical access.</p><p>We’ll follow Amira’s journey as she tackles these key Delta Lake operations:</p><ul><li><strong>History</strong> and <strong>Change Data Feed (CDF)</strong>: Enabling <strong>time travel</strong>, auditing, and tracking of table changes on a row level.</li><li><strong>VACUUM</strong>: Optimising storage and managing file retention.</li><li><strong>DROP, </strong><strong>RESTORE,</strong> and <strong>UNDROP</strong>: Recovering from data loss</li></ul><h3>Default Delta Lake Settings</h3><p>Before we begin to explore this use case with Amina, let us look at the delta settings she will need to keep in mind:</p><ul><li><strong>Table transaction history setting (30 days by default):</strong> Controls how long the history for a table is kept. Modify with delta.logRetentionDuration = “interval &lt;interval&gt;”</li><li><strong>Data files retention setting (7 days by default): </strong>Determines the threshold VACUUM uses to remove data files no longer referenced in the current table version. Modify with delta.deletedFileRetentionDuration = “interval &lt;interval&gt;”</li><li><strong>Change data feed retention setting (“false” by default):</strong> Allows Databricks to track row-level changes between versions of a Delta table using Change Data Feed (CDF) modify with delta.enableChangeDataFeed=true</li></ul><h3>Anatomy of a Delta Lake Table</h3><p>Amira begins her day investigating why one of her tables sales_transactions has ballooned in size. Before diving into optimisation, she reviews what makes up a Delta table.</p><p>A Delta table’s folder structure includes:</p><ul><li>A <strong>top-level directory</strong> representing the table itself</li><li>A <strong>_delta_log</strong> directory containing transaction log files</li></ul><p>The actual <strong>data files (e.g., file1.parquet, file2.parquet)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/0*b6eNIJwwrAe0LRP8" /><figcaption><em>Anatomy of a delta lake table. Source </em><a href="https://dennyglee.com/2023/11/26/understanding-the-delta-lake-transaction-log-at-the-file-level/"><strong><em>dennyglee</em></strong></a></figcaption></figure><p>Understanding this structure helps Amira identify which files Delta Lake manages automatically and which may remain after updates or deletions.</p><h3>Time Travel and Auditing: Table History</h3><p><strong>Scenario:</strong> One morning, Amira gets a request from compliance:</p><ul><li>“Can you show what the <strong><em>sales_transactions</em></strong> table looked like last Monday?”</li></ul><p>Using Delta Lake’s <strong>history</strong> and <strong>time travel</strong> features, she can easily query historical versions.</p><p>Each table modification creates a new version, which is recorded in the transaction log. The command below helps Amira inspect all changes:</p><pre>DESCRIBE HISTORY sales_transactions;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/0*FybyeDcLGMuzDARO" /></figure><p>This shows when data was updated, by whom, and how, which is crucial for auditing.</p><p>By default, Delta keeps log history for <strong>30 days</strong> (delta.logRetentionDuration = ’30 days’), though Amira can extend this if audits require longer retention.</p><p>To travel back in time, she can query an older version directly using the version number or a timestamp:</p><pre>SELECT * FROM sales_transactions VERSION AS OF 10;</pre><p>The <strong>transaction log</strong> is central to all of this. It records every change from inserts to schema modifications enabling both <strong>data lineage</strong> and <strong>recovery</strong>.</p><h3>Tracking Incremental Changes: Change Data Feed (CDF)</h3><p><strong>Scenario:</strong> Later that day, Amira’s downstream systems need to know exactly what changes in the sales_transactions table every hour, to update analytics dashboards in real-time.</p><p>Delta Lake’s <strong>Change Data Feed (CDF)</strong> makes this possible. It enables Amira to query the row-level changes, including inserts, updates, and deletes, that occurred between two versions of a table.</p><p>Coincidentally, she had already enabled CDF on the table, enabling her to keep a record of those changes:</p><pre>ALTER TABLE table_name SET TBLPROPERTIES<br>(delta.enableChangeDataFeed=true)</pre><p>Now, she or downstream systems are able to track row-level changes between versions of a Delta table;</p><pre>SELECT * FROM table_changes(&#39;sales_transactions&#39;, 100, 110);</pre><p>CDF stores these changes in a <strong>_change_data</strong> folder under the table directory, working hand-in-hand with the transaction log and version history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*eWT9idNKfh-P8Bxw" /><figcaption><em>Anatomy of a delta lake table with CDF enabled.</em></figcaption></figure><p>However, Amira knows that CDF data is <strong>transient</strong>. Once old versions are removed by retention policies or VACUUM, the related CDF data disappears too.</p><p>To preserve important change data, she creates an incremental process that writes CDF output to a permanent audit table before cleanup jobs run (learn more <a href="https://docs.databricks.com/aws/en/delta/delta-change-data-feed#can-i-use-change-data-feed-to-replay-the-entire-history-of-a-table">here</a>).</p><p>She also makes sure her retention settings accommodate the lag of streaming jobs:</p><pre>ALTER TABLE sales_transactions <br>SET TBLPROPERTIES (&#39;delta.deletedFileRetentionDuration&#39; = &#39;30 days&#39;);</pre><p>This ensures the <strong>_change_data</strong> files remain available long enough for downstream consumers to process updates, even if streaming is delayed.</p><h3>Behind the Scenes</h3><blockquote>We are developing a new enhancement for CDF that will enable its functionality without the need for <strong><em>_change_data</em></strong> files or additional configurations. Further updates will be provided soon.</blockquote><h3>Optimising Storage — VACUUM</h3><p><strong>Scenario:</strong> After months of data ingestion, Amira notices that cloud storage costs have surged. She suspects that old data files are still lingering in cloud storage even after being logically deleted.</p><p>This is where the<a href="https://docs.databricks.com/en/sql/language-manual/delta-vacuum.html"> VACUUM</a> command helps.</p><h3>What VACUUM Does</h3><ul><li>Removes files <strong>not referenced</strong> by the current Delta table state</li><li>Physically deletes old, unreferenced files once they exceed the <strong>retention threshold</strong> (default: 7 days)</li></ul><p>When Amira runs <em>VACUUM</em> <em>sales_transactions</em>; Delta removes files that are no longer needed, such as outdated Parquet files from previous updates or deletes.</p><p>However, she must be careful: if the retention threshold is too short, she could accidentally remove files needed for <strong>time travel</strong> or <strong>streaming jobs</strong>.</p><h3>Adjusting the Retention Period</h3><p>To align with her team’s data recovery needs, Amira sets a longer retention period:</p><pre>ALTER TABLE sales_transactions <br>SET TBLPROPERTIES (&#39;delta.deletedFileRetentionDuration&#39; = &#39;30 days&#39;);</pre><p>This ensures that deleted files remain accessible for a month, providing enough time to recover from ingestion errors or delayed processing.</p><h3>Behind the Scenes</h3><blockquote>The default VACUUM retention period is set to 7 days. This duration strikes a balance between increased cloud storage expenses resulting from extensive data retention and providing users with a reasonable timeframe for data recovery or time-travelling capabilities. This prevents your cloud storage costs from increasing excessively.</blockquote><h3>Undoing Mistakes — RESTORE</h3><p><strong>Scenario:</strong> A junior data engineer accidentally overwrote Amira’s table with bad data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/0*_tKVIcivvZT0bjXM" /><figcaption><em>Table history showing a </em><em>CREATE OR REPLACE operation, which overwrites the previous table contents</em></figcaption></figure><p>Instead of rebuilding from scratch, Amira simply runs:</p><pre>RESTORE TABLE sales_transactions TO VERSION AS OF 6;</pre><p>The <a href="https://docs.databricks.com/aws/en/sql/language-manual/delta-restore">RESTORE</a> operation instantly rolls the table back to its pre-error state, version 6, thanks to the retained log and data files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*5J3WjYB-5XSW8kSs" /><figcaption><em>Table history showing the </em><em>RESTORE operation</em></figcaption></figure><p>However, she must ensure that VACUUM has not deleted older data files; otherwise, restoring to those versions would be impossible.</p><h3>Behind the Scenes</h3><blockquote>The RESTORE command provides a permanent way to revert a Delta Lake table to an earlier state, unlike time travel, which offers a temporary view of past versions. While time travel allows you to read a previous version of a Delta table, RESTORE effectively undoes changes in the current version without erasing any historical data. This metadata-only operation updates the transaction log to exclude certain files from being read, resetting the table’s content to a prior version. Consequently, you can still use time travel to access any previous versions of the table, even after a RESTORE operation. The functionality of the RESTORE command relies on the log files, which maintain the history of the table.</blockquote><h3>Managing Accidental Deletion — DROP and UNDROP</h3><p><strong>Scenario:</strong> During her team’s routine cleanup, someone mistakenly drops a managed table in Unity Catalog:</p><pre>DROP TABLE analytics.sales_transactions;</pre><p>Fortunately as we’ve seen, Delta Lake provides a safety net. Within <strong>7 days</strong>, Amira can recover the table:</p><pre>UNDROP TABLE analytics.sales_transactions;</pre><p>This feature saves her hours of restoration work and prevents data loss across the team.</p><h3>The Benefits of Unity Catalog Managed Tables</h3><p>Amira’s overarching goal is to minimise operational toil while maximising performance, governance, and recoverability. Unity Catalog managed tables are the default and recommended table type in Databricks because they are fully governed and automatically optimised, lowering storage and compute costs compared to external tables.</p><ul><li><strong>Automatic maintenance and optimisation with Predictive Optimisation:</strong> Managed tables can automatically run operations like OPTIMIZE, VACUUM, and ANALYZE, learning from read/write patterns to keep data layout and statistics in peak shape without manual intervention.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/0*2YTV5lEJgEIpvQyC" /><figcaption>Benefits of Unity Catalog Managed Tables</figcaption></figure><ul><li><strong>Lower costs and faster queries:</strong> Managed tables use AI-driven optimisation (including clustering and compaction) plus intelligent statistics collection to reduce compute costs and improve query latency across clients.</li><li><strong>Always-on metadata caching</strong>: Managed tables enable in-memory metadata caching to reduce transaction log reads and accelerate query planning; this is enabled by default for managed tables.</li><li><strong>Lifecycle automation and safety nets</strong>: After a DROP TABLE on a managed table, Databricks automatically deletes the underlying data from your cloud storage after 8 days; Unity Catalog also supports UNDROP TABLE to recover dropped managed tables within the same window.</li><li><strong>Consistent storage location and name-based access</strong>: Data files for managed tables are stored in the parent schema or catalog’s managed location, and Databricks recommends name-based access (catalog.schema.table) rather than path-based access to preserve governance and managed features.</li></ul><p>When Amira requires direct path-based access to register existing data, or when the lifecycle must be fully self-managed, external tables can be an appropriate solution. Just remember that dropping an external table doesn’t delete the underlying files, and Unity Catalog does not manage external table lifecycle for you.</p><h3>Conclusion</h3><p>For Amira and any data practitioner managing Delta tables on a daily basis, understanding how Delta Lake handles data and log retention is essential.</p><p>By mastering commands like <strong>HISTORY</strong>, <strong>CDF</strong>, <strong>VACUUM</strong>, and <strong>RESTORE</strong>, she ensures her tables remain:</p><ul><li><strong>Clean</strong> (no obsolete files consuming storage)</li><li><strong>Recoverable</strong> (from accidental overwrites or deletions)</li><li><strong>Auditable</strong> (for compliance and debugging)</li><li><strong>Stream-friendly</strong> (for continuous data pipelines)</li></ul><p>Through her daily experience, Amira demonstrates how Delta Lake’s operational concepts are not just theory; they are vital tools for maintaining reliable, scalable, and efficient data ecosystems.</p><p>If you would like to learn more about Delta Lake, managed Unity Catalog tables and more, check out the resources below:</p><ul><li><a href="https://delta.io/blog/2022-10-03-rollback-delta-lake-restore/">How to roll back a delta lake table</a></li><li><a href="https://docs.databricks.com/aws/en/delta/history#gsc.tab=0">Work with delta table history</a></li></ul><p>Originally posted on the Databricks <a href="https://community.databricks.com/t5/technical-blog/a-data-practitioner-s-guide-managing-delta-table-history-data/ba-p/138236">Community blog</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d806488a835" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/a-data-practitioners-guide-to-managing-delta-table-history-data-retention-and-data-recovery-6d806488a835">A Databricks Guide to Managing Delta Table History, Data Retention and Data Recovery</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple Intro to Tagging on Databricks]]></title>
            <link>https://medium.com/data-science-collective/a-simple-intro-to-tagging-on-databricks-a895cad63c41?source=rss-92fab82e0c7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a895cad63c41</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[unity-catalog]]></category>
            <category><![CDATA[tagging]]></category>
            <category><![CDATA[brick-by-brick]]></category>
            <dc:creator><![CDATA[Tobi Sam]]></dc:creator>
            <pubDate>Mon, 13 Oct 2025 12:54:52 GMT</pubDate>
            <atom:updated>2025-10-23T12:48:04.633Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Standardising Data Governance and Cost Tracking with Tags in Databricks</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3V0KTa7aTcmeUvp7QolyQ.png" /></figure><p>Databricks tags provide structured metadata that improves governance, compliance, and operational efficiency across data and AI assets. Tags also support financial governance by enabling cost tracking and attribution. Assigning cost center or project-level tags to Databricks assets makes it possible to monitor resource usage and implement chargeback models for teams. This leads to better budgeting, efficient resource allocation, and accountability over data expenditures.</p><p>In this article, we’ll explore the benefits of tagging in Databricks and how tags can be applied both to <strong>Unity Catalog assets</strong> and <strong>compute resources</strong>.<br>This post assumes you already have some familiarity with Databricks. By the end, you should have a foundational understanding of how tags work and how they can be used for governance, cost tracking, and data discovery.</p><h4><strong>Tags in Unity Catalog</strong></h4><p>Tags have been available in <strong>Unity Catalog</strong> for a while. They allow users to label securable objects (like tables, columns, and schemas) to help with <strong>data discovery</strong>, <strong>cost attribution</strong>, and more.</p><p>However, as more users adopt Databricks, tagging practices can become inconsistent and difficult to manage.</p><p>For example:</p><ul><li>One user might tag a column as pii:yes</li><li>Another might tag it as pii:ssn</li></ul><p>Over time, this inconsistency makes it hard to govern and standardise your tagging strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JwJbNNmVnG2AMAFywuEXMg.png" /></figure><blockquote>This is where Governed tags come in!</blockquote><h4>Governed Tags</h4><p>Governed tags are<strong> account-level t</strong>ags with built-in policies that give account admins and data stewards control over <strong>tag names and allowed values</strong>.<br> They improve consistency and simplify governance across all workspaces under the same account.</p><p>For example, instead of having a simple PII tag with values like yesor no, it’s often more useful to define specific values that indicate the type of personal data — such as email, name, or ssn. This allows you to apply different governance behaviours for each type — for instance:</p><ul><li>Mask part of an email address, or</li><li>Mask a full name column.</li></ul><p>You can define this structure through a <strong>tag policy</strong>.</p><p>To create one:</p><ol><li>Go to <strong>Catalog &gt; Governed Tags &gt; Create Governed Tag</strong> in your workspace.</li><li>Define the new tag and specify its allowed values.</li><li>Set permissions at the individual tag policy level.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yw5x0PHo1-3Wa8kERGMPzQ.png" /><figcaption>An admin or a data steward can define a governed tag with the allowed values</figcaption></figure><p>This means, for example; The <em>Finance</em> group can manage and apply the cost_center tag while the <em>Security</em> group can manage and apply the pii tag.</p><p>When a tag policy is created or updated, existing tags that don’t comply will be marked invalid — prompting users to fix them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gq5Il5MpL6gMUcEf9c-Q8Q.png" /></figure><h4>Types of Governed Tags:</h4><p><a href="https://docs.databricks.com/aws/en/admin/governed-tags#system-governed-tags"><strong>System-governed</strong></a><strong> (default) tags</strong>: These are tags predefined by Databricks and cannot be edited or deleted. You can identify them with a wrench icon <strong>🔧</strong>. System governed tags support standardised tagging for use cases like classification, ownership, and lifecycle tracking, without requiring admins to define or manage custom governed tags.</p><p>On the other hand, <a href="https://docs.databricks.com/aws/en/database-objects/tags#governed-tags"><strong>user</strong>-<strong>governed tags</strong></a><strong> </strong>are custom tags you define, where you control allowed keys, values, and who can assign them. They are marked with a “lock” icon <strong>🔒</strong>.</p><p>You can set tags on objects in the UI or <a href="https://learn.microsoft.com/en-us/azure/databricks/sql/language-manual/sql-ref-syntax-ddl-set-tag">programatically</a>:</p><pre>-- SET TAG ON COLUMN &lt;table-name&gt;.&lt;column-name&gt; `&lt;key&gt;`=`&lt;value&gt;`;<br><br>SET TAG ON COLUMN users.email `pii`=`email`;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8gOEt5fkFmDGHqA98P2HA.png" /><figcaption>Types of Unity Catalog tags</figcaption></figure><blockquote>Note: If a governed tag is deleted, its associated tags become ungoverned.<br> They remain attached to objects, but anyone can then assign or modify them without requiring specific permissions.</blockquote><h4><strong>Discovery Tags</strong></h4><p>It’s important to note that, you can still tag assets without creating governed tags which have policies and access control. These tags are called discovery tags, as they are still beneficial for search and discoverability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZxW2sgxmLiyH3gXI-HIqZg.png" /><figcaption>Discovery tag usage example in the search bar</figcaption></figure><h4>What can you do with governed tags?</h4><p>Governed tags can be applied to <strong>Unity Catalog assets</strong> such as:</p><ul><li>Tables</li><li>Views</li><li>Volumes</li><li>Catalogs</li><li>Schemas</li><li>Columns</li></ul><p>They cannot currently be applied to compute resources like clusters or jobs — those use a separate tagging mechanism (explained later).</p><p>Here are some practical ways to use governed tags:</p><ol><li><strong>Data Classification</strong>: Governed tags let you standardize data classification across your organization — for example, to label:</li></ol><ul><li>Sensitive or regulated data</li><li>Cost centers</li><li>Data ownership or domain</li></ul><p>You can also combine governed tags with Unity Catalog’s <a href="https://docs.databricks.com/aws/en/data-governance/unity-catalog/data-classification"><strong>Data Classification</strong></a> feature to automatically classify and tag tables, then apply governance controls using tools such as <strong>Attribute-Based Access Control (ABAC)</strong>.</p><p><strong>2. Attribute-based access control (ABAC)</strong>: ABAC uses governed tags as attributes to dynamically enforce access policies — controlling <em>who</em> can see specific data.</p><p>For example, you can use a masking SQL function to hide parts of email addresses for certain users.</p><blockquote>To create an ABAC policy, follow the steps <a href="https://docs.databricks.com/aws/en/data-governance/unity-catalog/abac/tutorial">here</a>.</blockquote><pre>-- Function to mask email addresses<br>CREATE OR REPLACE FUNCTION mask_email(email STRING)<br>RETURNS STRING<br>RETURN<br> CASE<br>   WHEN email IS NULL THEN NULL<br>   ELSE<br>     CONCAT(<br>       SUBSTR(split(email, &#39;@&#39;)[0], 1, 1),<br>       REPEAT(&#39;*&#39;, GREATEST(LENGTH(split(email, &#39;@&#39;)[0]) - 2, 0)),<br>       SUBSTR(split(email, &#39;@&#39;)[0], -1),<br>       &#39;@&#39;,<br>       split(email, &#39;@&#39;)[1]<br>     )<br> END;</pre><p>You can then attach this function to an <strong>ABAC policy</strong> that controls visibility for the email column.</p><pre>ALTER TABLE users ALTER COLUMN email SET MASK ssn_mask;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcANcj0_dSofVG6yMfIZjg.png" /><figcaption>ABAC policy applied using a masking function in Unity Catalog</figcaption></figure><ul><li><strong>Resource discovery:</strong> Consistent tagging improves <strong>searchability </strong>and organisation across catalogs, schemas, tables, and other assets — making it easier for users to find relevant data.</li><li><strong>Certification and deprecation classification (in preview):</strong> Use system-governed tags to mark datasets as <strong>trusted</strong>, <strong>certified</strong>, or <strong>deprecated</strong>, improving lifecycle management and data consumer clarity.</li></ul><h3>Compute Tags</h3><p>While governed tags apply to data assets, “<strong>compute” tags</strong> are used for <strong>workspace-level compute resources</strong>, such as clusters and jobs.<br> These tags help track and manage compute usage and cost attribution.</p><p>There are three main types of compute tags:</p><ul><li><a href="https://docs.databricks.com/aws/en/admin/account-settings/usage-detail-tags#default-tags"><strong>Default Tags</strong></a>: Databricks automatically attaches basic tags to compute resources (like clusters or jobs) when they start up in your cloud account. These provide basic metadata like vendor, cluster ID, and creator.</li><li><a href="https://docs.databricks.com/aws/en/admin/account-settings/usage-detail-tags#custom-tags"><strong>Custom Tags</strong></a>: These are <strong>user-defined tags</strong> you can add for project tracking, cost-center attribution, environment classification etc. For non-serverless workloads, these tags <a href="https://docs.databricks.com/aws/en/admin/account-settings/usage-detail-tags#tag-propagation">propagate</a> down to the underlying infrastructure relevant to your cloud environment. This enables you to not only attribute your Databricks costs but also the underlying cloud infrastructure costs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZestU604GdtK6hYA056cA.png" /><figcaption>Compute cluster config UI with default and custom tags</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqMcwxXy6bTtZKjVO_bvqw.png" /><figcaption>Lakeflow jobs UI with custom tags</figcaption></figure><ul><li><a href="https://docs.databricks.com/aws/en/admin/usage/budget-policies"><strong>Serverless Budget Policies</strong></a>: When running serverless workloads, budget policies can automatically attach predefined tags for accurate cost attribution and reporting in your <a href="https://docs.databricks.com/aws/en/admin/system-tables/billing"><strong>billable usage system table</strong></a>. When creating a serverless resource (such as a Serverless Lakeflow job or Serverless Declarative Pipeline) users will be able to choose between budget policies assigned to them. In most cases, a user has a single budget policy assigned to them, which will be chosen by default. The budget policy’s tags will then be applied automatically to the serverless resource.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*CMG1EcwJ77BbAfkveXRb4w.png" /><figcaption>Serverless budget policy tags applied to a job</figcaption></figure><blockquote><strong>Note</strong>: Governed tags will soon be supported in Serverless Budget Policies allowing you to implement accurate chargebacks and better budgeting on the storage and query level.</blockquote><h3>Wrapping Up</h3><p>Tags in Databricks are much more than labels — they’re essential for <strong>governance</strong>, <strong>cost management</strong>, and <strong>data discovery</strong>.</p><ul><li>Use <strong>workspace-level tags</strong> to track compute usage and control spending.</li><li>Use <strong>governed tags</strong> for consistent, organisation-wide governance of your Unity Catalog assets.</li></ul><p>When used thoughtfully, tagging can save your organisation both money and operational complexity.</p><h3>Further materials</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fb5y8c3G6v4Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Db5y8c3G6v4Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fb5y8c3G6v4Y%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7185845d92000dbb30439e6d96b473d/href">https://medium.com/media/d7185845d92000dbb30439e6d96b473d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a895cad63c41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/a-simple-intro-to-tagging-on-databricks-a895cad63c41">A Simple Intro to Tagging on Databricks</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How SQL execution orders varies across databases]]></title>
            <link>https://medium.com/data-science/how-sql-execution-orders-varies-across-databases-b5b949f34f31?source=rss-92fab82e0c7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5b949f34f31</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[mssql]]></category>
            <dc:creator><![CDATA[Tobi Sam]]></dc:creator>
            <pubDate>Thu, 07 Dec 2023 04:55:08 GMT</pubDate>
            <atom:updated>2024-10-18T21:16:54.587Z</atom:updated>
            <content:encoded><![CDATA[<h3>How SQL Execution Orders Varies Across Databases</h3><h4><em>Why you can’t GROUP BY ordinal positions in SQL Server but can in some other database systems</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JMoIGmb5Fma2xoPHZud-SA.png" /><figcaption>Transact-SQL vs MySQL execution order (image by author)</figcaption></figure><p>After working regularly with open-source databases such as MySQL and PostgreSQL, I recently had the chance to work on a SQL Server project and discovered a subtle but important difference in the SQL landscapes. I observed that in SQL Server, I was unable to GROUP BY ordinal positions (GROUP BY 1, 2, 3…), which is a functionality I frequently used within other databases, particularly for rapid testing.</p><p>This discovery led me to explore several nuances of both database systems, particularly the <strong>SQL execution order</strong>, which will be the focus of this article.</p><p>Why does this matter? When working with database systems, understanding the subtle differences can greatly impact your workflow and increase your productivity. It can save you significant troubleshooting time. Also, <strong>by</strong> <strong>understanding the SQL execution order of various databases, you can craft more optimal SQL queries</strong> based on the system you are working with.</p><p>In this article, we will look into one major use case where this behaviour occurs — GROUP BY — and investigate why. However, this insight can be applied to the HAVING, WHERE or any other SQL command clause.</p><h3>Let’s begin</h3><p>Let’s look at this example in the query below. This will <strong>not</strong> work in SQL Server even though it works in MySQL:</p><pre>SELECT<br>    DATEPART(year, day) AS order_date,<br>    SUM(cost) as cost<br>FROM clean<br>GROUP BY 1;</pre><p>If you run this, you will probably get an error like this:</p><p>Each GROUP BY expression must contain at least one column that is not an outer reference.</p><p>However, this revised query works after replacing the GROUP BY ordinal reference with the explicit expression. You will also notice that you can reference the ordinal positions in the ORDER BY clause, which I found strange:</p><pre>SELECT<br>    datepart(year, day),<br>    sum(cost) as cost<br>from clean<br>GROUP BY datepart(year, day)<br>ORDER BY 1;</pre><p>In SQL Server, I quickly learned that I had to use explicit column names or expressions in the GROUP BY clause.<strong> This is considered a best practice as it makes the code easier to understand</strong>. However, I was curious about why this behavior differed between databases. Additionally, I found it interesting that the ORDER BY clause in SQL Server works with ordinal positions, which further piqued my curiosity.</p><h3><strong>Exploring the SELECT statement execution order</strong></h3><p>To find out, lets look at the SELECT statement execution/processing order for SQL server vs. other databases. It’s important to note that in SQL databases, each part of a query is executed sequentially and that order differs from how it is written.</p><p>In SQL Server, for instance, we can see from the image below and from <a href="https://learn.microsoft.com/en-us/sql/t-sql/queries/select-transact-sql?view=sql-server-ver16&amp;redirectedfrom=MSDN#logical-processing-order-of-the-select-statement">Microsoft docs </a>that the FROM clause is the first command to be evaluated. Furthermore, <strong>the SELECT clause runs after the GROUP BY clause</strong>. That is why we were unable to reference a column‘s position or even its alias in the GROUP BY clause in our first example!</p><p>However, we are free to reference the ordinal position and/or alias in the ORDER BY clause, as that is evaluated after the SELECT clause. The SELECT clause tells the database what columns will be returned and thus, the positioning is known at this point. Cool, right?</p><h4>SQL Server execution order</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*soFyNZokdpXPuTOaQ0Hb4w.png" /><figcaption>SQL Server SELECT statement processing order (Image by author)</figcaption></figure><h3>MySQL</h3><p>In MySQL however, I found it difficult to find clear documentation stating the order of execution of a SQL query. The execution order seems to depend on the contents of the query and what the query optimiser defines as the best path.</p><p>But from what we can see from the MySQL docs <a href="https://dev.mysql.com/doc/refman/8.0/en/select.html">here</a>, the clue shows us how the execution order might be and that the <strong>SELECT clause is evaluated before the GROUP BY clause</strong>:</p><blockquote>For GROUP BY or HAVING clauses, it searches the FROM clause before searching in the <strong>select_expr</strong> values. (For GROUP BY and HAVING, this differs from the pre-MySQL 5.0 behavior that used the same rules as for ORDER BY.)</blockquote><h3>GoogleSQL</h3><p>If we also look at the GoogleSQL (formerly Standard SQL) <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#implicit_aliases">docs</a> which is the syntax used in Google BigQuery, you will see similar deviation from the way queries are executed in SQL Server:</p><blockquote>GROUP BY and ORDER BY can also refer to a third group: Integer literals, which refer to items in the SELECT list. The integer 1 refers to the first item in the SELECT list, 2 refers to the second item, etc.</blockquote><p>As you can see, this behaviour is not supported in SQL Server. The Google docs also mention that GROUP BY, ORDER BY, and HAVING, can refer to aliases from the SELECT list.</p><p>With that, we can conclude with a high probability that the execution order for these other databases follows a path similar to the image below:</p><h4>MySQL, PostgreSQL &amp; BigQuery probable execution order</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*ANm1prpi5clDzE64XL4Lkw.png" /><figcaption>MySQL SELECT statement execution order (Image by author)</figcaption></figure><h4>Conclusion</h4><p>This was a short post where we looked at how the execution order in MySQL, GoogleSQL and other databases’ SQL syntaxes, differ from SQL Server’s, based on the observed behaviours and documentation. SQL Server emphasises explicitness in the GROUP BY clause for code clarity, while MySQL’s execution order definitely evaluates that SELECT clause before the GROUP BY clause, allowing us to reference the ordinal positions in it.</p><p>Feel free to share your thoughts on this subject and catch you in the next one.</p><blockquote>You can <a href="https://medium.com/@tobisam/membership">become a Medium member</a> to support me and enjoy more stories like this.</blockquote><h4>References</h4><ul><li><a href="https://learn.microsoft.com/en-us/sql/t-sql/queries/select-transact-sql?view=sql-server-ver16&amp;redirectedfrom=MSDN#logical-processing-order-of-the-select-statement">SELECT — Transact-SQL</a></li><li><a href="https://blogs.oracle.com/connect/post/on-rownum-and-limiting-results">ROWNUM</a> — Oracle</li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/select.html">MySQL reference</a></li><li><a href="https://www.postgresql.org/docs/current/using-explain.html">PostgreSQL</a> - EXPLAIN</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5b949f34f31" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-sql-execution-orders-varies-across-databases-b5b949f34f31">How SQL execution orders varies across databases</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to scale Airbyte]]></title>
            <link>https://medium.com/geekculture/how-to-scale-airbyte-29ca9e07ad3a?source=rss-92fab82e0c7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/29ca9e07ad3a</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[airbyte]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Tobi Sam]]></dc:creator>
            <pubDate>Thu, 06 Jul 2023 00:27:50 GMT</pubDate>
            <atom:updated>2023-07-06T00:27:50.311Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simple approaches to scale your Airbyte deployment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nB-rBj2wJ42VImz3" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Airbyte is becoming (or has become) a very popular Open Source solution for data ingestion in the modern data stack. I have personally used it in multiple projects and it gets the job done!</p><p>But as the amount of data being processed and transferred through Airbyte increases, you may need to scale your instance to handle the higher data volume or to deal with more complex transformations that require more resources . Scaling ensures that your Airbyte infrastructure can efficiently handle the data ingestion, transformation, and synchronization tasks.</p><p>In this article, we will explore some simple but effective strategies and techniques to scale Airbyte.</p><h3>Scaling using Airbyte configurations</h3><p>It is first important to revisit the architecture of Airbyte to see what parts we would need to focus on when scaling becomes an issue.</p><p>How a worker executes work depends on the Airbyte deployment. In the Docker deployment, an Airbyte worker spins up at least one Docker container. In the Kubernetes deployment, an Airbyte worker will create at least one Kubernetes pod. The created resource (Docker container or Kubernetes pod) does all the actual work.</p><blockquote><strong>Thus, scaling Airbyte is a matter of ensuring that the Docker container or Kubernetes Pod running the jobs has sufficient resources to execute its work.</strong></blockquote><p>Jobs-wise, we are mainly concerned with <strong>Sync jobs </strong>when thinking about scale. Sync jobs sync data from sources to destinations and are the majority of jobs run. Sync jobs use two workers. One worker reads from the source; the other worker writes to the destination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2PpmMck1hZYAFHdB9eP5w.png" /><figcaption>Airbyte worker architecture — Image by author</figcaption></figure><p>The main memory culprit is the source worker and there are two major things to consider when scaling Airbyte, Memory and Disk space.</p><h3>Memory</h3><h4>The Problem</h4><ul><li>The main memory culprit is the source worker. <strong>This is because the Source worker reads up to 10,000 records in memory.</strong> This can present problems for database sources with tables that have large row sizes. e.g. a table with an average row size of 0.5MBs will require 0.5 * 10000 / 1000 = 5GBs of RAM.</li><li>Airbyte’s Java connectors currently follow Java’s default behavior with container memory and w<strong>ill only use up to 1/4 of the host’s allocated memory.</strong> Imagine you have a Docker agent with 8GBs of RAM configured, a Java connector limits itself to 2GBs of RAM and will throw Out-of-Memory exceptions if the memory exceeds this.</li><li>The same applies to Kubernetes pods.</li></ul><h4>The Solution</h4><p>You may want to customize two fields in your Airbyte configurations.</p><ul><li>The JOB_MAIN_CONTAINER_MEMORY_REQUEST : Defines the job container&#39;s <strong>minimum</strong> RAM usage.</li><li>The JOB_MAIN_CONTAINER_MEMORY_LIMIT : Defines the job container&#39;s <strong>maximum</strong> RAM.</li><li>In our example above, we could modify the maximum RAM usage of the container like this: JOB_MAIN_CONTAINER_MEMORY_REQUEST=6g to allow the container to use 6GB of the host&#39;s allocated memory.</li></ul><p>You can find these variables in the .env file of the <a href="https://github.com/airbytehq/airbyte-platform/blob/main/.env">Airbyte repo.</a></p><p>In general, ensure you provision sufficient amount of RAM for your Airbyte instance so you don’t run into the memory issues mentioned.</p><h3>Disk</h3><h4>Problem</h4><ul><li>This problem is less likely to occur in smaller organisations but one that could very well still happen. An average Airbyte connector size is around 300MB. If you have multiple connectors, they could easily add up to 10GB of disk space.</li><li>Long-running jobs can generate a lot of logs, but Airbyte has tried to minimize this issue by <a href="https://docs.airbyte.com/operator-guides/scaling-airbyte/#disk-space">implementing back-pressure</a>.</li></ul><h4>Solution</h4><p>Consider how many connectors you might have to work with and provide enough disk space to cater to them. Airbyte recommends simply having at least 30GB of disk space for your Airbyte deployment.</p><h3>Scaling Airbyte with Kubernetes</h3><p>Airbyte can also be <a href="https://docs.airbyte.com/deploying-airbyte/on-kubernetes-via-helm/">deployed on Kubernetes.</a></p><p>Apart from the benefits of high availability, fault tolerance, and more, Kubernetes provides efficient resource utilisation for applications, and in our case Airbyte. To resolve the memory issue mentioned above, we could leverage the <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/verticalpodautoscaler">Vertical Pod Autoscaler (VPA)</a> feature of Kubernetes to either make recommendations on what the CPU and Memory requirements should be for our pod or to automatically scale the pod to the required capacity.</p><blockquote>Vertical Pod autoscaling provides recommendations for resource usage over time.</blockquote><p>In <a href="http://plural.sh/">Plural.sh</a> for example, you could use their GUI to see recommendations from the VPA and either manually or automatically apply those changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x729t9UYwMNGsZydX41geQ.png" /><figcaption>Airbyte worker Plural.sh console — Image by author</figcaption></figure><p>To learn more about deploying Airbyte, check out this open-source solution <a href="https://www.plural.sh/applications/airbyte">Plural.sh </a>to learn more about how to deploy Airbyte on Kubernetes.</p><p>Even though this wasn’t an exhaustive list, I hope you found these short tips helpful. Feel free to share your recommendations in the comments.</p><h3>Resources</h3><ul><li><a href="https://cloud.google.com/kubernetes-engine/docs/concepts/verticalpodautoscaler">https://cloud.google.com/kubernetes-engine/docs/concepts/verticalpodautoscaler</a></li><li><a href="https://docs.airbyte.com/operator-guides/scaling-airbyte/">https://docs.airbyte.com/operator-guides/scaling-airbyte/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29ca9e07ad3a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-scale-airbyte-29ca9e07ad3a">How to scale Airbyte</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Easy Way to Speed Up your dbt Runs on BigQuery]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/an-easy-way-to-speed-up-your-dbt-runs-on-bigquery-24238ac20f8a?source=rss-92fab82e0c7a------2"><img src="https://cdn-images-1.medium.com/max/1126/1*Gvb-EncycEt33nt7rMEXwQ.png" width="1126"></a></p><p class="medium-feed-snippet">Speed up dbt runs using concurrent queries</p><p class="medium-feed-link"><a href="https://medium.com/data-science/an-easy-way-to-speed-up-your-dbt-runs-on-bigquery-24238ac20f8a?source=rss-92fab82e0c7a------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/an-easy-way-to-speed-up-your-dbt-runs-on-bigquery-24238ac20f8a?source=rss-92fab82e0c7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/24238ac20f8a</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Tobi Sam]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 16:26:15 GMT</pubDate>
            <atom:updated>2023-04-12T08:38:32.480Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Tips and Tricks for Crafting Effective SQL Commands in Python]]></title>
            <link>https://medium.com/geekculture/how-to-write-5-common-sql-commands-in-pythons-pandas-17478ccf03ae?source=rss-92fab82e0c7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/17478ccf03ae</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Tobi Sam]]></dc:creator>
            <pubDate>Mon, 02 Jan 2023 23:01:45 GMT</pubDate>
            <atom:updated>2023-01-05T12:12:46.109Z</atom:updated>
            <content:encoded><![CDATA[<p>Transform your data with Python using familiar SQL concepts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7UZ_O7M1zitV-wtQ" /><figcaption>Photo by <a href="https://unsplash.com/@thisisengineering?utm_source=medium&amp;utm_medium=referral">ThisisEngineering RAEng</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you are already familiar with SQL and are curious about how you could use Python to manipulate your data the same way you do in SQL, these Pandas tips might be a helpful place to get started. We will look at these 5 SQL commands and how they could be rewritten in Python:</p><ol><li>SELECT</li><li>WHERE</li><li>GROUP BY</li><li>JOIN</li><li>ORDER BY</li></ol><p>We will use a selection from an orders table throughout this article:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dw67Zna4quRO0TRmdDpbOA.png" /><figcaption>orders table — Image by author</figcaption></figure><h3>1. SELECT statement</h3><h4>SQL</h4><p>If we want to view the customer_id and customer_group columns, we would simply use the SELECT statement in SQL:</p><pre>SELECT customer_id, customer_group<br>FROM orders</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*5McsSnDtSjVA0ZFOb0XWrA.png" /><figcaption>SQL Select statement result — Image by author</figcaption></figure><h4>Python</h4><p>In Python, to do the same thing, we will first import the <a href="https://pypi.org/project/pandas/">Pandas library</a>, which allows us to read our primary orders table from a csv file into a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html">Dataframe</a>, and then we can “select” a subset of that Dataframe, which is customer_id and customer_group:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74aa7d039163a1bd79a9c0f0553eb673/href">https://medium.com/media/74aa7d039163a1bd79a9c0f0553eb673/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*SLHmSyZNK0e0YQgbeV0nEg.png" /><figcaption>Image by author</figcaption></figure><p>And with that, we get the same result as we did in SQL.</p><p>Let’s breakdown what is happening on this line:</p><p>orders[[&#39;customer_id&#39;, customer_group&#39;]]</p><p>We first of all right the name of the Dataframe of interest, which is orders.</p><p>In Pandas, when selecting a subset of a Dataframe, the inner square brackets [] define a <a href="https://docs.python.org/3/tutorial/datastructures.html#tut-morelists">Python list</a> with column names (in our case, customer_id and customer_group), whereas the outer brackets are used to select the data from a pandas DataFrame .</p><p>To select a single column from the Dataframe, we wouldn’t need to use the double brackets. We would use the selection brackets only and write this instead:</p><p>orders[&#39;customer_id&#39;]</p><p>It’s important to note than when a single column is selected, the returned object is a pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.html#pandas.Series"><strong>Series</strong></a> and not a Dataframe. We only need double brackets when we have a list of columns to retrieve or when we want to return a Pandas Dataframe.</p><h3>2. WHERE clause</h3><h4><strong>SQL</strong></h4><p>Now in SQL, let’s say we would like to see only orders from B2B customers, we will use the WHERE clause to <strong>filter</strong> the table:</p><pre>SELECT * <br>FROM orders <br>WHERE customer_group = &#39;B2B&#39;</pre><p>And we get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*59EYBTxK6kTMH6otPGQgDQ.png" /><figcaption>Image by author</figcaption></figure><p>SQL is pretty straightforward, right? 😄</p><h4>Python</h4><p>In Python, the corresponding code looks like this:</p><pre>orders[orders[&#39;customer_group&#39;]==&#39;B2B&#39;]</pre><p>Also, if we wanted to filter on a numeric column. In SQL we would write something like this:</p><pre>WHERE total_net &gt; 500</pre><p>It looks a bit similar in Python, and since there is no “WHERE” clause in Pandas, we will use the square brackets again to give us a subset of the original Dataframe:</p><pre>orders[orders[&#39;total_net&#39;]&gt;500]</pre><p>We can also use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isin.html">isin</a> function to filter our Dataframe:</p><pre>orders[orders[&quot;customer_group&quot;].isin([&quot;B2B&quot;, &quot;B2C&quot;])]</pre><h3>3. GROUP BY statement &amp; aggregations</h3><p>Now let’s look at some aggregations. In SQL, when you apply any sort of aggregation operation to a table, such as, SUM, MAX, MIN, AGG and so on, you would typically need to <strong>group by</strong> the column(s) you are interested in; well, unless you only want to see the total sales in a table, for example.</p><p>Using the orders table, let’s look at the total net sales by product name.</p><h4><strong>SQL</strong></h4><pre>SELECT product_name, SUM(total_net) AS total<br>FROM orders<br>GROUP BY product_name</pre><p>Which will return:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*s3v4fQptMPHoJlfC-mNiOQ.png" /><figcaption>SQL Groupby — Image by author</figcaption></figure><h4>Python</h4><p>Pandas has a convenient <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html"><strong><em>groupby</em></strong></a> function which returns a groupby object when called. If we want to apply an aggregation function (in this case SUM) to a particular column in the Dataframe, we can do it in 3 simple steps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/681706681d5b3d4a08d15af82102b989/href">https://medium.com/media/681706681d5b3d4a08d15af82102b989/href</a></iframe><p>Which will return:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*NzOr1eEKJchd3nKgV_QM_A.png" /><figcaption>Pandas Groupby example — Image by author</figcaption></figure><p>This can also be done in a <em>Pythonic</em> way on one line:</p><pre>orders.groupby(&quot;product_name&quot;)[[&quot;total_net&quot;]].sum()</pre><h3>4. JOIN clause</h3><p>Another very common SQL command is the JOIN clause. It is used to combine rows from two or more tables based on a related column between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwOUHWBSUu0BBWslg6L9IQ.png" /><figcaption>SQL join to Python — Image by author</figcaption></figure><p>Let’s assume we have another table called “Customers” which looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*WX7MnoZMDDIUK1nqdFd8Dw.png" /><figcaption>Customers table — Image by author</figcaption></figure><p>A related column between the orders table above and this customers table is the customer_id column. So in SQL, we would write the following to join both tables:</p><h4>SQL</h4><pre>SELECT o.order_id, c.customer_id, c.customer_name, c.country_code<br>FROM orders AS o<br>INNER JOIN customers AS C<br>ON o.customer_id = c.customer_id</pre><p>which would return this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MzTed6Ro7IrqC761sb5HwQ.png" /><figcaption>SQL JOIN example — Image by author</figcaption></figure><h4>Python</h4><p>In Python, let’s start by first selecting the columns we are interested in from both Dataframes and saving those into two new Dataframes to make this easier to follow.</p><pre>orders_a = orders[[&quot;customer_id&quot;,&quot;order_id&quot;, &quot;product_name&quot;]]<br><br>customers_a = customers[[&quot;customer_id&quot;,&quot;customer_name&quot;,&quot;country_code&quot;]]</pre><p>In Pandas, the join function uses the index from both Dataframes to complete a join. So we set the index for each Dataframe and the join function uses that to combine both Dataframes. We also specify what sort of join we would like using the how parameter:</p><pre>orders_a.set_index(&quot;customer_id&quot;).join(customers_a.set_index(&quot;customer_id&quot;), how=&#39;inner&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nh1VDC-GatDVibNumlMZcQ.png" /><figcaption>Pandas Join example — Image by author</figcaption></figure><p>We can also use the on parameter</p><pre>orders_a.join(customers_a.set_index(&#39;customer_id&#39;), on=&#39;customer_id&#39;, how=&#39;inner&#39;)</pre><p>DataFrame.join always uses customers_a ‘s index but we can use any column in orders_a. That is why we didn’t need to set the index for orders_a in the second approach as this method preserves the original DataFrame’s index in the result.</p><blockquote>Note: JOINs in Pandas can also be done using the <a href="https://pandas.pydata.org/docs/reference/api/pandas.merge.html#pandas.merge"><strong>merge()</strong></a> function.</blockquote><h3>5. ORDER BY keyword</h3><p>The last thing we will look at is how we can <strong>sort</strong> our results. In SQL, we use the <strong>ORDER BY</strong> keyword to sort the results of a query. Let us sort a simple query result by the customer_id column in descending order.</p><h4>SQL</h4><pre>SELECT order_id, customer_id, customer_group<br>FROM orders<br>ORDER BY customer_id DESC</pre><blockquote>The ORDER BY keyword sorts the records in ascending order by default, but we can change that using the DESC keyword.</blockquote><h4>Python</h4><p>To sort a Dataframe in Pandas, we make use of the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html"><strong>sort_values</strong></a> function and our code will look like this:</p><pre>#Select the columns we would like to see from the original Dataframe<br>orders_columns = orders[[&quot;order_date&quot;,&quot;customer_id&quot;, &quot;order_country&quot;]]<br><br>#Sort the Dataframe<br>orders_columns.sort_values(by=[&quot;order_date&quot;], ascending=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*UVk-Sh2STlHPbe3Z2T9-FQ.png" /><figcaption>Pandas sort example — image by author</figcaption></figure><p>This could have been done in one line too:</p><pre>orders[[&quot;order_id&quot;,&quot;customer_id&quot;, &quot;customer_group&quot;]].sort_values(by=[&quot;customer_id&quot;], ascending=False)</pre><p>The sort_values function also sorts records in ascending order by default. That is why we had to include the ascending=False parameter in the snippet above to make sure our results were returned in descending order.</p><h3>Conclusion</h3><p>That is all for now and I hope you found this helpful. If you have any tips and tricks, feel free to share them in the comments section.</p><blockquote>You can<a href="https://medium.com/@tobisam/membership"> become a Medium member</a> and enjoy more stories like this and that also supports writers like me.</blockquote><h3>REFERENCE</h3><ul><li><a href="https://pandas.pydata.org/docs/index.html">Pandas Documentation</a></li><li><a href="https://towardsdatascience.com/5-pandas-group-by-tricks-you-should-know-in-python-f53246c92c94">Pandas Group By tricks by</a> <a href="https://medium.com/u/1fdda183cca2">Suraj Gurav</a></li><li><a href="https://www.w3schools.com/python/pandas/ref_df_groupby.asp">W3 Schools Pandas Groupby</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17478ccf03ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-write-5-common-sql-commands-in-pythons-pandas-17478ccf03ae">Tips and Tricks for Crafting Effective SQL Commands in Python</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Real-Time Event Streaming Pipeline with Kafka, BigQuery & Looker Studio]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/real-time-event-streaming-with-kafka-bigquery-69c3baebb51e?source=rss-92fab82e0c7a------2"><img src="https://cdn-images-1.medium.com/max/2268/1*2k4w4LltiNGHxJ08OdjyDg.png" width="2268"></a></p><p class="medium-feed-snippet">A simple data engineering project</p><p class="medium-feed-link"><a href="https://medium.com/data-science/real-time-event-streaming-with-kafka-bigquery-69c3baebb51e?source=rss-92fab82e0c7a------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/real-time-event-streaming-with-kafka-bigquery-69c3baebb51e?source=rss-92fab82e0c7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/69c3baebb51e</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Tobi Sam]]></dc:creator>
            <pubDate>Thu, 24 Nov 2022 19:50:35 GMT</pubDate>
            <atom:updated>2022-11-25T18:33:55.768Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Tracking Changes in a Data Warehouse]]></title>
            <link>https://medium.com/@tobisam/tracking-changes-in-a-data-warehouse-2060c143cb31?source=rss-92fab82e0c7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2060c143cb31</guid>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[slowly-changing-dimension]]></category>
            <dc:creator><![CDATA[Tobi Sam]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 15:49:09 GMT</pubDate>
            <atom:updated>2022-08-17T15:49:09.027Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A person’s hand using a pencil to point at a graph" src="https://cdn-images-1.medium.com/max/1024/1*x_ecoakTygmOpDj4YA-_ww.jpeg" /><figcaption><a href="https://www.pexels.com/photo/report-paper-on-a-white-board-7876383/">Source</a></figcaption></figure><p>When I started working as a data engineer, I often wondered how to deal with a situation where data stored in a database changes over time. For example, what do I do when customers update their personal information and effectively alter the entry in a specific database column? I would ask questions like:</p><ul><li>How do I properly deal with this new record reflected in the data warehouse?</li><li>How do I retain the historical references of a given attribute?</li></ul><p>Thankfully, there are several typical ways to deal with these scenarios in the business world.</p><h3>Scenario: Track sales locations</h3><p>Imagine you work on the Data and Analytics team of an e-commerce site that operates in two cities, London and Berlin. Each city has a sales manager, and the top-performing person gets a monthly bonus. To decide who gets the bonus, we aggregate the performance in a <strong>report we generate at the end of the following month</strong>.</p><p>We need to write the SQL query to retrieve the information about our orders and help us generate the monthly report:</p><pre>SELECT o.order_date, c.customer_city, c.customer_id, o.order_id</pre><pre>FROM `orders` o</pre><pre>LEFT JOIN `customer_dim` c</pre><pre>ON o.customer_id = c.customer_id</pre><p>This snippet pulls the relevant data from the columns in our orders table (note the first two rows, listing the cities of customers <strong>A100</strong> and <strong>B200</strong>):</p><figure><img alt="The columns in our orders table (the first two rows list the cities of customers A100 and B200" src="https://cdn-images-1.medium.com/max/720/0*VQ3OX8VYK8RFwMf9" /><figcaption><strong><em>Figure 1: </em></strong><em>The</em><strong><em> </em></strong><em>orders table</em></figcaption></figure><p>The official report isn’t due until the end of February, but we wanted to get an early glimpse of the results, so we run the following query at the end of January:</p><pre>SELECT order_date, customer_city, COUNT(order_id) AS total_orders</pre><pre>FROM `orders`</pre><pre>WHERE DATE_TRUNC(order_date, month) = ‘2022–01–01’</pre><pre>GROUP BY 1</pre><figure><img alt="A graph showing the aggregated orders in January by city" src="https://cdn-images-1.medium.com/max/1024/0*jnaRuvLhUg-fGI6C" /><figcaption><strong><em>Figure 2: </em></strong><em>Aggregating orders in January by city</em></figcaption></figure><p>It was a close call, but in January, the London Sales Manager won by one extra order. She’s excited and can’t wait to get her bonus.</p><p>Meanwhile, sometime in February, customers <strong>A100</strong> and <strong>B200</strong> moved to Berlin to start a new life. They update their new address in their online profile, so now our <em>orders</em> table and subsequent January report look like this:</p><figure><img alt="Left: The updated orders table. Right: Report showing the updated user locations" src="https://cdn-images-1.medium.com/max/1024/0*XSNHX8RLKYe1iUdr" /><figcaption><strong><em>Figure 4: </em></strong><em>Report showing the updated user locations &amp; a graph showing a false representation of January</em></figcaption></figure><p>As you can see, the latest report is a false representation of the data as it was back in January (when the sales were actually made).</p><p>This isn’t just a problem for the Sales team (let’s hope the London Sales Manager had no plans for her bonus); it also means that other stakeholders in the company wouldn’t know where the customer made their original order. Finally, this could be a bit embarrassing for the Data &amp; Analytics crew tasked with collecting such critical information. Talk about the butterfly effect.</p><h3>The Solution: Slowly Changing Dimensions (SCD)</h3><p>Fortunately, we can solve everyone’s problems by integrating a concept called <a href="https://www.kimballgroup.com/data-warehouse-business-intelligence-resources/kimball-techniques/dimensional-modeling-techniques/">Slowly Changing Dimensions (SCD)</a> into our data warehouse.</p><p>There are <a href="https://www.sqlshack.com/implementing-slowly-changing-dimensions-scds-in-data-warehouses/">several types of SCD techniques</a>, but we’ll focus on <a href="https://www.kimballgroup.com/data-warehouse-business-intelligence-resources/kimball-techniques/dimensional-modeling-techniques/type-2/">Type 2</a> as it’s one of the most common approaches.</p><figure><img alt="SCD Type 2 flowchart diagram by AWS" src="https://cdn-images-1.medium.com/max/1024/0*D-9qR07WSmQoGDfI" /><figcaption><strong><em>Figure 5: </em></strong><em>SCD Type 2 flowchart diagram</em></figcaption></figure><p>The folks at Amazon Web Services (AWS) came up with <a href="https://aws.amazon.com/blogs/big-data/implement-a-slowly-changing-dimension-in-amazon-redshift/">a brilliant flowchart</a>, which lists the steps one should consider when developing SCD Type 2. Above is our slightly modified version, adapted to fit the Google BigQuery data warehouse we’re referencing in our tutorial.</p><p>Starting from left to right, with the customer table at the top serving as the output, you would run the greyed-out steps only once. The rest are applied on every subsequent run of your Extract, Transform, Load (ETL) pipeline.</p><p>We’ll use this chart as our guide throughout the rest of this tutorial.</p><p>Let’s get going.</p><h3>Tutorial: Implementing SCD Type 2</h3><p>While not a deal-breaker, we assume readers have some previous experience with SQL and data modelling. Not there yet? You’re most welcome to follow along anyway!</p><p><strong>Prerequisites:</strong></p><ol><li>A Google BigQuery account</li><li>A sample project</li><li>SQL editor of your choice</li></ol><h3>Create a dimension schema with SCD attributes</h3><p>We’ll need to modify our original customer dimension table (left), which currently contains only three fields, and add the SCD attributes that would help us track changes over time:</p><figure><img alt="Highlighting the SCD Type 2 fields added to the customer_dim table" src="https://cdn-images-1.medium.com/max/1024/0*gTqaYFwlEZeiQ9TA" /><figcaption><strong><em>Figure 6</em></strong><em>: Highlighting the SCD Type 2 fields added to the customer_dim table</em></figcaption></figure><p>Here is a description of the new SCD attributes we will be adding:</p><ul><li><strong>customer_sk</strong>: An artificial primary key (aka, a surrogate key) that is a sequentially assigned integer or a uniquely generated value for every Type 2 change in our dimension. This surrogate key will be the unique identifier of each row in the table.</li><li><strong>customer_id</strong>: Same as the original table.</li><li><strong>name</strong>: Same as the original table.</li><li><strong>customer_city</strong>: Same as the original table.</li><li><strong>tracking_hash</strong>: This gives us an effective way to track changes of specific fields in a given customer_dim table. This way, we don’t need to keep track of multiple columns in the table — a single column indicates when any row changes.</li><li><strong>valid_from</strong>: Specifies the date from which the record is valid.</li><li><strong>valid_to</strong>: Specifies the last date before the record changed.</li><li><strong>record_updated_at</strong>: Specifies the date a record was last updated in the table.</li><li><strong>current_flag</strong>: Specifies if the record is the current/most recent entry.</li></ul><p>Here is the code to create the customer dimension schema:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4607af48b2ba2f1a29b58385af1518da/href">https://medium.com/media/4607af48b2ba2f1a29b58385af1518da/href</a></iframe><h3>Initial load</h3><p>The next step is to load the initial data into the table, adding the default SCD values and modelled attributes from the raw_customer source table.</p><p>You should run the following SQL snippet only once:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc456896c0696500c9f4294683d534cd/href">https://medium.com/media/dc456896c0696500c9f4294683d534cd/href</a></iframe><ul><li><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/uuid_functions#generate_uuid">GENERATE_UUID</a>(): This function is specific to BigQuery. It creates a unique identifier that serves as the surrogate key of each row in the query result during run-time. You could also use the <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/hash_functions#md5">MD5</a> hash function to run a hash on all columns in your table and generate a 16 bytes key.</li><li>Only the <strong><em>tracking_hash</em></strong> column will be used to detect a changed record. That way, we don’t have to keep track of multiple columns within the same table. The tracking_hash column in the code snippet above concatenates two columns, name and customer_city. In our example, we need to track only the customer_city column, but I wanted to show how we would approach multiple columns. Feel free to remove the CONCAT()function and replace it with the customer_city column alone. Your code on line 16 should then look like this:</li></ul><pre>TO_HEX(MD5(customer_city)) AS tracking_hash,</pre><ul><li>The MD5 function computes the hash of the input using the MD5 algorithm. The input can be either STRING or BYTES.</li><li>The TO_HEX function converts the sequence of bytes returned by the MD5 algorithm into a hexadecimal string, ensuring the hash outputs as a string.</li></ul><h3>Use a proxy table</h3><p>Before we continue, we should create a proxy customer_dim table, e.g., the customer_dim_next.</p><p>The proxy table is an exact copy of the customer_dim table that prevents any manipulations of the primary customer table. This precaution guarantees that our primary table remains intact if a failure occurs. Once all changes have successfully passed, we can load the content of customer_dim_next<em> </em>directly into<em> </em>customer_dim<em>.</em></p><pre>CREATE OR REPLACE TABLE customer_dim_next</pre><pre>AS SELECT * FROM customer_dim;</pre><h3>Subsequent loads</h3><p>For subsequent loads, we create a staging table called customer_dim_staging that retrieves data from the raw_customer source table and compares it to the target customer_dim table we’ve just created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29c62e564e34598d10e3fcadd774af3e/href">https://medium.com/media/29c62e564e34598d10e3fcadd774af3e/href</a></iframe><p>The schema of the staging table is very similar to the customer_dim table but includes two new flag columns that help us identify what sort of change occurred in the source table. There isn’t any surrogate key in this table.</p><ul><li>The new_record flag indicates a new record that doesn’t exist in the target table and needs to be inserted.</li><li>The changed_record flag tells us that we need to update the relevant record in the target table.</li></ul><p>After you’ve created the schema for the staging table, you would run this to track changes in the raw_customer source table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c313ae6b5d98559ea54b4ce6f512049f/href">https://medium.com/media/c313ae6b5d98559ea54b4ce6f512049f/href</a></iframe><h3>UPSERT (UPDATE and INSERT)</h3><p>This section is the core of our operation, where we perform three tasks:</p><ol><li>First, we track changes:</li></ol><ul><li>When we identify a Type 2 change in any record, we update the SCD columns for that record with a new valid_to date.</li><li>We set the current_flag to 0 since it’s no longer the latest version.</li><li>We set the record_updated_at<em> </em>column to the current timestamp.</li></ul><p>2. Next, we insert a new record with the most recent data points into the customer_dim table. We do the same if a new record is identified in the source table.</p><p>3. Lastly, we update all other columns that aren’t tracked as SCD Type 2 but might have changed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39f70d0e0e26fbb998d1be252878cde4/href">https://medium.com/media/39f70d0e0e26fbb998d1be252878cde4/href</a></iframe><h3>Create the final table</h3><p>Assuming all went well, the final step in your ETL pipeline is to replace the customer_dim table with the content from our proxy table, customer_dim_next.</p><pre>CREATE OR REPLACE TABLE customer_dim AS (</pre><pre>SELECT * FROM customer_dim_next;)</pre><p>Now, with all changes tracked within the same table, our SCD Type 2 table should look like this:</p><figure><img alt="The updated customer_dim table with SCD Type 2 attributes" src="https://cdn-images-1.medium.com/max/1024/0*oCrExkSkftycWLxl" /><figcaption><strong><em>Figure 7: </em></strong>customer_dim<em> table with SCD Type 2 attributes</em></figcaption></figure><h4>Recreating the orders dataset</h4><p>After successfully implementing SCD Type 2, we need an updated orders table, which includes our newly-created surrogate key, the current_flag column, or the valid_from and valid_to columns.</p><p>Let’s recreate our orders table (see figure 1 above) and modify our query by adding the valid_from and valid_to date columns to the WHERE clause, like so:</p><pre>SELECT</pre><pre> o.order_date,</pre><pre> c.customer_city,</pre><pre> c.customer_id,</pre><pre> o.order_id</pre><pre>FROM `orders` o</pre><pre>LEFT JOIN `customer_dim` c</pre><pre>ON o.customer_id = c.customer_id</pre><pre>WHERE o.order_date BETWEEN valid_from AND valid_to</pre><pre>AND DATE_TRUNC(order_date, month) = ‘2022–01–01’</pre><p>Now, whenever we query our orders table, the customer_city column should always match the city that was valid when an order was placed:</p><figure><img alt="Left: The table shows the customers’ correct location. Right: The accurate report" src="https://cdn-images-1.medium.com/max/1024/0*Iq3nhaJAXmXSCiDp" /><figcaption><strong><em>Figure 8: </em></strong><em>The table shows the customers’ correct location, resulting in accurate reporting</em></figcaption></figure><p>I hope this tutorial will help you implement and improve your data warehousing strategy.</p><p>Feel free to share your thoughts in the comments below, and <a href="https://medium.com/@tobisam">check out</a> my previous articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2060c143cb31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I improved my old Windows 10 laptop’s performance in 3 steps]]></title>
            <link>https://medium.com/geekculture/how-i-improved-my-old-windows-10-laptops-performance-in-3-steps-7dfb88a265e0?source=rss-92fab82e0c7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dfb88a265e0</guid>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[laptop-repair]]></category>
            <category><![CDATA[ssd]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[laptop]]></category>
            <dc:creator><![CDATA[Tobi Sam]]></dc:creator>
            <pubDate>Wed, 19 Jan 2022 03:03:17 GMT</pubDate>
            <atom:updated>2024-04-25T12:49:57.079Z</atom:updated>
            <content:encoded><![CDATA[<h4>How I optimized my old laptop for data engineering and Python programming tasks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vaGYN0YhnjQk-wC1" /><figcaption>Photo by <a href="https://unsplash.com/@pieronigro?utm_source=medium&amp;utm_medium=referral">Piero Nigro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When I got my laptop in 2015, it was pretty good for my needs at the time. As it started being used for more heavy duty workloads and began to wear, I knew I was lagging way behind. I also got exposed to what a MacBook could do in that time and I heard “When you go Mac, you never go Back”. There is a lot of truth in this.</p><p>Anyway, I decided to start saving up for a high-end laptop, but as a Windows fan-boy, I was curious to see if I could improve my oldie in anyway.</p><h4>My Old laptop specs</h4><ul><li>2015 Dell Inspiron 13 2-in-1 laptop (with touchscreen)</li><li>512 GB</li><li>8GB RAM</li><li>Intel Core i7 (2.6Ghz)</li></ul><h3>Follow this guide at your own risk! I am only documenting steps I took which worked for me.</h3><h3><strong>Before you begin</strong></h3><ul><li>Run benchmarks to compare speeds before and after upgrade. You can use <a href="https://crystalmark.info/en/software/crystaldiskmark/">CrystalDiskMark</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lAPTAQsPYqyl7HS0ig-Qw.jpeg" /><figcaption>Benchmark score before laptop upgrade. See below for ‘after’ scores — Image by author</figcaption></figure><ul><li>Uninstall applications and try to reduce your hard drive’s capacity utilization. PCs tend to slow down when more than 70% of the hard drive’s total capacity has been used.</li><li>If you plan on upgrading your hard drive, watch <a href="https://www.youtube.com/watch?v=nbGkPYtXtmA">this video</a> to see how to install Windows 10 on a flash drive. Also, make sure you backup your data to an external hard drive.</li></ul><h3>The 3-step process</h3><h4>1. Activate Drive Defragmentation</h4><p>Optimize your drive by making sure ‘defragment’ is active on your PC. If you have a device with older hardware with traditional rotating platters, organizing the data can increase the machine’s responsiveness. This step is particularly useful if you (like me) have an old hard drive with rotating parts. (This step is still helpful even if you have SSD storage).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*G6nK29SpxanraLlWUWenMg.jpeg" /><figcaption>Optimise Drives Screenshot — Image from author</figcaption></figure><p>To activate disk defragmentation, open the search bar and type in “Defragment”. Select the first option and you should see the screenshot here. Then make sure the drive you would like to optimize is highlighted, then click the “Optimize” button.</p><p>Note that this process can take a long time depending on the amount of data stored on the drive. It is probably best to leave the process running overnight if you have an older system with lots of data.</p><h4>2. Remove bloatware from Windows 10</h4><p>Windows comes preinstalled with a lot of applications, services and background telemetry functions that aren’t used a lot and which in turn, slow down your PC’s performance.</p><p>You can remove these bloatware from Windows10 using this free utility: <a href="https://github.com/Sycnex/Windows10Debloater">https://github.com/Sycnex/Windows10Debloater</a>. This tool removes unnecessary pre-installed Windows applications, stops some telemetry functions, stops Cortana from being used as your Search Index, disables unnecessary scheduled tasks, and more…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9k5oDhID5654TEeDXdKGg.jpeg" /><figcaption>Windows Start Menu — Image <a href="https://www.youtube.com/watch?v=SpauzQBwmuA&amp;ab_channel=IansTech">source</a></figcaption></figure><blockquote>Watch<a href="https://www.youtube.com/watch?v=7SdtxrsZN8k&amp;ab_channel=GEEKrar"> this tutorial </a>on how to use this tool</blockquote><p>I experienced very noticeable improvements in my PC’s performance! I noticed that my laptop started responding quicker to tasks and it was able to switch between applications with less of a hassle. It wasn’t perfect but after noticing these improvements, I knew I wanted more…</p><h4><strong>3. Upgrade Hard Disk Drive (HDD) to Solid State Drive (SSD)</strong></h4><p>Most older laptops come with HDD installed. The main difference between HDD and SSD is how data is stored and retrieved.</p><blockquote>A hard disk drive (HDD) is a traditional storage device that uses mechanical platters and a moving read/write head to access data. A solid state drive (SSD) is a newer, faster type of device that stores data on instantly-accessible memory chips. — <a href="https://www.avast.com/c-ssd-vs-hdd">Avast</a></blockquote><p>After learning about the differences, I decided to upgrade my HDD to SSD storage. This was the game changer for my oldie! It significantly improved load speed and general speed. It took mere seconds for my laptop to reboot compared to about to 2–4 minutes on the old HDD storage. Apps opened super fast and everything else on my laptop worked just quick!</p><p>Here are my benchmark scores after installing the SSD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnZJU_ValahiD3RTZeyHGg.jpeg" /><figcaption>Benchmark scores after upgrade — Image by author</figcaption></figure><p>These scores were significantly higher than before the upgrade and I could notice it.</p><p>If you are going to follow this step, find out the exact model of your PC and what SSD would be compatible with it. Here is a link to the SSD I got: <a href="https://www.idealo.de/preisvergleich/OffersOfProduct/201032817_-870-evo-500gb-samsung.html"><em>Link to amazon SSD</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEfavsxeB4sf3Q6Qm4EVEA.jpeg" /><figcaption>Laptop internals — Image by author</figcaption></figure><blockquote>To disassemble your laptop yourself, watch this video on how to disassemble your laptop: <a href="https://www.youtube.com/watch?v=t0rq0MoKtDA">https://www.youtube.com/watch?v=t0rq0MoKtDA</a></blockquote><p>After this final step, I made sure I followed step 1 and 2 above again to make sure my system was well optimized.</p><h3>Extras</h3><ul><li><strong>Setup a clean Windows 10 desktop</strong>. This video was really the icing on the cake for me as I had a fresh new OS installed plus a really clean minimalist-looking desktop interface. I would encourage you to check <a href="https://www.youtube.com/watch?v=_e7JTaPMf7Q&amp;t=236s&amp;ab_channel=Dave2D">this video out by Dave 2D.</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbEH3W0bC8SWe2cYNP7NzA.jpeg" /><figcaption>Image from <a href="https://www.youtube.com/watch?v=_e7JTaPMf7Q&amp;ab_channel=Dave2D">Dave 2D</a></figcaption></figure><ul><li><strong>Upgrade your battery.</strong> My battery had degraded over time and was at 55% capacity. Since I was feeling confident after installing the SSD myself, I decided to also upgrade my battery.</li></ul><h4>Conclusion</h4><p>My initial laptop specs weren’t so bad. The major issues I noticed were the bloatware and the fact that I was still using HDD. Upgrading the laptop helped me to better understand the inner workings of a PC and many of the underlying services running in Windows 10. Hope this helps someone out to give your PC a fighting chance.</p><blockquote>You can <a href="https://medium.com/@tobisam/membership">become a Medium member</a> and enjoy more stories like this.</blockquote><h4>References</h4><ul><li><a href="https://www.windowscentral.com/tips-tricks-increase-pc-performance-windows-10">https://www.windowscentral.com/tips-tricks-increase-pc-performance-windows-10</a></li><li><a href="https://www.avast.com/c-ssd-vs-hdd">https://www.avast.com/c-ssd-vs-hdd</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dfb88a265e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-i-improved-my-old-windows-10-laptops-performance-in-3-steps-7dfb88a265e0">How I improved my old Windows 10 laptop’s performance in 3 steps</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>