<?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 Nazeer Syed on Medium]]></title>
        <description><![CDATA[Stories by Nazeer Syed on Medium]]></description>
        <link>https://medium.com/@nazeer.td?source=rss-0a9bc48881dc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_EQsWAmPcbJUhZ9H</url>
            <title>Stories by Nazeer Syed on Medium</title>
            <link>https://medium.com/@nazeer.td?source=rss-0a9bc48881dc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:43:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nazeer.td/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[Why Is Your Python Code a Mess? 5 Design Patterns to Rethink if you are a Data Engineer]]></title>
            <link>https://medium.com/@nazeer.td/why-is-your-python-code-a-mess-5-design-patterns-to-rethink-if-you-are-a-data-engineer-4050234cd40b?source=rss-0a9bc48881dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4050234cd40b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Nazeer Syed]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 05:01:02 GMT</pubDate>
            <atom:updated>2026-11-30T05:01:02.242Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KeBuuLNdvZ9H_dbo2DrEg.png" /><figcaption>AI Generated Image</figcaption></figure><p>Design patterns often sound complicated, especially when introduced through textbook diagrams and lengthy class names. But they’re not about adding unnecessary complexity. <strong>Design patterns are simply reusable solutions to problems developers commonly face</strong> — like loading the same configuration repeatedly, managing growing <strong>if/elf </strong>chains, or making a pipeline depend on services it doesn’t actually need.</p><p>In this post, we’ll explore seven Python design patterns, from simple to more advanced. For each pattern, we’ll look at the problem it solves, write meaningful code with design pattern, and discuss when to use it and when to avoid it.</p><h3>1. Factory Pattern — Creating Objects</h3><p><strong>Purpose:</strong> Creates objects without exposing all the object-creation details to the code that uses them.</p><h4>Real-world example</h4><p>Imagine you have a notification system. You can send notifications through Email, SMS, or WhatsApp.</p><p>Instead of creating these objects manually everywhere, a Factory decides which object to create based on your request.</p><pre>class Email:<br>    def send(self):<br>        print(&quot;Sending Email&quot;)<br><br>class SMS:<br>    def send(self):<br>        print(&quot;Sending SMS&quot;)<br><br>class WhatsApp:<br>    def send(self):<br>        print(&quot;Sending WhatsApp message&quot;)<br><br>class NotificationFactory:<br>    @staticmethod<br>    def create_notification(notification_type):<br>        if notification_type == &quot;email&quot;:<br>            return Email()<br>        elif notification_type == &quot;sms&quot;:<br>            return SMS()<br>        elif notification_type == &quot;whatsapp&quot;:<br>            return WhatsApp()<br>        else:<br>            raise ValueError(&quot;Invalid notification type&quot;)<br><br># Object creation handled by Factory<br>notification = NotificationFactory.create_notification(&quot;sms&quot;)<br>notification.send()</pre><pre>Output: Sending SMS</pre><p><strong>How it works :</strong></p><p>1.You request an “<strong>sms</strong>” notification.<br>2.The <strong>Factory</strong> checks the requested type.<br>3.It creates an <strong>SMS object</strong>.<br>4.You use the <strong>object </strong>without worrying about its creation details.</p><p><strong>Without Factory:</strong> Your main code would need to contain object-creation logic everywhere.</p><p><strong>With Factory:</strong> Object creation is centralized in one place.</p><p><strong>When to use it:</strong> When you have multiple object types and their creation logic should be centralized or hidden from the caller.</p><h3>2. Strategy Pattern — Switching Behaviors</h3><p><strong>Purpose:</strong> Allows you to switch between different algorithms or behaviors without changing the code that uses them.</p><h4>Real-world example</h4><p>A shopping cart can apply different discount strategies:</p><ul><li>Regular customer → no discount</li><li>Festival sale → 20% discount</li><li>Student → 10% discount</li></ul><p>Instead of putting all the discount calculations into one large method, we create separate strategies.</p><pre>class RegularDiscount:<br>    def apply(self, price):<br>        return price<br><br>class FestivalDiscount:<br>    def apply(self, price):<br>        return price * 0.80<br><br>class StudentDiscount:<br>    def apply(self, price):<br>        return price * 0.90<br><br>class ShoppingCart:<br>    def __init__(self, strategy):<br>        self.strategy = strategy<br><br>    def checkout(self, price):<br>        return self.strategy.apply(price)<br><br># Choose a strategy<br>cart = ShoppingCart(FestivalDiscount())<br>print(cart.checkout(1000))  # 800.0<br><br># Change the strategy<br>cart.strategy = StudentDiscount()<br>print(cart.checkout(1000))  # 900.0</pre><pre>Output: 800.0<br>        900.0</pre><p><strong>How It Works</strong></p><ol><li><strong>ShoppingCart</strong> receives a discount strategy.</li><li>It calls <strong>strategy.apply(price)</strong>.</li><li>The selected strategy calculates the discount.</li><li>You can switch the strategy without changing <strong>ShoppingCart</strong>.</li></ol><p><strong>When to use it:</strong> When you have multiple ways to perform the same task, such as payment methods, discounts, sorting algorithms, or route selection.</p><h3>3. Singleton Pattern — One Shared Instance</h3><p><strong>Purpose:</strong> Ensures a class has only one shared instance, with access to that instance from different parts of a program.</p><h4>Real-world example</h4><p>Imagine a logging system in your application. Instead of creating separate logger objects everywhere, you may want all parts of the application to share the same logger instance.</p><pre>class Logger:<br>    _instance = None<br><br>    def __new__(cls):<br>        if cls._instance is None:<br>            cls._instance = super().__new__(cls)<br>        return cls._instance<br><br>    def log(self, message):<br>        print(f&quot;LOG: {message}&quot;)<br><br># Creating objects<br>logger1 = Logger()<br>logger2 = Logger()<br><br>logger1.log(&quot;Application started&quot;)<br><br>print(logger1 is logger2)  # True</pre><pre>Output:<br>LOG: Application started<br>True</pre><h3>How it works</h3><ul><li><strong>__new__()</strong> controls the creation of the instance.</li><li>The first time <strong>Logger()</strong> is called, a new object is created.</li><li>Later calls return the same object.</li><li><strong>logger1 and logger2</strong> point to the same instance.</li></ul><p><strong>When to use it:</strong> When a shared instance is genuinely needed, such as certain configuration managers or coordinated resources.</p><p>Important: Singleton is often overused. It can make testing harder and introduce hidden shared state. In many Python projects, dependency injection or a module-level shared object is simpler.</p><h3>4. Observer Pattern — Notify When Something Changes</h3><p><strong>Purpose:</strong> When one object changes its state, it automatically notifies multiple other objects that are interested in that change.</p><h4>Real-world example</h4><p>Think of a YouTube channel:</p><ul><li>The channel uploads a new video.</li><li>Subscribers receive notifications.</li><li>The channel doesn’t need to notify each subscriber manually in separate hardcoded code.</li></ul><p>The channel is the <strong>Subject</strong>, and subscribers are the <strong>Observers</strong>.</p><pre>class Subscriber:<br>    def __init__(self, name):<br>        self.name = name<br><br>    def update(self, video):<br>        print(f&quot;{self.name} notified: New video - {video}&quot;)<br><br>class YouTubeChannel:<br>    def __init__(self):<br>        self.subscribers = []<br><br>    def subscribe(self, subscriber):<br>        self.subscribers.append(subscriber)<br><br>    def upload_video(self, video):<br>        print(f&quot;Uploaded: {video}&quot;)<br><br>        for subscriber in self.subscribers:<br>            subscriber.update(video)<br><br># Create channel<br>channel = YouTubeChannel()<br><br># Subscribers<br>s1 = Subscriber(&quot;Arun&quot;)<br>s2 = Subscriber(&quot;Priya&quot;)<br>s3 = Subscriber(&quot;Rahul&quot;)<br><br># Subscribe<br>channel.subscribe(s1)<br>channel.subscribe(s2)<br>channel.subscribe(s3)</pre><pre>Output:<br><br>Uploaded: Python OOP Tutorial<br>Arun notified: New video - Python OOP Tutorial<br>Priya notified: New video - Python OOP Tutorial<br>Rahul notified: New video - Python OOP Tutorial</pre><p><strong>How It Works</strong></p><ol><li>Subscribers register with the channel.</li><li>The channel uploads a new video.</li><li>The channel loops through its subscribers.</li><li>Every subscriber gets notified automatically.</li></ol><p><strong>When to use it:</strong> Notifications, event systems, stock price updates, GUI events, messaging systems, and monitoring systems.</p><h3>5. Adapter Pattern — Making Incompatible Interfaces Work Together</h3><p><strong>Purpose:</strong> Allows two incompatible classes or systems to work together by converting one interface into another that the client expects.</p><h4>Real-world example</h4><p>Suppose your application expects all payment services to have a <strong>pay()</strong> method. But an existing third-party payment system provides <strong>make_payment() </strong>instead. You don’t want to modify the third-party class. Instead, you create an <strong>Adapter</strong> to bridge the difference.</p><pre># Existing third-party payment system<br>class OldPaymentGateway:<br>    def make_payment(self, amount):<br>        print(f&quot;Processing ₹{amount} through old gateway&quot;)<br><br># Our application expects a pay() method<br>class PaymentAdapter:<br>    def __init__(self, gateway):<br>        self.gateway = gateway<br><br>    def pay(self, amount):<br>        self.gateway.make_payment(amount)<br><br># Our application<br>def checkout(payment_service, amount):<br>    payment_service.pay(amount)<br><br># Use the adapter<br>old_gateway = OldPaymentGateway()<br>adapter = PaymentAdapter(old_gateway)<br>checkout(adapter, 500)</pre><pre>Output:<br><br>Processing ₹500 through old gateway</pre><p><strong>How It Works:</strong></p><ol><li>Our application expects a <strong>pay()</strong> method.</li><li>The old gateway only provides <strong>make_payment()</strong>.</li><li><strong>PaymentAdapter</strong> receives the old gateway.</li><li>The adapter translates <strong>pay()</strong> into <strong>make_payment()</strong>.</li><li>Our application works without modifying the old gateway.</li></ol><p><strong>When to use it:</strong> Integrating legacy code, third-party APIs, incompatible libraries, or systems with different method names or formats.</p><h3><strong>Conclusion</strong></h3><p>Design patterns help us write Python code that is cleaner, more reusable, and easier to maintain. Each pattern solves a specific problem, from object creation and behavior switching to communication and integration between systems. Understanding these patterns helps us choose the right approach instead of overcomplicating our code. <strong>The goal is not to use patterns everywhere, but to use the right pattern when it makes our code simpler and more effective.</strong></p><p>Found this useful? 👏 Clap it so that more people can find it, and follow me on <a href="https://www.linkedin.com/in/nsyed9/">Linkedin</a> for more content on data engineering and AI. See you there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4050234cd40b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Using Python Data Structures Blindly: Learn Where and Why to Use]]></title>
            <link>https://medium.com/@nazeer.td/stop-using-python-data-structures-blindly-learn-where-and-why-to-use-7e0de1969ef1?source=rss-0a9bc48881dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e0de1969ef1</guid>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Nazeer Syed]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 03:31:01 GMT</pubDate>
            <atom:updated>2026-11-23T03:31:01.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AszMWb5utbazmFstMeZK9g.png" /></figure><p>Every Python tutorial explains <em>what</em> a list is. Very few explain why a senior engineer reviewing your pull request will ask you to change it into a set, a tuple, or a dict — and why that one-line change can turn a pipeline that runs for 40 minutes into one that runs in 40 seconds.</p><p>Here’s the truth: in production, choosing a data type is a design decision. It decides how fast your lookups are, whether your finance numbers reconcile, whether a shared config can be accidentally mutated by another function, and whether your JSON serializer blows up at 3 AM.</p><p>This post walks through list, tuple, set and dictionary data types, with the real-world situations where each one is the right answer — and the situations where it quietly breaks things.</p><h3>The Four Questions That Pick Your Data Type</h3><p>Before memorizing anything, learn to ask these four questions about your data. Almost every choice falls out of the answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7n2SVhxIyZM3AAGbTyBiGg.png" /></figure><p>Keep these four questions in your head as we go through each type.</p><h3>01. list — the ordered, growable workhorse</h3><p>A list is an ordered, mutable sequence, meaning you can store items in a specific order and modify them whenever needed. Appending items to the end is efficient, and accessing elements by index is fast. However, searching for an item, inserting elements at the beginning, or removing elements from the beginning can be slower, especially as the list grows.</p><p><strong>Use it for</strong></p><ul><li>Collecting records you’ll process in order (rows from an API page, files to load)</li><li>Batch buffers before a bulk insert</li><li>Anything you’ll sort, slice, or iterate positionally</li></ul><p>Here are 4 simple, realistic production use cases where Python lists are useful. These are small examples you can include directly in your blog to show where lists are used in real applications.</p><h4>1. Shopping cart items</h4><p>Store products a user adds to their cart. Items can be added or removed dynamically.</p><pre>cart = [&quot;Laptop&quot;, &quot;Mouse&quot;, &quot;Keyboard&quot;]<br>cart.append(&quot;Headphones&quot;)<br>cart.remove(&quot;Mouse&quot;)</pre><p><strong>Why a list?</strong> The cart contains multiple items and changes as the user shops.</p><h4>2. API response data</h4><p>Store a collection of records returned by an API, such as user names, orders, or products.</p><pre>users = [&quot;Ram&quot;, &quot;John&quot;, &quot;Priya&quot;, &quot;Sam&quot;]<br>for user in users:    <br>print(user)</pre><p><strong>Why a list?</strong> It makes it easy to iterate through records and process each user.</p><h4>3. Background jobs / task processing</h4><p>Maintain a collection of pending tasks that an application needs to process.</p><pre>pending_tasks = [&quot;send_email&quot;, &quot;generate_report&quot;, &quot;sync_data&quot;]<br>pending_tasks.append(&quot;backup_database&quot;)</pre><p><strong>Why a list?</strong> Tasks can be collected dynamically and processed one by one.</p><h4>4. Data validation errors</h4><p>Collect multiple validation errors while processing a form or API request, and return them together.</p><pre>errors = []<br><br>if not username:    <br>  errors.append(&quot;Username is required&quot;)<br>if not email:    <br>  errors.append(&quot;Email is required&quot;)<br><br>print(errors)</pre><p><strong>Why a list?</strong> Instead of stopping at the first error, we can collect and return all errors at once.</p><p>Lists are especially useful in production whenever you need to <strong>collect, iterate over, maintain, or process multiple items in order</strong>.</p><h4>When Not to use List</h4><blockquote>If your code does if item in big_list inside a loop, you&#39;ve written an O(n²) algorithm. In a quick test with 1 million items, a single list membership check took about <strong>5 ms</strong>; the same check on a set took about <strong>0.07 µs</strong> — tens of thousands of times faster. Over a million-row loop, that&#39;s the difference between hours and under a second.</blockquote><h3>2. tuple — a fixed record you can trust</h3><p>A tuple is an ordered, <em>immutable</em> sequence. Beginners see it as “a list you can’t change.” Professionals see it as “a record whose shape is fixed and which nobody can tamper with.” That’s a feature, not a limitation.</p><p><strong>Use it for</strong></p><ul><li><strong>Database rows</strong> — cursor.fetchall() each row has a fixed shape</li><li><strong>Composite dictionary keys</strong> — (customer_id, order_date)</li><li><strong>Returning multiple values</strong> from a function:</li><li><strong>Query parameters</strong> — cursor.execute(sql, (start_date, end_date))</li><li><strong>Constants</strong> that never change: ALLOWED_REGIONS = (&quot;APAC&quot;, &quot;EMEA&quot;, &quot;NA&quot;)</li></ul><p>Here are 4 simple, realistic production use cases where Python tuples are useful. You can include these examples directly in your blog.</p><h4>1. Database records</h4><p>Store a db record containing fixed fields such as user ID, name, and age.</p><pre>user = (101, &quot;John&quot;, 28)<br>user_id, name, age = userprint(name)</pre><p><strong>Why a tuple?</strong> It keeps related values together and prevents accidental modification of the record structure.</p><h4>2. API response coordinates</h4><p>Store latitude and longitude values for a user’s location.</p><pre>location = (13.0827, 80.2707)<br>latitude, longitude = locationprint(latitude)</pre><p><strong>Why a tuple?</strong> Coordinates represent a fixed pair of values that should stay together.</p><h4>3. Configuration settings</h4><p>Store fixed application settings such as server host and port.</p><pre>server_config = (&quot;localhost&quot;, 8000)<br>host, port = server_configprint(port)</pre><p><strong>Why a tuple?</strong> It is useful for grouping configuration values that are not expected to change during normal application execution.</p><h4>4. Returning multiple values from functions</h4><p>Return multiple related results from a function, such as minimum and maximum prices.</p><pre>def get_price_range(prices):    <br>  return min(prices), max(prices)<br><br>result = get_price_range([100, 200, 300, 400])<br>print(result)  # (100, 400)</pre><p><strong>Why a tuple?</strong> Python automatically packs multiple returned values into a tuple, making it easy to return related results together.</p><h3>03. set and frozenset — uniqueness and membership</h3><p>A set is an unordered collection of unique, hashable items, meaning it automatically removes duplicate values. It makes checking whether an item exists in a collection quick and provides useful mathematical operations such as union (|), intersection (&amp;), difference (-), and symmetric difference (^).</p><p><strong>Use it for</strong></p><ul><li><strong>Deduplication</strong> — distinct customer IDs, distinct file names</li><li><strong>“Have I seen this?” checks</strong> — idempotent loads, already-processed files</li><li><strong>Comparing two collections</strong> — schema drift, reconciliation, missing keys</li></ul><p>Here are 4 simple, realistic production use cases where Python sets are useful. You can include these examples directly in your blog.</p><h4>1. Removing duplicate email addresses</h4><p>When collecting email addresses from multiple sources, sets help remove duplicates automatically.</p><pre>emails = [&quot;a@gmail.com&quot;, &quot;b@gmail.com&quot;, &quot;a@gmail.com&quot;]<br>unique_emails = set(emails)<br>print(unique_emails)</pre><p><strong>Why a set?</strong> It automatically keeps only unique email addresses, avoiding duplicate records.</p><h4>2. Checking user permissions</h4><p>Check whether a user has the required permission to perform an action.</p><pre>user_permissions = {&quot;read&quot;, &quot;write&quot;, &quot;delete&quot;}<br>if &quot;write&quot; in user_permissions:    <br>  print(&quot;Access granted&quot;)</pre><p><strong>Why a set?</strong> It makes checking whether a particular permission exists quick and convenient.</p><h4>3. Finding common customers</h4><p>Identify customers who purchased products from two different stores.</p><pre>store_a = {&quot;Ram&quot;, &quot;John&quot;, &quot;Priya&quot;}<br>store_b = {&quot;John&quot;, &quot;Priya&quot;, &quot;Sam&quot;}<br>common_customers = store_a &amp; store_b<br>print(common_customers)</pre><p><strong>Why a set?</strong> Intersection helps identify common customers without manually comparing every item.</p><h4>4. Tracking processed transactions</h4><p>Maintain a collection of transaction IDs that have already been processed to avoid duplicate processing.</p><pre>processed_ids = {101, 102, 103}<br>transaction_id = 102<br>if transaction_id not in processed_ids:    <br>  processed_ids.add(transaction_id)    <br>  print(&quot;Transaction processed&quot;)<br>else:    <br>  print(&quot;Duplicate transaction&quot;)</pre><p><strong>Why a set?</strong> It helps quickly identify previously processed transactions and reduce duplicate operations.</p><h3>04. dict — fast lookup by key</h3><p>A dictionary (dict) stores data as key-value pairs, allowing you to quickly access, add, update, or delete values using their corresponding keys. Since Python 3.7, dictionaries also preserve insertion order, meaning items remain in the order they were added. In data engineering and production applications, dictionaries are widely used for storing JSON data, application configurations, user details, and lookup tables.</p><p>Here are 4 simple, realistic production use cases where Python dictionaries are useful. You can include these examples directly in your blog.</p><h4>1. Storing user details</h4><p>Store user information using meaningful keys such as name, email, and age.</p><pre>user = {<br>    &quot;id&quot;: 101,<br>    &quot;name&quot;: &quot;John&quot;,<br>    &quot;email&quot;: &quot;john@example.com&quot;,<br>    &quot;age&quot;: 28<br>}<br><br>print(user[&quot;email&quot;])</pre><p><strong>Why a dictionary?</strong> It keeps related user information organized and makes it easy to access individual values using keys.</p><h4>2. Application configuration</h4><p>Store application settings such as database host, port, and debug mode.</p><pre>config = {<br>    &quot;db_host&quot;: &quot;localhost&quot;,<br>    &quot;db_port&quot;: 5432,<br>    &quot;debug&quot;: True<br>}<br><br>print(config[&quot;db_host&quot;])</pre><p><strong>Why a dictionary?</strong> It keeps configuration settings in one place and makes them easy to access and update.</p><h4>3. Counting product orders</h4><p>Track how many times each product has been ordered.</p><pre>orders = [&quot;Laptop&quot;, &quot;Mouse&quot;, &quot;Laptop&quot;, &quot;Keyboard&quot;, &quot;Mouse&quot;]<br><br>order_count = {}<br><br>for item in orders:<br>    order_count[item] = order_count.get(item, 0) + 1<br><br>print(order_count)</pre><p><strong>Why a dictionary?</strong> It makes counting and tracking values easier by storing each product as a key and its count as a value.</p><h4>4. Caching API responses</h4><p>Store frequently requested API results so the application can reuse them instead of repeatedly fetching the same data.</p><pre>cache = {}<br><br>cache[&quot;user_101&quot;] = {&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 28}<br><br>user = cache.get(&quot;user_101&quot;)<br><br>print(user)</pre><p><strong>Why a dictionary?</strong> It provides a convenient way to store and retrieve previously fetched data using unique keys.</p><h3>Conclusion</h3><p>The next time you reach for a data type, don’t ask “what does this type do?” Ask the four questions: <em>Will it change? Do I look things up? Does order matter? Must it be exact?</em> The answers will point you to the right type nearly every time, and your code will be faster, safer, and easier to review.</p><p>Found this useful? 👏 Clap it so that more people can find it, and follow me on <a href="https://www.linkedin.com/in/nsyed9/">Linkedin</a> for more content on data engineering and AI. See you there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e0de1969ef1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Any File, Any Format, One Pipeline: Metadata-Driven Ingestion from S3 to Snowflake]]></title>
            <link>https://medium.com/@nazeer.td/any-file-any-format-i-dont-care-metadata-driven-ingestion-from-s3-to-snowflake-3d549b650b2a?source=rss-0a9bc48881dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d549b650b2a</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[snowflake-data-cloud]]></category>
            <category><![CDATA[metadata-driven-framework]]></category>
            <category><![CDATA[snowflake-data-ingestion]]></category>
            <dc:creator><![CDATA[Nazeer Syed]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 17:25:52 GMT</pubDate>
            <atom:updated>2026-11-22T04:38:45.332Z</atom:updated>
            <content:encoded><![CDATA[<p>CSV, JSON, Parquet, Avro and XML landing in one bucket. One config table, one stored procedure, zero copy-pasted pipelines. A complete, production-grade walkthrough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90OU5-iJln-WaQ-DVC6avQ.png" /><figcaption>Metadata driven architecture frame work</figcaption></figure><p>Every data platform starts the same way. The first source arrives, and you write a pipeline for it. Then a second source shows up, so you copy the first pipeline and change a few names. By the time you reach source number forty, you have forty slightly different pipelines, each with its own quirks, its own error handling (or lack of it), and its own on-call surprise at 3 a.m.</p><p>Metadata-driven architecture replaces pipeline-per-source development with one generic engine, where adding a new feed is as simple as inserting a row into a configuration table.</p><h3>1. What is metadata-driven architecture?</h3><p><strong>Metadata-driven architecture</strong> is a design approach where the <em>behaviour</em> of a pipeline is controlled by configuration stored as data (the metadata), rather than being hardcoded into the pipeline’s logic. The code knows <em>how</em> to load data. The metadata tells it <em>what</em> to load, <em>from where</em>, <em>into what</em>, and <em>under which rules</em>.</p><p>A useful analogy: think of a professional kitchen. You don’t hire a new chef for every dish. You hire one skilled chef and hand them recipe cards. The recipe card says which ingredients, which quantities, which cooking method. The chef is the <strong>engine</strong>; the recipe cards are the <strong>metadata</strong>. A new dish on the menu means a new card, not a new chef.</p><h3>1. The Four Building Blocks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P67bYDrK0Ek26QPZdP5ZVA.png" /></figure><h3>2. The benefits, honestly stated</h3><ol><li><strong>Speed of onboarding.</strong> New sources go live by configuration. In mature platforms this changes onboarding from a sprint item to a same-day request.</li><li><strong>Consistency by construction.</strong> Every source gets the same audit columns, the same error handling, the same logging, because there is only one code path.</li><li><strong>Lower maintenance cost.</strong> Code volume no longer grows with source count. One engine to test, review and harden.</li><li><strong>Self-documenting platform.</strong> The config table <em>is</em> the inventory. Lineage, ownership and SLAs can live right next to it.</li><li><strong>Observability for free.</strong> Since the engine logs everything uniformly, one dashboard covers every feed.</li><li><strong>Separation of concerns.</strong> Platform engineers own the engine; analysts or domain teams can own their config rows (through review).</li><li><strong>Operational control.</strong> Pause, reprioritize, regroup or change error tolerance for a source without touching code.</li></ol><h3>3. The scenario: Acme Retail’s landing bucket</h3><p>Acme Retail receives files from five upstream systems into a single S3 bucket, <strong>s3://</strong><a href="https://us-east-2.console.aws.amazon.com/s3/buckets/raw-landing-mdd-arch?region=us-east-2"><strong>raw-landing-mdd-arch</strong></a><strong>/</strong>. Every system sends a different format, and each one needs a different load behaviour:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*M8eriLIvDZjwcoIZz9nakA.png" /></figure><p>The traditional answer is five pipelines. Our answer is one engine and five rows of metadata.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sw6kKuJ-WQ8a-MaPmnjXAA.png" /><figcaption>Five formats, five load behaviours, one code path.</figcaption></figure><h4>How the engine decides what to do</h4><p>The whole framework rests on two metadata attributes. Once you understand these, the code reads naturally:</p><ul><li><strong>LOAD_STRATEGY</strong> decides <em>how columns are mapped</em>. COLUMN_MATCH uses INFER_SCHEMA to create a typed table and MATCH_BY_COLUMN_NAME to load it (CSV with headers, JSON, Parquet, Avro, ORC). VARIANT lands each record as a single semi-structured column (perfect for XML, or for any document you&#39;d rather parse in a later layer).</li><li><strong>LOAD_TYPE</strong> APPEND copies new files straight into the target.</li></ul><h3>4. End-to-end implementation</h3><p>We’ll build this in eight steps. Everything below is runnable; you only need to swap in your AWS account ID, bucket name and IAM role.</p><h4>Step 1 — Generate sample files and upload them to S3</h4><p>To make the walkthrough reproducible, here’s a small Python script that creates one file per format and uploads it. (In real life, your upstream systems do this part.)</p><p>generate_sample_files.py</p><pre><br>import boto3<br>from datetime import datetime<br>from dotenv import load_dotenv<br>import os<br>import json<br>import pandas as pd<br><br><br>load_dotenv()<br><br>today = datetime.today()<br>todays_date = today.strftime(&quot;%Y%m%d&quot;)<br>print(today)<br><br>session = boto3.Session(<br>    aws_access_key_id=os.getenv(&quot;AWS_ACCESS_KEY_ID&quot;),<br>    aws_secret_access_key=os.getenv(&quot;AWS_SECRET_ACCESS_KEY&quot;)<br>)<br><br><br>BUCKET = &quot;raw-landing-mdd-arch&quot;<br>s3 = boto3.client(&quot;s3&quot;)<br><br><br><br># 1. Orders -- CSV with header<br>orders = pd.DataFrame({<br>    &quot;order_id&quot;:     [1001, 1002, 1003],<br>    &quot;customer_id&quot;:  [&quot;C001&quot;, &quot;C002&quot;, &quot;C001&quot;],<br>    &quot;order_date&quot;:   [&quot;2026-09-30&quot;, &quot;2026-09-30&quot;, &quot;2026-09-30&quot;],<br>    &quot;order_amount&quot;: [250.75, 99.00, 1240.10],<br>    &quot;status&quot;:       [&quot;DELIVERED&quot;, &quot;SHIPPED&quot;, &quot;PLACED&quot;],<br>})<br>orders.to_csv(&quot;orders_2026_09_30.csv&quot;, index=False)<br><br># 2. Customers -- newline-delimited JSON with a nested object<br>customers = [<br>    {&quot;customer_id&quot;: &quot;C001&quot;, &quot;full_name&quot;: &quot;Asha Rao&quot;, &quot;email&quot;: &quot;asha@example.com&quot;,<br>     &quot;address&quot;: {&quot;city&quot;: &quot;Hyderabad&quot;, &quot;country&quot;: &quot;IN&quot;}, &quot;updated_at&quot;: &quot;2026-09-30T10:15:00Z&quot;},<br>    {&quot;customer_id&quot;: &quot;C002&quot;, &quot;full_name&quot;: &quot;Daniel Lee&quot;, &quot;email&quot;: &quot;dan@example.com&quot;,<br>     &quot;address&quot;: {&quot;city&quot;: &quot;Seattle&quot;, &quot;country&quot;: &quot;US&quot;}, &quot;updated_at&quot;: &quot;2026-09-30T11:02:00Z&quot;},<br>]<br><br><br>with open(&quot;customers_2026_09_30.json&quot;, &quot;w&quot;) as f:<br>    f.write(&quot;\n&quot;.join(json.dumps(c) for c in customers))<br><br><br>uploads = {<br>    &quot;orders_2026_09_30.csv&quot;:          &quot;sales/orders/&quot;,<br>    &quot;customers_2026_09_30.json&quot;:      &quot;crm/customers/&quot;,<br>    }<br>for local, prefix in uploads.items():<br>    s3.upload_file(local, BUCKET, prefix + local)<br>    print(f&quot;uploaded s3://{BUCKET}/{prefix}{local}&quot;)</pre><h4>step2: Database layout, storage integration and external stage.</h4><p>We separate concerns into one database <strong>ANALYTICS_DB</strong> and two schemas: <strong>META</strong> for the framework itself, <strong>RAW</strong> for landed data.</p><pre>USE ROLE ACCOUNTADMIN;<br><br>CREATE SCHEMA IF NOT EXISTS ANALYTICS_DB.META;<br>CREATE SCHEMA IF NOT EXISTS ANALYTICS_DB.RAW;<br><br><br>GRANT CREATE STORAGE INTEGRATION ON ACCOUNT TO ROLE DB_DEVELOPER;<br>GRANT CREATE FILE FORMAT ON SCHEMA ANALYTICS_DB.META TO ROLE DB_DEVELOPER;<br>GRANT USAGE ON INTEGRATION S3_INTEGRATION TO ROLE DB_DEVELOPER;<br><br>GRANT USAGE ON DATABASE ANALYTICS_DB TO ROLE DB_DEVELOPER;<br>GRANT USAGE ON SCHEMA ANALYTICS_DB.META TO ROLE DB_DEVELOPER;<br>GRANT USAGE ON SCHEMA ANALYTICS_DB.RAW TO ROLE DB_DEVELOPER;<br>GRANT USAGE ON STAGE ANALYTICS_DB.SALES_SCHEMA.&quot;RAW-LANDING-MDD-ARCH&quot; TO ROLE DB_DEVELOPER;</pre><h4>step3: create storage integration and stage object.</h4><pre>use role db_developer;<br><br>CREATE OR REPLACE STORAGE INTEGRATION S3_INTEGRATION<br>    TYPE = EXTERNAL_STAGE<br>    STORAGE_PROVIDER = &#39;S3&#39;<br>    ENABLED = TRUE<br>    STORAGE_AWS_ROLE_ARN =<br>        &#39;arn:aws:iam::xxxxxxxxxx:role/role-raw-landing-mdd-arch&#39;<br>    STORAGE_ALLOWED_LOCATIONS =<br>        (&#39;s3://raw-landing-mdd-arch/&#39;);<br><br><br>CREATE or replace STAGE ANALYTICS_DB.SALES_SCHEMA.&quot;RAW-LANDING-MDD-ARCH&quot;<br>    URL = &#39;s3://raw-landing-mdd-arch/&#39;<br>    STORAGE_INTEGRATION = S3_INTEGRATION;</pre><h4>step4: one file format per fomat family.</h4><pre>USE ROLE DB_DEVELOPER;<br>CREATE OR REPLACE FILE FORMAT ANALYTICS_DB.META.FF_CSV<br>  TYPE = CSV<br>  PARSE_HEADER = TRUE<br>  FIELD_OPTIONALLY_ENCLOSED_BY = &#39;&quot;&#39;<br>  TRIM_SPACE = TRUE<br>  EMPTY_FIELD_AS_NULL = TRUE<br>  NULL_IF = (&#39;&#39;, &#39;NULL&#39;, &#39;null&#39;)<br>  ERROR_ON_COLUMN_COUNT_MISMATCH = FALSE;<br><br>CREATE OR REPLACE FILE FORMAT ANALYTICS_DB.META.FF_JSON<br>  TYPE = JSON<br>  STRIP_OUTER_ARRAY = TRUE;      -- handles both NDJSON and [ {...}, {...} ]<br><br>CREATE OR REPLACE FILE FORMAT ANALYTICS_DB.META.FF_PARQUET<br>  TYPE = PARQUET<br>  USE_LOGICAL_TYPE = TRUE;<br><br>CREATE OR REPLACE FILE FORMAT ANALYTICS_DB.META.FF_AVRO<br>  TYPE = AVRO;<br><br>CREATE OR REPLACE FILE FORMAT ANALYTICS_DB.META.FF_XML<br>  TYPE = XML<br>  STRIP_OUTER_ELEMENT = TRUE;    -- each &lt;invoice&gt; becomes its own row</pre><h4>step5: — The metadata model</h4><p>This is the heart of the framework. Three tables: the configuration, a run-level log, and a file-level log.</p><pre>CREATE TABLE IF NOT EXISTS ACME_DB.META.INGESTION_CONFIG (<br>    SOURCE_ID          VARCHAR       NOT NULL PRIMARY KEY,<br>    SOURCE_SYSTEM      VARCHAR       NOT NULL,<br>    SOURCE_GROUP       VARCHAR       DEFAULT &#39;DAILY&#39;,          -- which schedule picks it up<br>    DESCRIPTION        VARCHAR,<br>    STAGE_NAME         VARCHAR       NOT NULL,                 -- fully qualified stage<br>    S3_PREFIX          VARCHAR       NOT NULL,                 -- folder inside the stage<br>    FILE_PATTERN       VARCHAR,                                -- regex on file path<br>    FILE_FORMAT        VARCHAR       NOT NULL,                 -- fully qualified file format<br>    LOAD_STRATEGY      VARCHAR       DEFAULT &#39;COLUMN_MATCH&#39;,   -- COLUMN_MATCH | VARIANT<br>    LOAD_TYPE          VARCHAR       DEFAULT &#39;APPEND&#39;,         -- APPEND <br>    TARGET_SCHEMA      VARCHAR       NOT NULL,<br>    TARGET_TABLE       VARCHAR       NOT NULL,<br>    MERGE_KEYS         VARCHAR,                                -- comma-separated, MERGE only<br>    ON_ERROR           VARCHAR       DEFAULT &#39;SKIP_FILE&#39;,      -- CONTINUE | SKIP_FILE | ABORT_STATEMENT<br>    AUTO_CREATE_TABLE  BOOLEAN       DEFAULT TRUE,<br>    PRIORITY           NUMBER        DEFAULT 100,<br>    IS_ACTIVE          BOOLEAN       DEFAULT TRUE,<br>    OWNER_EMAIL        VARCHAR,<br>    CREATED_AT         TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP(),<br>    UPDATED_AT         TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP()<br>);<br><br>CREATE TABLE IF NOT EXISTS ACME_DB.META.INGESTION_RUN_LOG (<br>    RUN_ID           VARCHAR,<br>    SOURCE_ID        VARCHAR,<br>    TARGET_TABLE     VARCHAR,<br>    LOAD_TYPE        VARCHAR,<br>    STATUS           VARCHAR,        -- RUNNING | SUCCESS | PARTIAL | NO_NEW_FILES | FAILED<br>    FILES_PROCESSED  NUMBER,<br>    ROWS_LOADED      NUMBER,<br>    ROWS_ERRORED     NUMBER,<br>    ERROR_MESSAGE    VARCHAR,<br>    STARTED_AT       TIMESTAMP_LTZ,<br>    ENDED_AT         TIMESTAMP_LTZ<br>);<br><br>CREATE TABLE IF NOT EXISTS ACME_DB.META.INGESTION_FILE_LOG (<br>    RUN_ID        VARCHAR,<br>    SOURCE_ID     VARCHAR,<br>    FILE_NAME     VARCHAR,<br>    STATUS        VARCHAR,<br>    ROWS_PARSED   NUMBER,<br>    ROWS_LOADED   NUMBER,<br>    ERRORS_SEEN   NUMBER,<br>    FIRST_ERROR   VARCHAR,<br>    LOGGED_AT     TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP()<br>);</pre><h4>step6: — Register the two sources (this is the “pipeline”)</h4><p>Here’s the part that replaces five pipelines. Each INSERT row is a complete description of a feed.</p><pre>INSERT INTO ANALYTICS_DB.META.INGESTION_CONFIG<br>  (SOURCE_ID, SOURCE_SYSTEM, SOURCE_GROUP, DESCRIPTION,<br>   STAGE_NAME, S3_PREFIX, FILE_PATTERN, FILE_FORMAT,<br>   LOAD_STRATEGY, LOAD_TYPE, TARGET_SCHEMA, TARGET_TABLE, MERGE_KEYS,<br>   ON_ERROR, PRIORITY, OWNER_EMAIL)<br>VALUES<br>  (&#39;SALES_ORDERS&#39;, &#39;SHOPIFY&#39;, &#39;DAILY&#39;, &#39;Daily order extract&#39;,<br>   &#39;ANALYTICS_DB.SALES_SCHEMA.RAW-LANDING-MDD-ARCH&#39;, &#39;sales/orders/&#39;, &#39;.*orders_.*[.]csv&#39;, &#39;ANALYTICS_DB.META.FF_CSV&#39;,<br>   &#39;COLUMN_MATCH&#39;, &#39;APPEND&#39;, &#39;RAW&#39;, &#39;ORDERS&#39;, NULL,<br>   &#39;SKIP_FILE&#39;, 10, &#39;sales-data@acme.com&#39;),<br><br>  (&#39;CRM_CUSTOMERS&#39;, &#39;SALESFORCE&#39;, &#39;DAILY&#39;, &#39;Customer master, incremental changes&#39;,<br>   &#39;ANALYTICS_DB.SALES_SCHEMA.RAW-LANDING-MDD-ARCH&#39;, &#39;crm/customers/&#39;, &#39;.*[.]json&#39;, &#39;ANALYTICS_DB.META.FF_JSON&#39;,<br>   &#39;COLUMN_MATCH&#39;, &#39;APPEND&#39;, &#39;RAW&#39;, &#39;CUSTOMERS&#39;, &#39;CUSTOMER_ID&#39;,<br>   &#39;SKIP_FILE&#39;, 20, &#39;crm-data@acme.com&#39;);</pre><h4>Step 7 — The generic ingestion engine</h4><p>The engine is a Snowpark Python stored procedure. Python is a good fit here because the logic is mostly string-building and branching, which is clearer in Python than in procedural SQL. Here’s what it does for each active source, in priority order:</p><ol><li>Make sure the target table exists. If not, create it from the files themselves using INFER_SCHEMA + USING TEMPLATE, turn on schema evolution, and add four standard audit columns.</li><li>Build the right COPY INTO statement from the metadata.</li><li>For APPEND, copy straight into the target. Even if you try to reload the same file 0 rows inserted (to override this mention FORCE=TRUE).</li><li>Log the run and every file, and keep going even if one source fails.</li></ol><p><strong>sp_run_ingestion.sql</strong></p><pre>CREATE OR REPLACE PROCEDURE ANALYTICS_DB.META.SP_RUN_INGESTION(<br>    P_SOURCE_GROUP VARCHAR DEFAULT &#39;ALL&#39;,<br>    P_SOURCE_ID    VARCHAR DEFAULT NULL<br>)<br>RETURNS VARIANT<br>LANGUAGE PYTHON<br>RUNTIME_VERSION = &#39;3.11&#39;<br>PACKAGES = (&#39;snowflake-snowpark-python&#39;)<br>HANDLER = &#39;run&#39;<br>EXECUTE AS OWNER<br>AS<br>$$<br>import uuid<br>from snowflake.snowpark.types import (<br>    StructType, StructField, StringType, LongType<br>)<br><br>DB = &quot;ANALYTICS_DB&quot;<br>META = f&quot;{DB}.META&quot;<br><br>ALLOWED_ON_ERROR = {&quot;CONTINUE&quot;, &quot;SKIP_FILE&quot;, &quot;ABORT_STATEMENT&quot;}<br>ALLOWED_STRATEGIES = {&quot;COLUMN_MATCH&quot;, &quot;VARIANT&quot;}<br><br>AUDIT_COLUMNS = [<br>    (&quot;_SOURCE_FILE&quot;,        &quot;VARCHAR&quot;,       &quot;METADATA$FILENAME&quot;),<br>    (&quot;_FILE_ROW_NUMBER&quot;,    &quot;NUMBER(38,0)&quot;,  &quot;METADATA$FILE_ROW_NUMBER&quot;),<br>    (&quot;_FILE_LAST_MODIFIED&quot;, &quot;TIMESTAMP_NTZ&quot;, &quot;METADATA$FILE_LAST_MODIFIED&quot;),<br>    (&quot;_LOADED_AT&quot;,          &quot;TIMESTAMP_LTZ&quot;, &quot;METADATA$START_SCAN_TIME&quot;),<br>]<br><br>FILE_LOG_SCHEMA = StructType([<br>    StructField(&quot;RUN_ID&quot;, StringType()),<br>    StructField(&quot;SOURCE_ID&quot;, StringType()),<br>    StructField(&quot;FILE_NAME&quot;, StringType()),<br>    StructField(&quot;STATUS&quot;, StringType()),<br>    StructField(&quot;ROWS_PARSED&quot;, LongType()),<br>    StructField(&quot;ROWS_LOADED&quot;, LongType()),<br>    StructField(&quot;ERRORS_SEEN&quot;, LongType()),<br>    StructField(&quot;FIRST_ERROR&quot;, StringType()),<br>])<br><br><br># ---------- helpers ----------<br><br>def lit(value):<br>    if value is None:<br>        return &quot;NULL&quot;<br>    return &quot;&#39;&quot; + str(value).replace(&quot;\\&quot;, &quot;\\\\&quot;).replace(&quot;&#39;&quot;, &quot;&#39;&#39;&quot;) + &quot;&#39;&quot;<br><br><br>def ident(name):<br>    return &#39;&quot;&#39; + name.replace(&#39;&quot;&#39;, &#39;&quot;&quot;&#39;) + &#39;&quot;&#39;<br><br><br>def sql(session, statement):<br>    return session.sql(statement).collect()<br><br><br>def table_exists(session, schema, table):<br>    rows = sql(session, f&quot;&quot;&quot;<br>        SELECT COUNT(*) AS N<br>        FROM {DB}.INFORMATION_SCHEMA.TABLES<br>        WHERE TABLE_SCHEMA = {lit(schema)}<br>          AND TABLE_NAME = {lit(table)}<br>    &quot;&quot;&quot;)<br>    return rows[0][&quot;N&quot;] &gt; 0<br><br><br># ---------- configuration ----------<br><br>def load_configs(session, group, source_id):<br>    where = [&quot;IS_ACTIVE = TRUE&quot;]<br><br>    if source_id:<br>        where.append(f&quot;SOURCE_ID = {lit(source_id)}&quot;)<br>    elif group and group.upper() != &quot;ALL&quot;:<br>        where.append(f&quot;SOURCE_GROUP = {lit(group.upper())}&quot;)<br><br>    rows = sql(session, f&quot;&quot;&quot;<br>        SELECT *<br>        FROM {META}.INGESTION_CONFIG<br>        WHERE {&quot; AND &quot;.join(where)}<br>        ORDER BY PRIORITY, SOURCE_ID<br>    &quot;&quot;&quot;)<br><br>    configs = []<br><br>    for row in rows:<br>        cfg = row.as_dict()<br>        cfg[&quot;LOAD_STRATEGY&quot;] = (<br>            cfg[&quot;LOAD_STRATEGY&quot;] or &quot;COLUMN_MATCH&quot;<br>        ).upper()<br>        cfg[&quot;ON_ERROR&quot;] = (<br>            cfg[&quot;ON_ERROR&quot;] or &quot;SKIP_FILE&quot;<br>        ).upper()<br><br>        configs.append(cfg)<br><br>    return configs<br><br><br>def validate(cfg):<br>    if cfg[&quot;ON_ERROR&quot;] not in ALLOWED_ON_ERROR:<br>        raise ValueError(<br>            f&quot;Unsupported ON_ERROR: {cfg[&#39;ON_ERROR&#39;]}&quot;<br>        )<br><br>    if cfg[&quot;LOAD_STRATEGY&quot;] not in ALLOWED_STRATEGIES:<br>        raise ValueError(<br>            f&quot;Unsupported LOAD_STRATEGY: {cfg[&#39;LOAD_STRATEGY&#39;]}&quot;<br>        )<br><br><br># ---------- target table ----------<br><br>def ensure_audit_columns(session, fq_table):<br>    for name, dtype, _ in AUDIT_COLUMNS:<br>        sql(<br>            session,<br>            f&quot;ALTER TABLE {fq_table} &quot;<br>            f&quot;ADD COLUMN IF NOT EXISTS {ident(name)} {dtype}&quot;<br>        )<br><br><br>def ensure_target(session, cfg):<br>    schema = cfg[&quot;TARGET_SCHEMA&quot;].upper()<br>    table = cfg[&quot;TARGET_TABLE&quot;].upper()<br><br>    fq_target = (<br>        f&quot;{DB}.{ident(schema)}.{ident(table)}&quot;<br>    )<br><br>    if not table_exists(session, schema, table):<br>        if not cfg[&quot;AUTO_CREATE_TABLE&quot;]:<br>            raise ValueError(<br>                f&quot;{fq_target} does not exist and &quot;<br>                &quot;AUTO_CREATE_TABLE is FALSE&quot;<br>            )<br><br>        if cfg[&quot;LOAD_STRATEGY&quot;] == &quot;VARIANT&quot;:<br>            sql(<br>                session,<br>                f&quot;CREATE TABLE {fq_target} (RAW VARIANT)&quot;<br>            )<br>        else:<br>            location = (<br>                f&quot;@{cfg[&#39;STAGE_NAME&#39;]}/{cfg[&#39;S3_PREFIX&#39;]}&quot;<br>            ).rstrip(&quot;/&quot;)<br><br>            sql(session, f&quot;&quot;&quot;<br>                CREATE TABLE {fq_target}<br>                USING TEMPLATE (<br>                    SELECT ARRAY_AGG(<br>                        OBJECT_CONSTRUCT(*)<br>                    )<br>                    FROM TABLE(<br>                        INFER_SCHEMA(<br>                            LOCATION =&gt; {lit(location)},<br>                            FILE_FORMAT =&gt; {lit(cfg[&#39;FILE_FORMAT&#39;])},<br>                            IGNORE_CASE =&gt; TRUE<br>                        )<br>                    )<br>                )<br>            &quot;&quot;&quot;)<br><br>    ensure_audit_columns(session, fq_target)<br>    return fq_target<br><br><br># ---------- COPY INTO RAW ----------<br><br>def build_copy(cfg, fq_target):<br>    source = (<br>        f&quot;@{cfg[&#39;STAGE_NAME&#39;]}/{cfg[&#39;S3_PREFIX&#39;]}&quot;<br>    ).rstrip(&quot;/&quot;)<br><br>    pattern = &quot;&quot;<br>    if cfg.get(&quot;FILE_PATTERN&quot;):<br>        pattern = f&quot;PATTERN = {lit(cfg[&#39;FILE_PATTERN&#39;])}&quot;<br><br>    file_format = (<br>        f&quot;FILE_FORMAT = &quot;<br>        f&quot;(FORMAT_NAME = {lit(cfg[&#39;FILE_FORMAT&#39;])})&quot;<br>    )<br><br>    if cfg[&quot;LOAD_STRATEGY&quot;] == &quot;VARIANT&quot;:<br>        audit_names = &quot;, &quot;.join(<br>            ident(name) for name, _, _ in AUDIT_COLUMNS<br>        )<br>        metadata_values = &quot;, &quot;.join(<br>            expression for _, _, expression in AUDIT_COLUMNS<br>        )<br><br>        return f&quot;&quot;&quot;<br>            COPY INTO {fq_target} (RAW, {audit_names})<br>            FROM (<br>                SELECT $1, {metadata_values}<br>                FROM {source}<br>            )<br>            {file_format}<br>            {pattern}<br>            ON_ERROR = {cfg[&#39;ON_ERROR&#39;]}<br>        &quot;&quot;&quot;<br><br>    include_metadata = &quot;, &quot;.join(<br>        f&quot;{ident(name)} = {expression}&quot;<br>        for name, _, expression in AUDIT_COLUMNS<br>    )<br><br>    return f&quot;&quot;&quot;<br>        COPY INTO {fq_target}<br>        FROM {source}<br>        {file_format}<br>        {pattern}<br>        MATCH_BY_COLUMN_NAME = CASE_INSENSITIVE<br>        INCLUDE_METADATA = ({include_metadata})<br>        ON_ERROR = {cfg[&#39;ON_ERROR&#39;]}<br>    &quot;&quot;&quot;<br><br><br>def parse_copy_result(rows):<br>    files = []<br><br>    for row in rows:<br>        result = {<br>            key.upper(): value<br>            for key, value in row.as_dict().items()<br>        }<br><br>        if &quot;FILE&quot; in result:<br>            files.append(result)<br><br>    return files<br><br><br># ---------- logging ----------<br><br>def log_start(session, run_id, cfg):<br>    target = (<br>        f&quot;{DB}.{cfg[&#39;TARGET_SCHEMA&#39;]}.{cfg[&#39;TARGET_TABLE&#39;]}&quot;<br>    )<br><br>    sql(session, f&quot;&quot;&quot;<br>        INSERT INTO {META}.INGESTION_RUN_LOG<br>            (RUN_ID, SOURCE_ID, TARGET_TABLE, LOAD_TYPE,<br>             STATUS, STARTED_AT)<br>        SELECT<br>            {lit(run_id)},<br>            {lit(cfg[&#39;SOURCE_ID&#39;])},<br>            {lit(target)},<br>            &#39;COPY&#39;,<br>            &#39;RUNNING&#39;,<br>            CURRENT_TIMESTAMP()<br>    &quot;&quot;&quot;)<br><br><br>def log_end(<br>    session, run_id, status, files,<br>    rows_loaded, rows_errored, message=None<br>):<br>    sql(session, f&quot;&quot;&quot;<br>        UPDATE {META}.INGESTION_RUN_LOG<br>        SET STATUS = {lit(status)},<br>            FILES_PROCESSED = {len(files)},<br>            ROWS_LOADED = {rows_loaded},<br>            ROWS_ERRORED = {rows_errored},<br>            ERROR_MESSAGE = {lit(message[:4000] if message else None)},<br>            ENDED_AT = CURRENT_TIMESTAMP()<br>        WHERE RUN_ID = {lit(run_id)}<br>    &quot;&quot;&quot;)<br><br><br>def log_files(session, run_id, source_id, files):<br>    if not files:<br>        return<br><br>    data = [<br>        (<br>            run_id,<br>            source_id,<br>            f.get(&quot;FILE&quot;),<br>            f.get(&quot;STATUS&quot;),<br>            f.get(&quot;ROWS_PARSED&quot;),<br>            f.get(&quot;ROWS_LOADED&quot;),<br>            f.get(&quot;ERRORS_SEEN&quot;),<br>            f.get(&quot;FIRST_ERROR&quot;),<br>        )<br>        for f in files<br>    ]<br><br>    session.create_dataframe(<br>        data, schema=FILE_LOG_SCHEMA<br>    ).write.mode(&quot;append&quot;).save_as_table(<br>        f&quot;{META}.INGESTION_FILE_LOG&quot;,<br>        column_order=&quot;name&quot;<br>    )<br><br><br># ---------- load one source ----------<br><br>def load_source(session, cfg):<br>    run_id = str(uuid.uuid4())<br>    files = []<br><br>    try:<br>        validate(cfg)<br>        log_start(session, run_id, cfg)<br><br>        fq_target = ensure_target(session, cfg)<br><br>        # All configured sources load directly into RAW.<br>        copy_sql = build_copy(cfg, fq_target)<br>        files = parse_copy_result(sql(session, copy_sql))<br><br>        log_files(session, run_id, cfg[&quot;SOURCE_ID&quot;], files)<br><br>        rows_loaded = sum(<br>            f.get(&quot;ROWS_LOADED&quot;) or 0 for f in files<br>        )<br>        rows_errored = sum(<br>            f.get(&quot;ERRORS_SEEN&quot;) or 0 for f in files<br>        )<br><br>        if not files:<br>            status = &quot;NO_NEW_FILES&quot;<br>        elif rows_errored or any(<br>            f.get(&quot;STATUS&quot;) != &quot;LOADED&quot; for f in files<br>        ):<br>            status = &quot;PARTIAL&quot;<br>        else:<br>            status = &quot;SUCCESS&quot;<br><br>        log_end(<br>            session, run_id, status,<br>            files, rows_loaded, rows_errored<br>        )<br><br>        return {<br>            &quot;source_id&quot;: cfg[&quot;SOURCE_ID&quot;],<br>            &quot;status&quot;: status,<br>            &quot;files&quot;: len(files),<br>            &quot;rows_loaded&quot;: rows_loaded,<br>        }<br><br>    except Exception as exc:<br>        # Record failures even if the run-log start failed.<br>        try:<br>            if not any(<br>                f.get(&quot;RUN_ID&quot;) == run_id for f in []<br>            ):<br>                existing = sql(session, f&quot;&quot;&quot;<br>                    SELECT COUNT(*) AS N<br>                    FROM {META}.INGESTION_RUN_LOG<br>                    WHERE RUN_ID = {lit(run_id)}<br>                &quot;&quot;&quot;)<br><br>                if existing[0][&quot;N&quot;] &gt; 0:<br>                    log_end(<br>                        session, run_id, &quot;FAILED&quot;,<br>                        files, 0, 0, str(exc)<br>                    )<br>        except Exception:<br>            pass<br><br>        return {<br>            &quot;source_id&quot;: cfg.get(&quot;SOURCE_ID&quot;),<br>            &quot;status&quot;: &quot;FAILED&quot;,<br>            &quot;error&quot;: str(exc)[:500],<br>        }<br><br><br># ---------- procedure entry point ----------<br><br>def run(session, p_source_group, p_source_id):<br>    configs = load_configs(<br>        session, p_source_group, p_source_id<br>    )<br><br>    results = [<br>        load_source(session, cfg)<br>        for cfg in configs<br>    ]<br><br>    return {<br>        &quot;sources_processed&quot;: len(results),<br>        &quot;failed&quot;: sum(<br>            1 for result in results<br>            if result[&quot;status&quot;] == &quot;FAILED&quot;<br>        ),<br>        &quot;results&quot;: results,<br>    }<br><br>$$;</pre><h4>Step 8 — Run it</h4><pre>CALL ANALYTICS_DB.META.SP_RUN_INGESTION(&#39;DAILY&#39;,&#39;SALES_ORDERS&#39;);</pre><p>On the first run, the engine creates <strong>ORDERS</strong> table (inferring their schema from the files), loads them, and returns a summary like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dtjlOhfDWN1H_sID11R6aA.png" /></figure><h4>Now try to load customers table and the results are below.</h4><pre>CALL ANALYTICS_DB.META.SP_RUN_INGESTION(&#39;DAILY&#39;,&#39;CRM_CUSTOMERS&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Tkhh-bJnVsVI5uoi7bufg.png" /></figure><p>Now verify the data in orders and customers table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_PutluKY7RMP-Hs00viwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFS1WybsSJSJwJxrAMO0oQ.png" /></figure><p>Now, lets verify ingestion run logs and file log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zuHa6kW8s3WEaFfDir7JA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E49YZz7lUXOSs00UZjJFsA.png" /></figure><h3>5. The payoff: onboarding third source in one statements</h3><p>Add the following code to generate_sample_files.py to create a sample Parquet file and upload it to your Amazon S3 bucket.</p><pre># 3. Products -- Parquet full snapshot<br>products = pd.DataFrame({<br>    &quot;product_id&quot;:   [&quot;P10&quot;, &quot;P11&quot;, &quot;P12&quot;],<br>    &quot;product_name&quot;: [&quot;Trail Shoe&quot;, &quot;Rain Jacket&quot;, &quot;Day Pack&quot;],<br>    &quot;category&quot;:     [&quot;Footwear&quot;, &quot;Apparel&quot;, &quot;Bags&quot;],<br>    &quot;unit_price&quot;:   [120.00, 89.50, 64.00],<br>    &quot;is_active&quot;:    [True, True, False],<br>})<br>products.to_parquet(&quot;products_2026_09_30.parquet&quot;, index=False)<br><br><br>uploads = {<br>    &quot;orders_2026_09_30.csv&quot;:          &quot;sales/orders/&quot;,<br>    &quot;customers_2026_09_30.json&quot;:      &quot;crm/customers/&quot;,<br>    &quot;products_2026_09_30.parquet&quot;:    &quot;catalog/products/&quot;,  --newly addedfor parque<br>    }</pre><p>A new product-management vendor starts delivering Parquet files to s3://raw-landing-mdd-arch/catalog/products/. In a hardcoded architecture, that means building another pipeline. With a metadata-driven framework, it’s simply a new source configuration and one row in the config table—no new pipeline required.</p><pre>-- if you did not create parque file format in previous steps, please run this below statement.<br>CREATE OR REPLACE FILE FORMAT ANALYTICS_DB.META.FF_PARQUET<br>  TYPE = PARQUET<br>  USE_LOGICAL_TYPE = TRUE;<br><br>INSERT INTO ANALYTICS_DB.META.INGESTION_CONFIG<br>  (SOURCE_ID, SOURCE_SYSTEM, SOURCE_GROUP, DESCRIPTION,<br>   STAGE_NAME, S3_PREFIX, FILE_PATTERN, FILE_FORMAT,<br>   LOAD_STRATEGY, LOAD_TYPE, TARGET_SCHEMA, TARGET_TABLE, MERGE_KEYS,<br>   ON_ERROR, PRIORITY, OWNER_EMAIL)<br>values<br>  (&#39;PIM_PRODUCTS&#39;, &#39;PIM&#39;, &#39;DAILY&#39;, &#39;Full product catalogue snapshot&#39;,<br>   &#39;ANALYTICS_DB.SALES_SCHEMA.RAW-LANDING-MDD-ARCH&#39;, &#39;catalog/products/&#39;, &#39;.*[.]parquet&#39;, &#39;ANALYTICS_DB.META.FF_PARQUET&#39;,<br>   &#39;COLUMN_MATCH&#39;, &#39;APPEND&#39;, &#39;RAW&#39;, &#39;PRODUCTS&#39;, NULL,<br>   &#39;SKIP_FILE&#39;, 30, &#39;catalog-data@acme.com&#39;);</pre><pre> CALL ANALYTICS_DB.META.SP_RUN_INGESTION(&#39;DAILY&#39;,&#39;PIM_PRODUCTS&#39;);</pre><p>That’s it! Execute the aboveCALL statement to load the file into RAW.PRODUCTS. As the output shows, the framework automatically generates the required DDL and loads the data with just one configuration insert and one procedure call—no new pipeline code required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHkQ71j2OcaQvQkKhv50Vw.png" /></figure><h3>Wrapping up</h3><p>Metadata-driven architecture isn’t a tool or a product. It’s a decision to stop encoding <em>what</em> you load in code and start describing it as data. In this example, two formats collapsed into one stored procedure and one config table, and a third source took one insert statements to onboard.</p><p>The real win shows up at source number fifty: the platform is still one engine, one log, one dashboard, and the answer to “what do we ingest and how?” is a single <strong>SELECT</strong>.</p><p>Found this useful? 👏 Clap it so that more people can find it, and follow me on <a href="https://www.linkedin.com/in/nsyed9/">Linkedin</a> for more content on data engineering and AI. See you there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d549b650b2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Vault vs. Dimensional Modeling: Stop Asking Which One Is Better]]></title>
            <link>https://medium.com/@nazeer.td/data-vault-vs-dimensional-modeling-stop-asking-which-one-is-better-0de590135e13?source=rss-0a9bc48881dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/0de590135e13</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[data-vault]]></category>
            <dc:creator><![CDATA[Nazeer Syed]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 11:26:57 GMT</pubDate>
            <atom:updated>2026-10-07T11:26:57.792Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pdSPUx-XsjQy4afL4IWtZA.png" /></figure><p>Every data team eventually has this debate. Someone says <em>“we should do Data Vault, it’s more scalable.”</em> Someone else says <em>“just build a star schema, the business needs dashboards.”</em> Both are right — for different problems.</p><p>In this post, I’ll skip the textbook-only approach and walk through <strong>two practical use cases</strong>:</p><ol><li>A <strong>bank going through an acquisition</strong>, where Data Vault is clearly the right choice — and a star schema would hurt.</li><li>An <strong>online retailer’s sales analytics</strong>, where a dimensional model is clearly the right choice — and Data Vault would be overkill.</li></ol><p>All SQL examples are written for Snowflake, but the ideas apply to any warehouse.</p><h3>A 5-Minute Refresher</h3><h3>Dimensional Modeling (Kimball)</h3><p>Dimensional modeling organizes data around <strong>business processes</strong> for <strong>easy querying</strong>. You get two kinds of tables:</p><ul><li><strong>Fact tables</strong> — the measurable events: sales, clicks, payments. Mostly numbers and foreign keys.</li><li><strong>Dimension tables</strong> — the context: who, what, where, when. Customer, product, store, date.</li></ul><p>Arrange them with the fact in the middle and dimensions around it, and you get the famous <strong>star schema</strong>. It is designed for one audience: the people who <em>read</em> the data.</p><h3>Data Vault 2.0 (Dan Linstedt)</h3><p>Data Vault organizes data around <strong>business keys</strong> and <strong>how they change over time</strong>, for <strong>easy loading and full auditability</strong>. It has three building blocks:</p><ul><li><strong>Hubs</strong> — one row per unique business key (e.g. customer number). Nothing else. They never change.</li><li><strong>Links</strong> — relationships between business keys (customer ↔ account). Also insert-only.</li><li><strong>Satellites</strong> — the descriptive attributes and their full history (name, address, risk rating), usually <em>one satellite per source system</em>.</li></ul><p>Data Vault is designed for a different audience: the people who <em>load, integrate and govern</em> the data.</p><blockquote><strong>The one-line difference: Dimensional models are optimized for <em>reading</em>. Data Vault is optimized for <em>writing, integrating and auditing</em>. Most good architectures eventually use both — but which one sits at the centre depends on your problem.</strong></blockquote><h3>Use Case 1: Data Vault Wins — A Bank After an Acquisition</h3><h3>The situation</h3><p>Imagine <strong>Northstar Bank</strong>, a mid-size retail bank. Last year it acquired a smaller regional bank. Now it has customer data coming from several systems that were never designed to talk to each other:</p><ul><li><strong>Core banking system (Northstar)</strong> — savings and current accounts, customer ID like <strong>NS-100245</strong></li><li><strong>Core banking system (acquired bank)</strong> — different vendor, customer ID like <strong>RB0098812</strong></li><li><strong>Credit card platform</strong> — a third-party processor with its own customer reference</li><li><strong>CRM / KYC system</strong> — addresses, phone numbers, risk ratings, KYC verification status</li></ul><p>The requirements from the business and regulators look like this:</p><ul><li><strong>Regulators and auditors</strong> must be able to ask: <em>“What did you know about this customer’s risk rating on 15 March, and which system told you?”</em> — and get an exact answer.</li><li><strong>Systems keep changing.</strong> The acquired bank’s core system will be migrated onto Northstar’s platform over the next 18 months. A new loan origination system is also arriving next quarter.</li><li><strong>The same customer exists in multiple systems</strong> with different IDs, and the matching rules are still being agreed upon.</li><li><strong>Nothing can be overwritten.</strong> Every version of every record must be kept with when it arrived and where it came from.</li></ul><p>This is the classic environment where Data Vault shines. Banks and insurers are among the most common adopters of Data Vault for exactly these reasons.</p><h3>The model</h3><pre>  ┌───────────────────────────┐<br>                 │   SAT_CUSTOMER_NORTHSTAR  │  (name, DOB, address…<br>                 └─────────────┬─────────────┘   from Northstar core)<br>┌──────────────────────────┐   │<br>│  SAT_CUSTOMER_ACQUIRED   │───┤<br>└──────────────────────────┘   │<br>┌──────────────────────────┐ ┌─▼────────────┐      ┌─────────────────────┐      ┌─────────────┐<br>│  SAT_CUSTOMER_KYC        │─▶ HUB_CUSTOMER ◀──────│ LINK_CUSTOMER_ACCOUNT│──────▶ HUB_ACCOUNT │<br>└──────────────────────────┘ └──────────────┘      └─────────────────────┘      └──────┬──────┘<br>                                                                                       │<br>                                                                       ┌───────────────▼────┐<br>                                                                       │ SAT_ACCOUNT_BALANCE│<br>                                                                       └────────────────────┘</pre><h3>Hub: one row per customer business key</h3><pre>CREATE TABLE raw_vault.hub_customer (<br>    hk_customer      BINARY(16)    NOT NULL,  -- MD5 hash of the business key<br>    customer_bk      VARCHAR(50)   NOT NULL,  -- business key from the source<br>    load_dts         TIMESTAMP_NTZ NOT NULL,  -- when we first saw it<br>    record_source    VARCHAR(50)   NOT NULL,  -- which system it came from<br>    CONSTRAINT pk_hub_customer PRIMARY KEY (hk_customer)<br>);<br><br>-- Insert only NEW business keys. Existing keys are never touched.<br>INSERT INTO raw_vault.hub_customer<br>SELECT DISTINCT<br>    MD5_BINARY(UPPER(TRIM(stg.customer_id))),<br>    UPPER(TRIM(stg.customer_id)),<br>    CURRENT_TIMESTAMP(),<br>    &#39;NORTHSTAR_CORE&#39;<br>FROM staging.northstar_customers stg<br>WHERE NOT EXISTS (<br>    SELECT 1 FROM raw_vault.hub_customer h<br>    WHERE h.hk_customer = MD5_BINARY(UPPER(TRIM(stg.customer_id)))<br>);</pre><h3>Satellite: full history, one per source</h3><pre>CREATE TABLE raw_vault.sat_customer_kyc (<br>    hk_customer      BINARY(16)    NOT NULL,<br>    load_dts         TIMESTAMP_NTZ NOT NULL,<br>    hash_diff        BINARY(16)    NOT NULL,  -- hash of all attributes, to detect change<br>    risk_rating      VARCHAR(10),<br>    kyc_status       VARCHAR(20),<br>    address_line     VARCHAR(200),<br>    city             VARCHAR(100),<br>    record_source    VARCHAR(50)   NOT NULL,<br>    CONSTRAINT pk_sat_customer_kyc PRIMARY KEY (hk_customer, load_dts)<br>);<br><br>-- Insert a new row ONLY when something actually changed<br>INSERT INTO raw_vault.sat_customer_kyc<br>SELECT<br>    MD5_BINARY(UPPER(TRIM(stg.customer_id))),<br>    CURRENT_TIMESTAMP(),<br>    MD5_BINARY(CONCAT_WS(&#39;||&#39;,<br>        COALESCE(stg.risk_rating, &#39;&#39;), COALESCE(stg.kyc_status, &#39;&#39;),<br>        COALESCE(stg.address_line, &#39;&#39;), COALESCE(stg.city, &#39;&#39;))),<br>    stg.risk_rating, stg.kyc_status, stg.address_line, stg.city,<br>    &#39;CRM_KYC&#39;<br>FROM staging.crm_kyc stg<br>LEFT JOIN (<br>    SELECT hk_customer, hash_diff<br>    FROM raw_vault.sat_customer_kyc<br>    QUALIFY ROW_NUMBER() OVER (PARTITION BY hk_customer ORDER BY load_dts DESC) = 1<br>) cur<br>  ON cur.hk_customer = MD5_BINARY(UPPER(TRIM(stg.customer_id)))<br>WHERE cur.hk_customer IS NULL<br>   OR cur.hash_diff &lt;&gt; MD5_BINARY(CONCAT_WS(&#39;||&#39;,<br>        COALESCE(stg.risk_rating, &#39;&#39;), COALESCE(stg.kyc_status, &#39;&#39;),<br>        COALESCE(stg.address_line, &#39;&#39;), COALESCE(stg.city, &#39;&#39;)));</pre><h3>Link: the relationship between customer and account</h3><pre>CREATE TABLE raw_vault.link_customer_account (<br>    hk_customer_account BINARY(16)    NOT NULL,  -- hash of both business keys<br>    hk_customer         BINARY(16)    NOT NULL,<br>    hk_account          BINARY(16)    NOT NULL,<br>    load_dts            TIMESTAMP_NTZ NOT NULL,<br>    record_source       VARCHAR(50)   NOT NULL,<br>    CONSTRAINT pk_link_cust_acct PRIMARY KEY (hk_customer_account)<br>);</pre><h3>Answering the auditor’s question</h3><p>Now the regulator asks: <em>“What was customer NS-100245’s risk rating on 15 March 2026, and where did it come from?”</em></p><pre>SELECT<br>    h.customer_bk,<br>    s.risk_rating,<br>    s.kyc_status,<br>    s.record_source,<br>    s.load_dts AS valid_from<br>FROM raw_vault.hub_customer h<br>JOIN raw_vault.sat_customer_kyc s<br>  ON s.hk_customer = h.hk_customer<br>WHERE h.customer_bk = &#39;NS-100245&#39;<br>  AND s.load_dts &lt;= &#39;2026-03-15 23:59:59&#39;<br>QUALIFY ROW_NUMBER() OVER (ORDER BY s.load_dts DESC) = 1;</pre><p>Because satellites are <strong>insert-only</strong> and every row carries load_dts and record_source, this answer is exact and defensible. Nothing was ever overwritten.</p><h3>Why we chose Data Vault here</h3><h3>Why we chose Data Vault here</h3><p><strong>1. New source systems are additive, not disruptive </strong>When the new loan origination system arrives, we add <strong>HUB_LOAN</strong>, <strong>LINK_CUSTOMER_LOAN</strong> and <strong>SAT_LOAN_ORIGINATION</strong>. The existing hubs, links and satellites are <em>not modified</em>. No existing pipeline is broken, no regression test of the whole warehouse is needed.</p><p><strong>2. Full, built-in audit trail </strong>Every row records when it was loaded and from which system. Point-in-time questions (“what did we know on date X?”) are a standard pattern, not an emergency project. This is what regulators expect from a bank.</p><p><strong>3. Integration without forcing early decisions </strong>The business hasn’t finalised how to match <strong>NS-100245</strong> to <strong>RB0098812</strong>. In Data Vault, both keys simply land in <strong>HUB_CUSTOMER</strong>, and a <strong>Same-As Link</strong> can record the match later — when the rules are agreed. Raw data is loaded today; business rules are applied downstream and can change without reloading history.</p><p><strong>4. Parallel, simple loading</strong>Hubs, links and satellites follow the same small set of load patterns and can load in parallel. That makes the pipelines easy to generate with tools such as dbt packages (for example <strong>AutomateDV</strong> or <strong>datavault4dbt</strong>) instead of hand-coding hundreds of loads.</p><p><strong>5. Source migration doesn’t destroy history</strong>When the acquired bank’s system is switched off, its satellite simply stops receiving rows. Its history stays queryable forever, side by side with the new source.</p><h3>What users actually get</h3><ul><li><strong>Compliance and risk teams</strong> get traceable, point-in-time answers they can hand to auditors.</li><li><strong>Data engineers</strong> onboard new systems in days, not months, without touching existing loads.</li><li><strong>Analysts</strong> still get friendly star schemas — built <em>on top of</em> the vault as information marts (more on this at the end).</li></ul><h3>Why a dimensional model would be a bad choice as the core here</h3><p><strong>1. Every new source means remodelling conformed dimensions </strong>A single <strong>DIM_CUSTOMER</strong> must merge Northstar, acquired bank, card and KYC attributes into <em>one</em> row per customer. Add the loan system and you change the dimension’s structure, its load logic and possibly every fact table that references it. With an 18-month migration in progress, that table would be redesigned again and again.</p><p><strong>2. Business rules are baked in at load time </strong>To load one <strong>DIM_CUSTOMER</strong>, you must decide <em>today</em> which source wins when the acquired bank and the KYC system disagree on an address. If that rule changes next quarter, the history built with the old rule is already wrong — and the raw source values may no longer be anywhere in the warehouse.</p><p><strong>3. Auditability is weaker </strong>SCD Type 2 keeps history of the <em>merged, cleaned</em> record, not of what each source system actually sent. When an auditor asks “which system said this customer was low-risk?”, a conformed dimension usually can’t answer.</p><p><strong>4. SCD Type 1 fields destroy history outright </strong>Many dimensions overwrite some attributes (Type 1) to keep things simple. In a regulated bank, overwriting a risk rating is not a simplification — it’s a compliance gap.</p><h3>Use Case 2: Dimensional Wins — An Online Retailer’s Sales Analytics</h3><h3>The situation</h3><p>Now picture <strong>UrbanCart</strong>, an online store selling home and kitchen products. It runs on a single e-commerce platform (think Shopify or a similar system). The marketing and merchandising teams want:</p><ul><li>A <strong>Power BI / Tableau dashboard</strong> showing daily revenue, units sold and margin.</li><li>Slicing by <strong>product category, brand, region, sales channel and promotion</strong>.</li><li>Comparisons like <em>“this month vs same month last year”</em> and <em>“Diwali sale vs normal week.”</em></li><li>Self-service: business users dragging fields onto a report <strong>without writing SQL</strong>.</li></ul><p>There’s <strong>one main source system</strong>, no regulatory audit requirement on the analytics layer, and the questions are well understood. This is the textbook home of the star schema — the pattern behind most retail and e-commerce BI dashboards.</p><h3>The model</h3><pre>                ┌──────────────┐<br>                │   DIM_DATE   │<br>                └──────┬───────┘<br>┌──────────────┐ ┌─────▼──────────┐ ┌──────────────┐<br>│ DIM_PRODUCT  │─▶   FACT_SALES   ◀─│ DIM_CUSTOMER │<br>└──────────────┘ └─────▲──────────┘ └──────────────┘<br>                ┌──────┴───────┐<br>                │ DIM_CHANNEL  │<br>                └──────────────┘</pre><h3>The fact table</h3><pre>CREATE TABLE mart.fact_sales (<br>    date_key        NUMBER(8)     NOT NULL,   -- e.g. 20261007<br>    product_key     NUMBER        NOT NULL,<br>    customer_key    NUMBER        NOT NULL,<br>    channel_key     NUMBER        NOT NULL,<br>    order_id        VARCHAR(30)   NOT NULL,   -- degenerate dimension<br>    quantity        NUMBER(10,0),<br>    gross_amount    NUMBER(12,2),<br>    discount_amount NUMBER(12,2),<br>    net_amount      NUMBER(12,2),<br>    cost_amount     NUMBER(12,2)<br>);<br>-- Grain: one row per order line.</pre><h3>A dimension table</h3><pre>CREATE TABLE mart.dim_product (<br>    product_key     NUMBER AUTOINCREMENT PRIMARY KEY,<br>    product_sku     VARCHAR(30),<br>    product_name    VARCHAR(200),<br>    brand           VARCHAR(100),<br>    category        VARCHAR(100),<br>    sub_category    VARCHAR(100),<br>    unit_price      NUMBER(10,2)<br>);</pre><h3>The question the business actually asks</h3><p><em>“Show me net revenue and margin by category, per month, for the online channel in 2026.”</em></p><pre>SELECT<br>    d.year_month,<br>    p.category,<br>    SUM(f.net_amount)                   AS net_revenue,<br>    SUM(f.net_amount - f.cost_amount)   AS margin<br>FROM mart.fact_sales f<br>JOIN mart.dim_date    d ON f.date_key    = d.date_key<br>JOIN mart.dim_product p ON f.product_key = p.product_key<br>JOIN mart.dim_channel c ON f.channel_key = c.channel_key<br>WHERE d.year = 2026<br>  AND c.channel_name = &#39;Online&#39;<br>GROUP BY d.year_month, p.category<br>ORDER BY d.year_month, p.category;</pre><p>Three simple joins. Every one is a fact-to-dimension join on an integer key. A business analyst can read this query — and a BI tool can generate it automatically.</p><h3>Why we chose a dimensional model here</h3><p><strong>1. It matches how people think</strong>Merchandisers think in “sales by category by month”. The star schema is literally that sentence turned into tables. Field names in the BI tool make sense to non-engineers.</p><p><strong>2. Fast queries, few joins</strong>One fact table and a handful of small dimensions. Snowflake prunes the fact table by date, joins tiny dimension tables, and returns results quickly — exactly what an interactive dashboard needs.</p><p><strong>3. BI tools are built for it</strong>Power BI, Tableau and Looker all model data as facts and dimensions. A star schema drops straight into a semantic model with clean relationships, so self-service works without a data engineer in the loop.</p><p><strong>4. Small, simple, quick to deliver</strong>Five tables, one source, a clear grain. A small team can build, test and ship it in weeks and maintain it easily.</p><h3>Why Data Vault would be a bad choice here</h3><p>Let’s be concrete. In Data Vault, the same data would become something like:</p><ul><li>HUB_PRODUCT, HUB_CUSTOMER, HUB_ORDER, HUB_CHANNEL</li><li>LINK_ORDER_LINE (order ↔ product ↔ customer ↔ channel)</li><li>SAT_PRODUCT_DETAILS, SAT_CUSTOMER_DETAILS, SAT_ORDER_HEADER, SAT_ORDER_LINE_AMOUNTS, SAT_CHANNEL_DETAILS</li></ul><p>That’s around <strong>10 tables instead of 5</strong>. And the same revenue-by-category question becomes:</p><pre>SELECT<br>    TO_CHAR(soh.order_date, &#39;YYYY-MM&#39;)                   AS year_month,<br>    sp.category,<br>    SUM(sla.net_amount)                                  AS net_revenue,<br>    SUM(sla.net_amount - sla.cost_amount)                AS margin<br>FROM raw_vault.link_order_line l<br>JOIN raw_vault.hub_order   ho ON l.hk_order   = ho.hk_order<br>JOIN raw_vault.hub_product hp ON l.hk_product = hp.hk_product<br>JOIN raw_vault.hub_channel hc ON l.hk_channel = hc.hk_channel<br>JOIN (SELECT * FROM raw_vault.sat_order_line_amounts<br>      QUALIFY ROW_NUMBER() OVER (PARTITION BY hk_order_line ORDER BY load_dts DESC) = 1) sla<br>  ON sla.hk_order_line = l.hk_order_line<br>JOIN (SELECT * FROM raw_vault.sat_order_header<br>      QUALIFY ROW_NUMBER() OVER (PARTITION BY hk_order ORDER BY load_dts DESC) = 1) soh<br>  ON soh.hk_order = ho.hk_order<br>JOIN (SELECT * FROM raw_vault.sat_product_details<br>      QUALIFY ROW_NUMBER() OVER (PARTITION BY hk_product ORDER BY load_dts DESC) = 1) sp<br>  ON sp.hk_product = hp.hk_product<br>JOIN (SELECT * FROM raw_vault.sat_channel_details<br>      QUALIFY ROW_NUMBER() OVER (PARTITION BY hk_channel ORDER BY load_dts DESC) = 1) sc<br>  ON sc.hk_channel = hc.hk_channel<br>WHERE YEAR(soh.order_date) = 2026<br>  AND sc.channel_name = &#39;Online&#39;<br>GROUP BY 1, 2;</pre><p><strong>1. Join explosion and slower dashboards</strong>Seven joins plus “latest row” logic on every satellite — and that’s for a simple question. Every dashboard tile pays this cost. Business users cannot write this, and BI tools struggle to model it.</p><p><strong>2. You’d build the star schema anyway</strong>Because nobody can report directly from a raw vault, you’d still need to build <strong>FACT_SALES</strong> and the dimensions on top. With only one source system and no audit requirement, the vault layer becomes an extra hop that adds cost and latency but no real value.</p><p><strong>3. Its strengths aren’t needed</strong>Data Vault pays off when there are many changing sources, conflicting business keys and strict audit needs. UrbanCart has one source, stable keys and a dashboard to ship. You’d be paying the price of flexibility you will never use.</p><p><strong>4. More people, more skills, more time</strong>Data Vault needs hash-key standards, automation tooling and engineers who know the methodology. For a small analytics team, that overhead can delay the first useful dashboard by months.</p><h3>Side-by-Side Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6PxGvlTvYFOmqsR8rAZwhg.png" /></figure><h3>The Real Answer: Usually Both</h3><p>Here’s the part many debates miss: <strong>Data Vault and dimensional modeling are not rivals — they’re layers.</strong></p><p>At Northstar Bank, the raw vault is the integration and audit layer. But the branch performance dashboard still runs on a star schema — <strong>FACT_TRANSACTIONS, DIM_CUSTOMER, DIM_BRANCH</strong> — built <em>from</em> the vault as an information mart. Business users never query hubs and satellites directly.</p><pre>Sources ──▶ Staging ──▶ Raw Vault ──▶ Business Vault ──▶ Star Schemas ──▶ BI / ML<br>                        (hubs, links,   (business rules,   (facts and<br>                         satellites)     PIT/bridge tables)  dimensions)</pre><p>At UrbanCart, there’s no vault at all — and that’s fine. If UrbanCart later acquires two other stores with different platforms and needs a combined, auditable customer history, <em>that</em> is the moment to introduce a vault underneath the existing marts.</p><blockquote><strong>A simple rule of thumb</strong></blockquote><blockquote><strong>Ask two questions: <em>“How many sources will change underneath us?”</em> and <em>“Will someone need to prove what we knew, and when?”</em> If both answers are “a lot” and “yes”, put Data Vault at the core. If both are “few” and “no”, go straight to a star schema. Either way, your business users should end up looking at facts and dimensions.</strong></blockquote><p>Found this useful? 👏 Clap it so that more people can find it, and follow me on <a href="https://www.linkedin.com/in/nsyed9/">Linkedin</a> for more content on data engineering and AI. See you there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0de590135e13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake Table Functions: What You’re Missing in Oracle, Teradata and Other RDBMS]]></title>
            <link>https://medium.com/@nazeer.td/snowflake-table-functions-what-youre-missing-in-oracle-teradata-and-other-rdbms-2f905c86730b?source=rss-0a9bc48881dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f905c86730b</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[udf]]></category>
            <category><![CDATA[snowflake-data-cloud]]></category>
            <dc:creator><![CDATA[Nazeer Syed]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 12:04:38 GMT</pubDate>
            <atom:updated>2026-09-30T15:24:57.983Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why developers coming from Oracle or Teradata are constantly surprised by Snowflake’s TABLE() functions—and how they fundamentally change modern data pipelines.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKxdYjk7grJqjuipvlJzCw.jpeg" /></figure><p>If you came to Snowflake from Oracle or Teradata, you’ve probably had this moment: you open someone’s query and the FROM clause doesn&#39;t contain a table. It contains a <em>function call</em>.</p><pre>SELECT * FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));<br>SELECT * FROM TABLE(INFORMATION_SCHEMA.COPY_HISTORY(...));<br>SELECT f.value FROM orders o, LATERAL FLATTEN(input =&gt; o.payload:items) f;</pre><p>A regular (scalar) function takes values and returns <strong>one value per row</strong>. An aggregate function takes many rows and returns <strong>one value per group</strong>. A table function is the third shape: <strong>Table Function</strong> returns an entire tabular dataset — composed of zero, one, or multiple rows, each with one or more columns. In Snowflake, table functions can be invoked directly in the FROM clause of a query.</p><ul><li><strong>System table functions</strong> — built in: <strong>FLATTEN</strong>, <strong>SPLIT_TO_TABLE</strong>, <strong>GENERATOR</strong>, <strong>RESULT_SCAN</strong>, <strong>INFER_SCHEMA</strong>, <strong>VALIDATE</strong>, and the whole <strong>INFORMATION_SCHEMA </strong>family (<strong>QUERY_HISTORY</strong>, <strong>COPY_HISTORY</strong>, <strong>TASK_HISTORY</strong>, <strong>WAREHOUSE_METERING_HISTORY</strong>, …).</li><li><strong>User-defined table functions (UDTFs)</strong> — ones you write, in SQL, Python, Java, Scala or JavaScript.</li></ul><h3>“But Oracle and Teradata don’t have this…” — they do, sort of</h3><p>Let’s be precise, because this is a common misconception. Table functions are not unique to Snowflake:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eIxko7z_cdCXYXidFgnLLw.png" /></figure><blockquote><strong>Key idea If the answer to a question is a set of rows that depends on parameters (a time window, a file location, a query ID, a JSON path), Snowflake tends to give you a table function rather than a view or a utility.</strong></blockquote><h3>Why table functions are so useful</h3><ol><li><strong>Parameterised relations.</strong> A view can’t take arguments; a table function can. <strong>COPY_HISTORY(TABLE_NAME =&gt; ‘ORDERS’, START_TIME =&gt; …)</strong> is a &quot;view with parameters&quot;.</li><li><strong>Row multiplication with LATERAL.</strong> One input row can produce many output rows — the key to exploding arrays, date ranges and delimited strings without procedural loops.</li><li><strong>Everything stays in SQL.</strong> Output is a relation, so you can <strong>JOIN, WHERE, GROUP BY, CREATE TABLE AS</strong> it. No exporting, no parsing text output.</li><li><strong>Real-time metadata.</strong> <strong>INFORMATION_SCHEMA</strong> table functions have no ingestion latency, unlike <strong>SNOWFLAKE.ACCOUNT_USAGE</strong> views (which can lag by up to a few hours).</li><li><strong>Parallel, stateful processing.</strong> Partitioned UDTFs let you run custom logic per group (per user, per device) in parallel across the warehouse — something scalar UDFs cannot do.</li></ol><p><strong>1. Unnesting Semi-Structured JSON Data (The FLATTEN Function)</strong><br>Snowflake allows storing raw JSON directly inside a <strong>VARIANT</strong> column. To transform array elements into relational rows, Snowflake uses the built-in <strong>FLATTEN()</strong> table function.</p><pre>-- Expanding a JSON array of customer orders into individual relational rows<br>SELECT <br>    raw_payload:customer_id::STRING AS customer_id,<br>    f.value:item_id::STRING AS item_id,<br>    f.value:price::NUMBER(10,2) AS item_price<br>FROM raw_orders_table,<br>TABLE(FLATTEN(input =&gt; raw_payload:order_items)) f;</pre><p><strong>2. Querying Cloud Storage Files Directly (The RESULT_SCAN &amp; INFER_SCHEMA Functions)</strong><br>Instead of loading files blindly into staging tables, Snowflake provides table functions that read stage metadata or previous operational results on the fly.</p><pre>-- Automatically inspect schema of Parquet files sitting on S3 stage<br>SELECT * <br>FROM TABLE(<br>    INFER_SCHEMA(<br>        LOCATION =&gt; &#39;@my_s3_stage/monthly_sales/&#39;,<br>        FILE_FORMAT =&gt; &#39;my_parquet_format&#39;<br>    )<br>);</pre><p><strong>3. Auditing Operational Metadata (Information Schema Table Functions)</strong><br>Snowflake exposes system metrics through table functions, allowing data engineers to audit warehouse usage, credit consumption, and query history directly with standard SQL.</p><pre>-- Fetching long-running queries executed in the past 12 hours<br>SELECT query_id, user_name, execution_time/1000 AS seconds<br>FROM TABLE(INFORMATION_SCHEMA.QUERY_HISTORY(<br>    date_range_start =&gt; DATEADD(&#39;hour&#39;, -12, CURRENT_TIMESTAMP())<br>))<br>WHERE execution_status = &#39;SUCCESS&#39;<br>ORDER BY execution_time DESC;</pre><p>4.<strong>Splitting delimited strings with SPLIT_TO_TABLE</strong></p><p>Legacy sources love comma-separated lists in a single column. Teradata users will recognise this as the cousin of <strong>STROKE_SPLIT_TO_TABLE</strong>:</p><pre>-- products.tags = &#39;organic,vegan,gluten-free&#39;<br>SELECT p.product_id,<br>       s.index                AS tag_position,<br>       TRIM(s.value)          AS tag<br>FROM products p,<br>     LATERAL SPLIT_TO_TABLE(p.tags, &#39;,&#39;) s;</pre><p>This is how you normalise a multi-valued attribute into a proper bridge table for a dimensional model — no stored procedure, no loop.</p><p><strong>5.Generating rows from nothing with GENERATOR</strong></p><p><strong>GENERATOR</strong> produces an arbitrary number of empty rows. Combine it with sequence and random functions and you get date spines, test data and number tables.</p><h4>A date dimension in one statement</h4><pre>CREATE OR REPLACE TABLE gold.dim_date AS<br>WITH spine AS (<br>    SELECT DATEADD(day,<br>               ROW_NUMBER() OVER (ORDER BY SEQ4()) - 1,<br>               &#39;2020-01-01&#39;::DATE) AS cal_date<br>    FROM TABLE(GENERATOR(ROWCOUNT =&gt; 4018))   -- 2020-01-01 .. 2030-12-31<br>)<br>SELECT TO_NUMBER(TO_CHAR(cal_date, &#39;YYYYMMDD&#39;)) AS date_key,<br>       cal_date,<br>       YEAR(cal_date)        AS year,<br>       QUARTER(cal_date)     AS quarter,<br>       MONTH(cal_date)       AS month,<br>       MONTHNAME(cal_date)   AS month_name,<br>       DAYNAME(cal_date)     AS day_name,<br>       DAYOFWEEKISO(cal_date) IN (6, 7) AS is_weekend<br>FROM spine;</pre><p><strong>Gotcha SEQ4()</strong> is <em>not</em> guaranteed to be gap-free — it&#39;s fast and unique, but Snowflake may skip values when generating in parallel. For anything where gaps matter (dates, surrogate keys in test data), wrap it with <strong>ROW_NUMBER() OVER(ORDER BY SEQ4())</strong> as above. Also note <strong>ROWCOUNT</strong> must be a constant, not a column or variable expression.</p><p><strong>6. table functions in a Cortex RAG pipeline</strong></p><p>Table functions compose with everything. Chunking documents for retrieval is just a scalar function returning an array, flattened into rows:</p><pre>INSERT INTO rag.doc_chunks (doc_id, chunk_no, chunk_text)<br>SELECT d.doc_id, c.index, c.value::STRING<br>FROM rag.documents d,<br>     LATERAL FLATTEN(<br>        input =&gt; SNOWFLAKE.CORTEX.SPLIT_TEXT_RECURSIVE_CHARACTER(<br>                    d.content, &#39;markdown&#39;, 1500, 200)) c;</pre><p>Array in, rows out — the same <strong>FLATTEN</strong> you used on order JSON is doing the chunk fan-out for your AI pipeline.</p><h3>Cheat sheet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HzxmIpZvPcaJdkWRZkVBYw.png" /></figure><h3>Conclusion</h3><blockquote><strong>View = give me the dataset, I’ll filter it.<br>Table function = give me the parameters, Snowflake generates the dataset.</strong></blockquote><p>Table functions aren’t a Snowflake invention — Oracle, Teradata, SQL Server and Postgres all have their own versions. What Snowflake did differently was make them the <em>default interface</em> for a large part of the platform: semi-structured data, metadata, loading, schema inference and custom parallel processing all come back as rows you can query. Once you read <strong>TABLE(...)</strong> as &quot;a table that takes arguments&quot; and <strong>LATERAL</strong> as &quot;for each row&quot;, the syntax that looked alien becomes one of the most productive tools in your Snowflake toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f905c86730b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why dbt When We Already Have Snowflake?]]></title>
            <link>https://medium.com/@nazeer.td/why-dbt-when-we-already-have-snowflake-0247acc4dc88?source=rss-0a9bc48881dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/0247acc4dc88</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[snowflake-data-cloud]]></category>
            <dc:creator><![CDATA[Nazeer Syed]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 04:16:28 GMT</pubDate>
            <atom:updated>2026-09-22T04:16:28.830Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dtNuNu2R6Bic8ihlD3RQeg.png" /></figure><p>There’s a fair objection I hear from experienced Snowflake engineers: <em>“My SQL works. I have </em><strong><em>MERGE</em></strong><em>, I have tasks, I have stored procedures. Why add another tool?&quot;</em></p><p>It’s a good question, and “because everyone uses dbt” is not a good answer. So let’s do something more honest. Let’s take one ordinary transformation, write it the traditional Snowflake way, then write the exact same thing in dbt — and look at what changed and what it’s worth.</p><p>No toy example that only works in slides. A real incremental table, the kind you actually ship.</p><h3>The task</h3><p>We have a staged orders table, and we want a mart: a daily order summary per customer. It should load <strong>incrementally</strong> — only reprocess new days, not rebuild the whole thing every run. This is bread-and-butter analytics engineering, and it’s exactly where the two approaches diverge most clearly.</p><h3>The traditional Snowflake way</h3><p>Written natively, you’re responsible for the target table, the incremental logic, and the environment wiring. It looks like this:</p><p><strong>Snowflake — native scripting</strong></p><pre>-- 1. Environment wiring (per environment, by hand)<br>USE DATABASE ANALYTICS_PROD;<br>USE SCHEMA MARTS;<br><br>-- 2. Create the target table if it isn&#39;t there yet<br>CREATE TABLE IF NOT EXISTS customer_daily_orders (<br>    customer_id      NUMBER,<br>    order_date       DATE,<br>    total_orders     NUMBER,<br>    total_amount     NUMBER(38,2),<br>    last_updated_at  TIMESTAMP_NTZ<br>);<br><br>-- 3. Incremental upsert, by hand<br>MERGE INTO customer_daily_orders AS target<br>USING (<br>    SELECT<br>        customer_id,<br>        order_date,<br>        COUNT(*)             AS total_orders,<br>        SUM(amount)          AS total_amount,<br>        CURRENT_TIMESTAMP()  AS last_updated_at<br>    FROM ANALYTICS_PROD.STAGING.stg_orders<br>    WHERE order_date &gt;= (<br>        SELECT COALESCE(MAX(order_date), &#39;1900-01-01&#39;)<br>        FROM customer_daily_orders<br>    )<br>    GROUP BY customer_id, order_date<br>) AS source<br>ON  target.customer_id = source.customer_id<br>AND target.order_date  = source.order_date<br>WHEN MATCHED THEN UPDATE SET<br>    target.total_orders    = source.total_orders,<br>    target.total_amount    = source.total_amount,<br>    target.last_updated_at = source.last_updated_at<br>WHEN NOT MATCHED THEN INSERT (<br>    customer_id, order_date, total_orders, total_amount, last_updated_at<br>) VALUES (<br>    source.customer_id, source.order_date, source.total_orders,<br>    source.total_amount, source.last_updated_at<br>);</pre><p>This is correct and it works. But notice what you’re carrying:</p><ul><li>The <strong>DDL is your problem</strong>. If a column changes, you hand-edit the table definition <em>and</em> the merge.</li><li>The database name <strong>ANALYTICS_PROD</strong> is <strong>hardcoded</strong>. Dev and prod are copy-paste-and-find-replace, which is exactly how staging tables leak into production dashboards.</li><li>The dependency on <strong>stg_orders </strong>is <strong>implicit</strong>. Nothing enforces that it runs first. You own the ordering, usually inside a task DAG or an orchestrator you maintain separately.</li><li>There are <strong>no tests</strong> here. Is <strong>customer_id</strong> ever null? Is the grain actually one row per customer per day? You find out in a dashboard, from a stakeholder, on a Friday.</li></ul><h3>The dbt way</h3><p>Here’s the same transformation as a dbt model. This is the <em>entire</em> file:</p><p><strong>dbt — models/marts/customer_daily_orders.sql</strong></p><pre>{{<br>    config(<br>        materialized=&#39;incremental&#39;,<br>        unique_key=[&#39;customer_id&#39;, &#39;order_date&#39;]<br>    )<br>}}<br><br>SELECT<br>    customer_id,<br>    order_date,<br>    COUNT(*)            AS total_orders,<br>    SUM(amount)         AS total_amount,<br>    CURRENT_TIMESTAMP() AS last_updated_at<br>FROM {{ ref(&#39;stg_orders&#39;) }}<br><br>{% if is_incremental() %}<br>WHERE order_date &gt;= (SELECT MAX(order_date) FROM {{ this }})<br>{% endif %}<br><br>GROUP BY customer_id, order_date</pre><p>That’s it. You wrote the <strong>business logic</strong> — a <strong>SELECT</strong> — and nothing else. dbt generates the rest at run time.</p><blockquote><strong>What dbt does for you here</strong></blockquote><blockquote><strong>On the first run it issues a CREATE TABLE AS SELECT. On every run after, it wraps your SELECT in a MERGE keyed on UNIQUE_KEY — the same merge you wrote by hand above, generated from the config() block. The {% if is_incremental() % } guard means the filter only applies on incremental runs, not the initial full build.</strong></blockquote><p>The three pieces of “wiring” from the native version have quietly disappeared into the tooling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5pXIRZ5qcizY7HRy15ENQ.png" /></figure><h3>The part you can’t see in the SQL</h3><p>The code shrinking is nice, but it isn’t the real argument. The real argument is everything dbt gives you <em>around</em> the model that native scripting leaves as a separate, manual, easily-skipped chore.</p><h3>1. Dependencies become a graph, automatically</h3><p>That <strong>{{ ref(‘stg_orders’) }}</strong> isn&#39;t just a fancy table name. It tells dbt &quot;this model depends on <strong>stg_orders</strong>,&quot; and dbt uses every ref() across your project to build a dependency graph. You run dbt run and models execute in the correct order — no orchestration DAG to hand-maintain, no &quot;why did the mart run before its source&quot; incidents.</p><h3>2. Environments stop being copy-paste</h3><p><strong>ref()</strong> resolves to whatever database and schema your <em>target</em> points at. The same model file, unchanged, materializes into <strong>ANALYTICS_DEV</strong> when you&#39;re developing and <strong>ANALYTICS_PROD</strong> in production. No find-and-replace, no accidental cross-environment writes.</p><h3>3. Tests live next to the model</h3><p>Add a small YAML file beside the model and your assumptions become enforced contracts:</p><p><strong>dbt — models/marts/customer_daily_orders.yml</strong></p><pre>models:<br>  - name: customer_daily_orders<br>    description: &quot;One row per customer per day: order count and revenue.&quot;<br>    columns:<br>      - name: customer_id<br>        tests:<br>          - not_null<br>      - name: order_date<br>        tests:<br>          - not_null<br>    tests:<br>      - dbt_utils.unique_combination_of_columns:<br>          combination_of_columns: [customer_id, order_date]</pre><p>Now <strong>dbt test</strong> proves the grain is actually one row per customer per day, on every run, in CI, before anything reaches a dashboard. In the native world these checks are separate ad-hoc query scripts someone has to remember to run — so nobody runs them.</p><h3>4. Documentation and lineage are a byproduct</h3><p>That <strong>description</strong> field, plus every <strong>ref()</strong>, feeds <strong>dbt docs</strong> — a searchable catalog and a clickable lineage graph generated from the code itself. It can&#39;t drift out of date the way a Confluence page does, because it <em>is</em> the code. With native scripting, lineage is tribal knowledge and a diagram someone drew in 2023.</p><blockquote><strong>Why this compounds</strong></blockquote><blockquote><strong>One transformation, the difference looks modest. At fifty interdependent models it’s the difference between a system a new engineer can navigate on day one and a pile of stored procedures only the author understands. dbt’s payoff scales with the size of your project — which is precisely when you need it most.</strong></blockquote><h3>5. It’s just files, so version control actually works</h3><p>Every model is a plain <strong>.sql</strong> file. Pull requests produce meaningful diffs, changes get reviewed, and CI can run <strong>dbt build — select state:modified+ </strong>to test only what changed and everything downstream of it. Try getting a clean, reviewable git history out of stored procedures edited in a worksheet.</p><h3>When traditional Snowflake still wins</h3><p>dbt isn’t a religion, and pretending it has no tradeoffs would undercut the whole point of comparing honestly. Reach for native Snowflake when:</p><ul><li><strong>You need imperative or procedural logic</strong> — loops, dynamic SQL, branching control flow. dbt is declarative by design; Snowflake Scripting and stored procedures exist for a reason.</li><li><strong>The work is operational, not transformational</strong> — managing tasks, streams, alerts, resource monitors, account administration. That’s Snowflake’s job, not dbt’s.</li><li><strong>You want fully-managed refresh</strong> — <strong>Dynamic Tables</strong> now cover a real slice of what people used incremental dbt models for, with Snowflake handling the refresh via <strong>TARGET_LAG</strong>. Worth evaluating before you reach for dbt on a given table. (These two aren&#39;t mutually exclusive — dbt can manage Dynamic Tables as a materialization.)</li><li><strong>Your team has zero dbt fluency and a hard deadline</strong> — a tool nobody knows is a liability that week, whatever its long-run merits.</li></ul><p>The right framing isn’t “dbt versus Snowflake.” dbt <em>runs on</em> Snowflake — it compiles to the same SQL your warehouse already executes. The question is whether you want to hand-write and hand-maintain the DDL, the merges, the environment wiring, the tests, and the docs — or write the business logic and let a tool generate the rest, consistently, in a form your whole team can review.</p><h3>The Conclusion</h3><p>Go back to the two code blocks. The native version and the dbt model produce the <em>identical</em> table with the <em>identical</em> merge. dbt didn’t make the SQL smarter.</p><p>What it did was turn a transformation into a <strong>governed, tested, documented, dependency-aware, environment-portable asset</strong> — and it did that by generating the boilerplate you were writing by hand, so the only thing left in your file is the logic that’s actually yours.</p><p>That’s the advantage. Not that dbt does something Snowflake can’t. That it stops <em>you</em> from having to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0247acc4dc88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Snowflake Query Is Slow. Here’s Exactly How to Find Out Why.]]></title>
            <link>https://medium.com/@nazeer.td/your-snowflake-query-is-slow-heres-exactly-how-to-find-out-why-b866c10e17b2?source=rss-0a9bc48881dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b866c10e17b2</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[snowflake-data-cloud]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[snowflake-computing]]></category>
            <category><![CDATA[query-optimization]]></category>
            <dc:creator><![CDATA[Nazeer Syed]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 20:07:49 GMT</pubDate>
            <atom:updated>2026-07-28T20:07:49.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKpEkahPjjVqh72ZrCrFaA.png" /></figure><p>The single most common mistake I see — in production and in interviews — is treating warehouse size as the first lever. Someone’s dashboard is slow, so they bump the warehouse from Medium to Large, the bill doubles, and the query is still slow because the real problem was a filter that scanned every micro-partition in a 2 TB table.</p><p>Performance work on Snowflake is a <strong>diagnostic discipline</strong>, not a guessing game. The loop is always the same: <strong>Measure → Diagnose → Optimize → Validate</strong>. This post walks that loop end to end, with the exact diagnostic queries you’d run, worked examples, and — because the goal is interview readiness — the “why” underneath each fix that interviewers love to probe.</p><h3>1. Foundations You Must Understand First</h3><p>Every optimization below makes sense only if you understand three things about how Snowflake stores and reads data. Skip this and the fixes become cargo-cult rituals. Nail it and every interview answer becomes “because…”.</p><h3>0.1 Micro-partitions</h3><p>Snowflake automatically stores table data in <strong>micro-partitions</strong> — immutable, compressed files of roughly <strong>50–500 MB of uncompressed data</strong> each (16 MB compressed, columnar internally). You never manage them directly. Critically, for each micro-partition Snowflake keeps <strong>metadata</strong>: the min and max value of every column, distinct counts, null counts.</p><h3>0.2 Pruning — the whole ballgame</h3><p>When your query has a filter like <strong>WHERE order_date &gt; ‘2024–01–01’</strong>, Snowflake reads the metadata first and <strong>skips any micro-partition whose max order_date is before 2024-01-01</strong>. It never touches those files. This is <strong>partition pruning</strong>, and it is the single biggest performance lever on the platform.</p><blockquote><strong>The mental model: Snowflake performance is mostly about <em>reading less data</em>. A bigger warehouse reads the same data faster; good pruning means you never read most of it at all. That’s why the infographic leads with “a slow query does not always mean a larger warehouse.” Reducing bytes scanned usually beats adding compute — and it’s free.</strong></blockquote><h3>0.3 The three cache layers</h3><p>Before you optimize anything, know what’s already being cached, because it explains “why was it fast the second time?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDICbZR1zT1G_R_Z-rVQ4A.png" /></figure><blockquote><strong>INTERVIEW ANSWER</strong></blockquote><blockquote><strong><em>“Why did my query run in 20ms the second time?”</em> — The result cache served it from the cloud services layer without spinning up the warehouse, because the query text was identical and no underlying data had changed. If I change even a literal or the data mutates, the cache misses and it re-executes.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7om8Bol1XIFEEzqfIGl3SQ.png" /></figure><p>Ways to Enable Results Cache:</p><pre>ALTER SESSION SET USE_CACHED_RESULT = TRUE;  -- SESSION LEVEL<br>ALTER USER myuser SET USE_CACHED_RESULT = TRUE; --USER LEVEL<br>ALTER ACCOUNT SET USE_CACHED_RESULT = TRUE; --ACCOUNT LEVEL </pre><h3>2. Identify the Bottleneck</h3><p>Never optimize blind. The first move on any slow query is to pull its execution stats from <strong>SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY</strong> and read four numbers.</p><h4>2.1 The four columns that tell you everything</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L48SFH08xt5S4vab29418Q.png" /></figure><h4>2.2 The diagnostic query</h4><p>Run this against a specific <strong>QUERY_ID</strong> (grab it from Snowsight&#39;s Query History) to get every relevant metric in one shot:</p><pre>SELECT<br>    QUERY_ID,<br>    QUERY_TEXT,<br>    TOTAL_ELAPSED_TIME / 1000            AS ELAPSED_SEC,<br>    COMPILATION_TIME  / 1000            AS COMPILE_SEC,<br>    EXECUTION_TIME    / 1000            AS EXEC_SEC,<br>    QUEUED_OVERLOAD_TIME / 1000         AS QUEUED_SEC,<br>    BYTES_SCANNED / 1e9                 AS GB_SCANNED,<br>    BYTES_SPILLED_TO_LOCAL_STORAGE  / 1e9 AS GB_SPILLED_LOCAL,<br>    BYTES_SPILLED_TO_REMOTE_STORAGE / 1e9 AS GB_SPILLED_REMOTE,<br>    PARTITIONS_SCANNED,<br>    PARTITIONS_TOTAL,<br>    ROWS_PRODUCED<br>FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY<br>WHERE QUERY_ID = &#39;&lt;your_query_id&gt;&#39;;</pre><p><strong>Latency gotcha:</strong> <strong>ACCOUNT_USAGE.QUERY_HISTORY</strong> can lag by up to ~45 minutes but retains 365 days of history. For queries in the last few minutes, use the <strong>INFORMATION_SCHEMA.QUERY_HISTORY()</strong> table function instead — it&#39;s near real-time but only keeps 7–14 days. Knowing this distinction is a classic interview differentiator.</p><p>Read the result like a triage nurse: whichever number is abnormal decides which step you jump to next. Don’t fix all four — fix the one that dominates <strong>ELAPSED_SEC</strong>.</p><h4>2.3 Check Warehouse Queuing</h4><p>If <strong>QUEUED_SEC</strong> was your red flag, the query itself may be fine — it just couldn&#39;t get compute. There are two fundamentally different fixes, and confusing them is a common interview trap.</p><h4>Scale UP vs. Scale OUT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7fHtJgM586r1Jh5G89oIA.png" /></figure><blockquote><strong>The rule of thumb: Scale <em>up</em> for a <em>heavy</em> query. Scale <em>out</em> for <em>many</em> queries. A single 40-minute ETL job doesn’t benefit from multi-cluster (one query only runs on one cluster); it benefits from a larger size. A BI dashboard hit by 200 analysts at 9am benefits from multi-cluster auto-scaling, not a bigger single warehouse.</strong></blockquote><h4>2.4 Find the queries competing for your warehouse</h4><p>Queuing is often caused by <em>other</em> heavy queries hogging the same warehouse. Find them:</p><pre>SELECT<br>    QUERY_TEXT,<br>    TOTAL_ELAPSED_TIME,<br>    WAREHOUSE_NAME,<br>    START_TIME<br>FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY<br>WHERE WAREHOUSE_NAME = &#39;COMPUTE_WH&#39;<br>  AND START_TIME &gt; DATEADD(&#39;HOUR&#39;, -1, CURRENT_TIMESTAMP())<br>ORDER BY TOTAL_ELAPSED_TIME DESC<br>LIMIT 10;</pre><p>The fix might not be “scale” at all — it might be <strong>workload isolation</strong>: move the offending batch job onto its own dedicated warehouse so it stops starving your interactive dashboards. Separating workloads by warehouse is often the cleanest answer and one interviewers reward.</p><h3>3. Reduce Data Scanned (Partition Pruning)</h3><p>This is the highest-impact section. If <strong>PARTITIONS_SCANNED</strong> is close to <strong>PARTITIONS_TOTAL</strong>, your query is doing a full table scan and no amount of compute will make that cheap.</p><h3>3.1 Give the optimizer something to prune on</h3><p>Compare these two queries against an <strong>ORDERS</strong> table clustered naturally by date (rows arrive in date order):</p><pre>-- BAD: scans everything. No usable range predicate on the<br>-- natural clustering column, so every micro-partition is read.<br>SELECT *<br>FROM ORDERS<br>WHERE CUSTOMER_ID = 5;<br><br>-- GOOD: prune with the date first, THEN filter customer.<br>-- Snowflake skips every micro-partition outside the date range.<br>SELECT *<br>FROM ORDERS<br>WHERE ORDER_DATE &gt;= &#39;2024-01-01&#39;<br>  AND CUSTOMER_ID = 5;</pre><p>The bad query isn’t “wrong” — it returns correct results. But because <strong>CUSTOMER_ID</strong> is scattered across every micro-partition, Snowflake can&#39;t skip any of them. Adding the date predicate lets pruning eliminate the vast majority of files before a single byte is read.</p><h3>3.2 Strategies for Selecting Clustering Keys</h3><p>a. Cluster columns that are most actively used in selective filters. For many fact tables involved in date-based queries (for example “WHERE invoice_date &gt; x AND invoice date &lt;= y”)</p><p>b. If there is room for additional cluster keys, then consider columns frequently used in join predicates</p><p>c. If you are defining a multi-column clustering key for a table, the order in which the columns are specified in the <strong>CLUSTER BY</strong> clause is important. As a general rule, Snowflake recommends ordering the columns from <strong><em>lowest</em></strong> cardinality to <strong><em>highest</em></strong> cardinality.</p><p>d. In some cases, clustering on columns used in <strong>GROUP BY</strong> or <strong>ORDER BY</strong> clauses can be helpful. However, clustering on these columns is usually less helpful than clustering on columns that are heavily used in filter or JOIN operations.</p><blockquote><strong>Clustering is not free. Automatic Clustering runs a background service that reorganizes micro-partitions and consumes credits. Only cluster large tables that are (a) frequently filtered/joined on the key and (b) not churning constantly on that key. A small table, or one you full-scan anyway, should never be clustered. “When would you <em>not</em> add a clustering key?” is a favorite trick question — the answer is: small tables, low-cardinality keys, high-DML tables, or when the query pattern doesn’t filter on it.</strong></blockquote><h3>4. Fix Spilling</h3><p>If <strong>BYTES_SPILLING &gt; 0</strong>, the query needed more memory than the warehouse had, so it wrote intermediate data to disk — or worse, to remote storage. Spilling is a performance cliff: remote spilling can slow a query by 10–100x.</p><h3>4.1 Local vs. remote spilling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIvojCidRshQLo02Se8sYw.png" /></figure><h3>4.2 The fixes, in priority order</h3><ol><li><strong>Reduce data processed first</strong> — add filters, push <strong>WHERE</strong> clauses earlier, <strong>LIMIT</strong> where valid, project only needed columns. Often removes the spill without spending a cent.</li><li><strong>Break the query up</strong> — materialize an intermediate result into a temp table or CTE so a giant join/sort isn’t held in memory all at once.</li><li><strong>Increase warehouse size</strong> — each size up roughly doubles memory. This is the direct fix when the workload genuinely needs it, but it’s the <em>last</em> resort after the two free options.</li></ol><h3>5. Optimize the SQL Itself</h3><p>Sometimes the warehouse and pruning are fine and the SQL is simply written in a way that forces Snowflake to do too much work. Here are the recurring offenders and their fixes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9GsPorRG9HE6TKHVFP-oQ.png" /></figure><h3>5.1 The pruning-killer everyone writes</h3><p>This one deserves its own spotlight because it silently disables partition pruning:</p><pre>-- BAD: wrapping the column in a function forces Snowflake to<br>-- evaluate YEAR() on every row -&gt; no pruning, full scan.<br>SELECT *<br>FROM ORDERS<br>WHERE YEAR(order_date) = 2024;<br><br>-- GOOD: express the same filter as a range on the raw column.<br>-- Micro-partition min/max metadata can now prune.<br>SELECT *<br>FROM ORDERS<br>WHERE order_date &gt;= &#39;2024-01-01&#39;<br>  AND order_date &lt;  &#39;2025-01-01&#39;;</pre><p><strong>The principle:</strong> the moment you wrap a filter column in a function ( <strong>YEAR(), UPPER(), CAST(), SUBSTR()</strong>), Snowflake can no longer compare your predicate against the stored min/max metadata, so pruning is lost and you full-scan. Always transform the <em>literal</em>, never the column.</p><h3>5.2 The overlooked signal: high compile time</h3><p>Compile time is one of the most overlooked query performance signals because a query can spend significant time planning before any data is processed. During compilation, Snowflake parses the SQL, expands views, retrieves metadata, optimizes the execution plan, and evaluates micro-partition metadata for pruning. If <strong>COMPILATION_TIME</strong> makes up a large portion of the total query time, the bottleneck lies in the query planner rather than the warehouse compute. In such cases, increasing warehouse size or tuning execution won’t help — you need to simplify the query or reduce planning complexity.</p><p>The tell is the ratio, not the raw number:</p><pre>SELECT<br>    QUERY_ID,<br>    COMPILATION_TIME / 1000                    AS COMPILE_SEC,<br>    EXECUTION_TIME   / 1000                    AS EXEC_SEC,<br>    ROUND(COMPILATION_TIME * 100.0<br>          / NULLIF(TOTAL_ELAPSED_TIME, 0), 1)  AS PCT_COMPILE<br>FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY<br>WHERE QUERY_ID = &#39;&lt;your_query_id&gt;&#39;;</pre><p>If <strong>PCT_COMPILE</strong> is ~60%+ <em>and</em> the absolute value is meaningful (seconds, not milliseconds), you have a compilation problem. Here are the five causes and their remedies.</p><h4>Cause 1 — Too many joins (the biggest one)</h4><p><strong>Remedy:</strong> break it into stages. Materialize the enriched fact into a temp/transient table first, then join the rest. Each smaller statement compiles fast, and the optimizer’s search space shrinks dramatically.</p><h4>Cause 2 — Giant IN lists / literal explosions</h4><p><strong>Remedy:</strong> load the values into a temp table and join. The optimizer handles a join far better than a huge literal list.</p><h4>Cause 3 — Deeply nested views</h4><p><strong>Remedy:</strong> flatten. Collapse the logic into fewer layers, or materialize the stable middle layers as tables (or Dynamic Tables) so the top query reads a physical object instead of re-expanding the tree.</p><h4>Cause 4 — Metadata bloat / too many micro-partitions</h4><p>a table with an enormous number of micro-partitions makes compilation slower — there’s simply more metadata to scan through.</p><p><strong>Remedy:</strong> reduce partition count and improve organization.</p><h4>Cause 5 — SELECT * on wide tables &amp; heavy security policies</h4><p><strong>Remedy:</strong> select only the columns you need, and keep policy logic simple — a row access policy with subqueries is compile-time overhead on every query against that table.</p><h3>6.Search Optimization &amp; Query Acceleration</h3><p>Two paid services solve two different problems that plain warehouse tuning can’t. Knowing <em>which</em> to reach for is the whole point.</p><h3>6.1 Search Optimization Service (SOS)</h3><p>For <strong>point lookups on large tables</strong> — highly selective equality or <strong>IN</strong> filters that return a few rows out of billions (e.g. looking up one customer, one order id). SOS builds a persistent search access path so these needle-in-haystack queries don&#39;t scan the table.</p><pre>ALTER TABLE ORDERS<br>  ADD SEARCH OPTIMIZATION ON EQUALITY(CUSTOMER_ID);</pre><p>Check which tables would benefit:</p><pre>SELECT *<br>FROM TABLE(<br>  INFORMATION_SCHEMA.SEARCH_OPTIMIZATION_HISTORY(<br>    DATE_RANGE_START =&gt; DATEADD(&#39;DAY&#39;, -7, CURRENT_TIMESTAMP())<br>  )<br>);</pre><h3>6.2 Query Acceleration Service (QAS)</h3><p>For queries with <strong>large scans</strong> or bursty, unpredictable workloads — QAS offloads parts of the scan to serverless compute, so a single big query gets extra horsepower without permanently resizing the warehouse.</p><pre>ALTER WAREHOUSE COMPUTE_WH<br>  SET ENABLE_QUERY_ACCELERATION = TRUE;</pre><h3>Read the Query Profile UI</h3><p>Everything above is measurable in SQL, but the <strong>Query Profile</strong> in Snowsight is where you <em>see</em> the bottleneck operator visually. Path: <strong>Query History → click the query → Query Profile tab</strong>.</p><h3>7.1 What to look for</h3><ul><li><strong>Nodes with high % of total time</strong> — that node is your bottleneck operator. Optimize that, not the query as a whole.</li><li><strong>Pruning ratio on TableScan nodes</strong> — “partitions scanned / partitions total.” Close to 1.0 means no pruning (see Step 3).</li><li><strong>Spilling indicators on Join / Sort / Aggregate nodes</strong> — the orange “bytes spilled” line (see Step 4).</li><li><strong>Exploding joins</strong> — when a join’s <em>output rows greatly exceed its input rows</em>. Almost always a bad or missing join key producing a partial Cartesian product.</li></ul><h3>8. The 6-Point Diagnostic Checklist</h3><p>Memorize this. It’s the exact order to work a slow query, and it doubles as a crisp interview framework:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsEXJV4RP8xzQCvWwZPkZw.png" /></figure><h3>9. Bonus: your 10 slowest queries this week</h3><p>Start every performance review by finding where the pain actually is:</p><pre>SELECT<br>    QUERY_ID,<br>    SUBSTR(QUERY_TEXT, 1, 80) AS QUERY_PREVIEW,<br>    USER_NAME,<br>    WAREHOUSE_NAME,<br>    TOTAL_ELAPSED_TIME / 1000 AS ELAPSED_SEC,<br>    BYTES_SCANNED / 1e9       AS GB_SCANNED,<br>    PARTITIONS_SCANNED,<br>    PARTITIONS_TOTAL,<br>    ROUND(PARTITIONS_SCANNED * 100.0<br>          / NULLIF(PARTITIONS_TOTAL, 0), 1) AS PCT_SCANNED<br>FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY<br>WHERE START_TIME &gt; DATEADD(&#39;DAY&#39;, -7, CURRENT_TIMESTAMP())<br>  AND TOTAL_ELAPSED_TIME &gt; 0<br>  AND QUERY_TYPE = &#39;SELECT&#39;<br>ORDER BY TOTAL_ELAPSED_TIME DESC<br>LIMIT 10;</pre><h3>10. Extra Suggestions</h3><p>a. Set <strong>AUTO_SUSPEND</strong> = &#39;<strong>60</strong>&#39; OR LOW and <strong>AUTO_RESUME = TRUE</strong></p><p>b. use <strong>Result cache as a free optimization</strong></p><p>c. use <strong>Materialized views</strong> for repeated aggregations</p><p>d. Filter <strong>Early</strong> before joining, eliminate <strong>Join Explosions</strong></p><p>e. Choose <strong>Warehouse size</strong>, measure — Dont Guess.</p><h3><strong>Conclusion</strong></h3><p>A slow Snowflake query is a solvable puzzle, not a budget request. Work the loop — <strong>Measure → Diagnose → Optimize → Validate</strong> — and let the four signals from <strong>QUERY_HISTORY</strong> route you: queuing to warehouse sizing, spilling to memory, high scan ratios to pruning and clustering, high compile time to SQL structure. Reach for Search Optimization and Query Acceleration only when the query <em>shape</em> justifies them, and confirm every fix in the Query Profile.</p><p>Found this useful? 👏 Clap it so that more people can find it, and follow me on <a href="https://www.linkedin.com/in/nsyed9/">Linkedin</a> for more content on data engineering and AI. See you there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b866c10e17b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ICEBERG + SNOWFLAKE: Confused by Catalogs? Let’s Clear It Up]]></title>
            <link>https://medium.com/@nazeer.td/iceberg-snowflake-confused-by-catalogs-lets-clear-it-up-a26974ce36cd?source=rss-0a9bc48881dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a26974ce36cd</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[snowflake-horizon]]></category>
            <category><![CDATA[snowflake-data-cloud]]></category>
            <category><![CDATA[apache-iceberg]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Nazeer Syed]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 17:47:36 GMT</pubDate>
            <atom:updated>2026-07-23T17:47:36.691Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFevF28gTlJuOjzJ7O12Rg.png" /></figure><h3><strong>Snowflake Catalog, External Catalog, Horizon, and JDBC Federation</strong></h3><p>These four terms get used as if everyone already knows how they relate, and almost nobody does on the first pass. So let’s build the picture from nothing. By the end of this section you’ll be able to look at any Snowflake-plus-Iceberg setup and say exactly which pattern it is and why.</p><h3>First, the one idea everything hangs on: what a catalog actually is</h3><p>An Iceberg table is not one thing. It is two:</p><ul><li><strong>The data files</strong> — the actual Parquet files sitting in your S3 or ADLS bucket. This is the bulk of the table, the rows themselves.</li><li><strong>The metadata</strong> — small JSON files that track the schema, the list of snapshots, and exactly which data files belong to the table right now.</li></ul><p>The <strong>catalog</strong> is a third, tiny, but decisive thing. It is the pointer that answers one question: <em>“for this table, which metadata file is the current one?”</em> That’s it. The catalog is a lookup — table name in, current metadata location out.</p><p><strong>The sentence to remember</strong></p><blockquote><strong>A catalog does not store your data and it does not store your table’s contents. It stores the pointer to the current version. Whoever controls that pointer controls the table — they arbitrate every write, and they decide what “current” means for everyone else.</strong></blockquote><p>Once that clicks, every pattern below is just an answer to two questions: <strong>who holds the pointer, and how does the other engine reach it?</strong> Keep those two questions in your head and the fog lifts.</p><h3>A picture to anchor it: the library</h3><p>Think of a library. The <em>books on the shelves</em> are your data files in the bucket. The <em>card catalog</em> — the index that tells you where each book is and which edition is the current one — is the Iceberg catalog. Reading a book means two steps: check the card catalog to find the current edition, then walk to the shelf and read it.</p><p>Every pattern below is a different answer to “who runs the card catalog, and who’s allowed to walk the shelves.”</p><h3>1. Snowflake catalog — Snowflake runs the card catalog</h3><p>This is what we built in this post. You wrote<strong> CATALOG=&#39;SNOWFLAKE&#39;</strong> on the database, and from that moment <strong>Snowflake owns the pointer</strong> for every Iceberg table inside it. Snowflake writes the metadata, manages the snapshots, runs compaction in the background, and applies its own role-based access control, masking policies, and time travel.</p><p>The data files still live in <em>your</em> bucket — Snowflake never takes custody of the rows. But the brain of the table, the catalog, lives inside Snowflake. In the library analogy: the books are yours, on your shelves, but Snowflake runs the card catalog and enforces the borrowing rules. This is often called a <strong>Snowflake-managed Iceberg table</strong>, and “Snowflake catalog” and “Snowflake-managed” mean the same thing.</p><h3>2. Horizon Catalog — the doorway into the Snowflake catalog</h3><p>Here is the piece that confuses people most, so read it slowly. Horizon is not a <em>different</em> catalog from the Snowflake catalog. Horizon <strong>is</strong> Snowflake’s catalog and governance layer — and, crucially, it speaks the open Iceberg REST Catalog protocol.</p><p>That last part is what makes it interesting. Because Horizon talks the standard REST language, an outside engine — Spark, Flink, Trino, PyIceberg, DuckDB — can walk up to Snowflake and use its card catalog directly, without any Snowflake-specific connector. That is exactly what our Spark session did: it pointed at the <strong>/polaris/api/catalog</strong> endpoint in the <a href="https://medium.com/@nazeer.td/i-inserted-data-from-spark-and-snowflake-saw-it-instantly-bidirectional-iceberg-bccab587b56b">previous blog</a>, authenticated with a PAT scoped to a role, received vended credentials, and read and wrote real rows.</p><p><strong>Snowflake catalog vs Horizon — the clean distinction</strong></p><blockquote><strong>They describe the <em>same tables</em> from two angles. “Snowflake catalog” is about <em>ownership</em> — Snowflake holds the pointer. “Horizon” is about <em>access</em> — it is the doorway, the open REST API, that lets external engines reach that pointer while Snowflake’s rules still apply. When someone says “connect Spark to Horizon,” they mean “connect Spark to Snowflake-managed Iceberg tables.” Snowflake stays the owner; the outside engine is a guest holding a scoped pass.</strong></blockquote><p>In the library: Snowflake runs the card catalog (that’s the Snowflake catalog), and Horizon is the public reading-room door that lets visitors from other institutions come in, use the catalog, and even shelve new books — but every action is logged and rule-checked by the host. This is the pattern in this post, and it is the one to reach for when <strong>Snowflake should be the governed source of truth</strong> and other engines are participants.</p><h3>3. External catalog &amp; catalog-linked database — the pointer lives somewhere else</h3><p>Now flip the direction. Sometimes Snowflake is <em>not</em> the owner. Some other system — AWS Glue, Apache Polaris, Databricks Unity Catalog — holds the pointer, and Snowflake needs to reach out to <em>their</em> card catalog. That other system is an <strong>external catalog</strong>.</p><p>The classic way to do this registers one external table at a time through a catalog integration, and historically it was read-only from Snowflake’s side. The modern, far more capable way is a <strong>catalog-linked database</strong>: you link a whole Snowflake database to the external REST catalog once, and Snowflake auto-discovers every namespace and table in it, keeps in sync as they change, and — this is the important upgrade — <strong>can read and write back</strong> into the remote catalog, including creating and dropping tables there.</p><p><strong>The mirror image</strong></p><blockquote><strong>A catalog-linked database is the exact reflection of the Horizon pattern. Both use the same open Iceberg REST protocol; they just point in opposite directions. With Horizon, Snowflake owns the catalog and an outside engine reaches in. With a catalog-linked database, an outside system owns the catalog and <em>Snowflake</em> reaches out. Same doorway, opposite side.</strong></blockquote><p>In the library: instead of hosting, Snowflake sends a librarian over to another institution, who reads their card catalog, borrows books off their shelves, and can even file new books there — all governed by that other institution’s index. Reach for this when <strong>someone else’s catalog already owns the tables</strong> and Snowflake needs to join in rather than take over.</p><h3>4. JDBC query federation — no shared table at all</h3><p>This one is the odd sibling, and the fastest way to understand it is to notice what it is <em>not</em>: it has nothing to do with Iceberg, catalogs, or shared files. There is no shared shelf and no shared card catalog.</p><p>JDBC query federation is a live <strong>connection</strong> to another running database. When you query a federated table, your engine hands part of the query to the remote database over JDBC, the remote database runs it on its own compute, and the results come back over the wire. Nothing is shared physically; every query is a fresh round trip. It is almost always <strong>read-only</strong>, and how much work gets pushed to the remote side depends on whether each filter can be translated into that database’s dialect — anything that can’t translate gets pulled back and finished locally, which can be slow.</p><p>In the library: you don’t visit and you don’t share shelves. You phone another library, ask “what does page 40 of this book say,” and a librarian there reads it aloud to you. Useful for a quick look, but you’re dependent on their staff doing the work every single time, and you can only read, never write. Reach for this for <strong>ad hoc access to non-Iceberg tables</strong> — a Postgres, MySQL, or SQL Server system you want to peek into without building a pipeline.</p><h3>Conclusion:</h3><p>Almost all of the confusion around these four terms comes from skipping the first idea — that a catalog is just the pointer to the current version of a table, not the data and not the metadata. Hold onto that, and the rest arranges itself: it’s always a question of <strong>who owns the pointer</strong> and <strong>which way the connection flows</strong>.</p><p>Snowflake owns it and others reach in? Horizon. Someone else owns it and Snowflake reaches out? Catalog-linked database. Nobody’s sharing an Iceberg table at all and you just need to read a live database? JDBC federation. Three answers, one question, no doubt left.</p><p>Found this useful? 👏 Clap it so that more people can find it, and follow me on <a href="https://www.linkedin.com/in/nsyed9/">Linkedin</a> for more content on data engineering and AI. See you there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a26974ce36cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Iceberg Table, Two Engines: No Copy, No Pipeline, Both Directions]]></title>
            <link>https://medium.com/@nazeer.td/i-inserted-data-from-spark-and-snowflake-saw-it-instantly-bidirectional-iceberg-bccab587b56b?source=rss-0a9bc48881dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/bccab587b56b</guid>
            <category><![CDATA[apache-iceberg]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[snowflake-iceberg]]></category>
            <category><![CDATA[snowflake-horizon-catalog]]></category>
            <category><![CDATA[snowflake-data-cloud]]></category>
            <dc:creator><![CDATA[Nazeer Syed]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 23:41:55 GMT</pubDate>
            <atom:updated>2026-08-04T04:16:58.562Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*seY3aSr0H7AxshEJUZbGtg.png" /></figure><p>Most Snowflake and Spark integrations focus only on reading data through Parquet files or JDBC connections, but true interoperability requires seamless writes as well. Traditionally, writing from Spark into Snowflake-managed tables meant exports, staging areas, and custom pipelines.</p><p>The Iceberg REST Catalog specification changes this by enabling open access through Snowflake Horizon Catalog. Any Iceberg-compatible engine like Spark, Flink, Trino, or PyIceberg can securely read and write Snowflake-managed Iceberg tables while respecting Snowflake governance.</p><p>In this walkthrough, I demonstrate the complete round trip: creating an Iceberg table in Snowflake, reading it from Spark, writing new data back from Spark, and verifying the changes directly in Snowflake.</p><h3>What “Snowflake-managed” means here</h3><p>This is the part people get backwards, so it’s worth being precise before any code.</p><p>There are two shapes of Iceberg table in Snowflake. In the first, some external catalog (AWS Glue, Unity Catalog, Polaris) owns the table and Snowflake reads it as an externally managed table. In the second — the one used here — <strong>Snowflake is the catalog</strong>. Snowflake owns the metadata, handles compaction and snapshot management, applies its own RBAC, and simply exposes the whole thing through the open Iceberg REST API under Horizon.</p><p>So the data files sit in <em>your</em> S3 bucket. Snowflake writes and manages the Iceberg metadata. And Spark talks to Snowflake as if it were any other REST catalog. That’s the architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hPGAuVWV_py9HtcsEQOag.png" /></figure><p>Notice what is <em>not</em> in that diagram: a JDBC hop, a Snowflake virtual warehouse in the Spark read path, and a copy of the data. Spark reads the Parquet files directly using credentials Horizon hands it at request time.</p><h3>Step 1 — Create the external volume</h3><p>An external volume is Snowflake’s handle on your object storage. Creating one needs an account-level privilege, so grant it first.</p><pre>USE ROLE ACCOUNTADMIN;<br>GRANT CREATE EXTERNAL VOLUME ON ACCOUNT TO ROLE DB_DEVELOPER;<br>USE ROLE DB_DEVELOPER;<br><br>CREATE OR REPLACE EXTERNAL VOLUME iceberg_external_volume<br>   STORAGE_LOCATIONS =<br>      (<br>         (<br>            NAME = &#39;my-s3-us-west-2&#39;<br>            STORAGE_PROVIDER = &#39;S3&#39;<br>            STORAGE_BASE_URL = &#39;s3://ns-iceberg-demo/&#39;<br>            STORAGE_AWS_ROLE_ARN = &#39;arn:aws:iam::&lt;AWS_ACCOUNT_ID&gt;:role/iceberg_snowflake&#39;<br>            STORAGE_AWS_EXTERNAL_ID = &#39;iceberg_table_demo_ns&#39;<br>         )<br>      )<br>      ALLOW_WRITES = TRUE;</pre><p><strong>ALLOW_WRITES = TRUE</strong> is not optional for this exercise. Without it Snowflake can register metadata but neither Snowflake nor a delegated engine can write data files, and your Spark <strong>INSERT</strong> will fail with a permission error that points at S3 rather than at the volume — which sends you debugging the wrong layer entirely.</p><h4>Complete the IAM trust relationship</h4><p>On the AWS side, you need to create an IAM policy that defines the required permissions for accessing the S3 location. After creating the policy, create an IAM role and attach the policy to that role. This role will be used by the data platform to securely access the required AWS resources.</p><p>Below are the IAM policy and role configurations which i used for this setup.</p><pre>--BUCKET ACCESS POLICY<br><br>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:GetObjectVersion&quot;,<br>                &quot;s3:DeleteObject&quot;,<br>                &quot;s3:DeleteObjectVersion&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::ns-iceberg-demo/*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:ListBucket&quot;,<br>                &quot;s3:GetBucketLocation&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::ns-iceberg-demo&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringLike&quot;: {<br>                    &quot;s3:prefix&quot;: [<br>                        &quot;*&quot;<br>                    ]<br>                }<br>            }<br>        }<br>    ]<br>}<br><br>--TRUST RELATIONSHIP IN IAM ROLE. <br><br>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;AWS&quot;: &quot;XXXXX&quot; --Copy STORAGE_AWS_IAM_USER_ARN from below DESC EXTERNAL VOLUME iceberg_external_volume command<br>            },<br>            &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;sts:ExternalId&quot;: &quot;iceberg_table_demo_ns&quot;  --copy STORAGE_AWS_EXTERNAL_ID from below DESC EXTERNAL VOLUME iceberg_external_volume command<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>Snowflake generates an IAM user on its side when the volume is created. That principal has to be trusted by the role in your ARN, so read it back and paste it into the role’s trust policy:</p><p>Snowflake · read the principal, then verify</p><pre>-- Copy STORAGE_AWS_IAM_USER_ARN and STORAGE_AWS_EXTERNAL_ID from the output<br>-- into the trust policy of the IAM role named in the ARN above.<br>DESC EXTERNAL VOLUME iceberg_external_volume;<br><br>-- Round-trip test: writes a probe file, reads it back, deletes it.<br>SELECT SYSTEM$VERIFY_EXTERNAL_VOLUME(&#39;iceberg_external_volume&#39;);</pre><p>Run the verify function until it comes “<strong>success=true</strong>”. Everything downstream assumes storage access already works, and a failure here surfaces later as a confusing catalog error rather than an obvious permissions one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-hqXumwl0HN85PRFGgzbA.png" /></figure><h3>Step 2 — Create the Snowflake-managed Iceberg database and table</h3><p>Setting <strong>catalog= ‘SNOWFLAKE’</strong> at the database level is what makes Horizon the owner of every Iceberg table inside it. Setting the external volume at the same level means individual tables inherit it and you never repeat yourself.</p><pre>-- GRANT IS MUST, OTHER WISE SPARK CANT ACCESS S3F FILES IN THE VOLUME.<br>GRANT USAGE ON EXTERNAL VOLUME iceberg_external_volume TO ROLE DB_ADMIN; <br>USE ROLE DB_ADMIN;<br>create or replace database mngd_icbrg<br>catalog= &#39;SNOWFLAKE&#39;<br>EXTERNAL_VOLUME = &#39;iceberg_external_volume&#39;;<br><br>CREATE SCHEMA ICB_SCHMA;<br><br>CREATE ICEBERG TABLE mngd_icbrg.ICB_SCHMA.ICB_ORDERS (<br>    order_id INT,<br>    customer STRING,<br>    amount NUMBER(10,2)<br>);<br><br>INSERT INTO mngd_icbrg.ICB_SCHMA.ICB_ORDERS<br>VALUES<br>(1,&#39;John&#39;,100.25),<br>(2,&#39;Sara&#39;,250.50);<br><br>select * from mngd_icbrg.ICB_SCHMA.ICB_ORDERS</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wgtuGXMZmR_RJ8rA5jF3dw.png" /></figure><h3>Step 3 — Mint a programmatic access token</h3><p>Spark authenticates to Horizon with a Snowflake PAT. Restrict it to a single role so the token can never do more than that role can — this is your blast radius, set it deliberately.</p><pre>ALTER USER ADD PROGRAMMATIC ACCESS TOKEN databricks_pat<br>  DAYS_TO_EXPIRY = 30<br>  ROLE_RESTRICTION = &#39;DB_ADMIN&#39;<br>  COMMENT = &#39;PAT token for Databricks connection&#39;;</pre><h3>Step 4 — Configure the Spark session</h3><p>This ran on a plain local Spark session — <strong>local[*]</strong>, no cluster, no Databricks workspace. That&#39;s a deliberate part of the proof: nothing about this depends on a managed Spark platform.</p><pre>from pyspark.sql import SparkSession<br><br>CATALOG_NAME = &quot;ICEBERG_DEMO&quot;<br>SNOWFLAKE_DB_NAME = &quot;MNGD_ICBRG&quot;<br><br>ACCOUNT_URL = &quot;https://AERSXYS-DY16150.snowflakecomputing.com&quot;<br>CATALOG_URI = f&quot;{ACCOUNT_URL}/polaris/api/catalog&quot;<br><br>PAT_TOKEN = &quot;xxxxx&quot;  --copy the pat token from step3<br><br><br>spark = (<br>    SparkSession.builder<br>    .master(&quot;local[*]&quot;)<br>    .appName(&quot;horizon_catalog&quot;)<br>    .config(<br>        &quot;spark.jars.packages&quot;,<br>        &quot;org.apache.iceberg:iceberg-spark-runtime-3.5_2.12:1.8.1,org.apache.iceberg:iceberg-aws-bundle:1.8.1&quot;<br>    )<br>    .config(<br>        &quot;spark.sql.extensions&quot;,<br>        &quot;org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions&quot;<br>    )<br>    .getOrCreate()<br>)<br><br># Catalog Configurations<br>spark.conf.set(f&quot;spark.sql.catalog.{CATALOG_NAME}&quot;, &quot;org.apache.iceberg.spark.SparkCatalog&quot;)<br>spark.conf.set(f&quot;spark.sql.catalog.{CATALOG_NAME}.type&quot;, &quot;rest&quot;)<br>spark.conf.set(f&quot;spark.sql.catalog.{CATALOG_NAME}.uri&quot;, CATALOG_URI)<br>spark.conf.set(f&quot;spark.sql.catalog.{CATALOG_NAME}.credential&quot;, PAT_TOKEN)<br>spark.conf.set(f&quot;spark.sql.catalog.{CATALOG_NAME}.warehouse&quot;, SNOWFLAKE_DB_NAME)<br>spark.conf.set(f&quot;spark.sql.catalog.{CATALOG_NAME}.scope&quot;, &quot;session:role:DB_ADMIN&quot;)<br><br># S3 File IO &amp; Vended Credentials Configurations<br>spark.conf.set(f&quot;spark.sql.catalog.{CATALOG_NAME}.io-impl&quot;, &quot;org.apache.iceberg.aws.s3.S3FileIO&quot;)<br>spark.conf.set(f&quot;spark.sql.catalog.{CATALOG_NAME}.header.X-Iceberg-Access-Delegation&quot;, &quot;vended-credentials&quot;)<br>spark.conf.set(&quot;spark.sql.iceberg.vectorization.enabled&quot;, &quot;false&quot;)</pre><h3>Step 5 — Read from Spark</h3><p>Discovery works through the standard Iceberg catalog interface. Snowflake schemas appear as Iceberg namespaces:</p><pre>spark.sql(&quot;SHOW NAMESPACES IN ICEBERG_DEMO&quot;).show()<br>spark.sql(f&quot;SHOW TABLES IN {CATALOG_NAME}.ICB_SCHMA&quot;).show()<br><br>spark.sql(&quot;USE ICEBERG_DEMO&quot;)<br>spark.sql(&quot;USE NAMESPACE ICB_SCHMA&quot;)<br><br>spark.sql(&quot;SELECT * FROM ICB_ORDERS&quot;).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*_3nbehUXq-aSr8Ukk9XxjQ.png" /></figure><h3>Step 6 — Write from Spark</h3><p>Here’s the half that actually distinguishes Horizon from a read-only federation setup. Spark writes into a table whose catalog, RBAC, and metadata lifecycle all belong to Snowflake:</p><pre>spark.sql(&quot;&quot;&quot;<br>INSERT INTO ICEBERG_DEMO.ICB_SCHMA.ICB_ORDERS<br>VALUES<br>(1001, &#39;Alice&#39;, 300),<br>(1002, &#39;Bob&#39;, 400)<br>&quot;&quot;&quot;)</pre><p>Now spark shows 4 rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*pA_2Cit9ah8o4h9WjDCeTQ.png" /></figure><p>Lets run the same query in snowflake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZPqMFu1uS-8lYNIS22NKQ.png" /></figure><p>Four rows. No refresh command, no metadata sync job, no polling. Spark’s commit went through Snowflake’s catalog, so the moment it succeeded the rows were queryable in Snowflake — and visible to Snowflake’s masking policies, row access policies, and time travel like any other row.</p><p>The key innovation is not Spark reading Iceberg tables, but Spark writing through Snowflake’s Horizon catalog while maintaining Snowflake governance, without shared long-lived credentials or data duplication.</p><p>This moves beyond traditional connector and pipeline approaches by separating compute choices from data ownership. Teams can use Spark for heavy transformations and Snowflake for governed analytics, while both operate on the same underlying table.</p><p>Found this useful? 👏 Clap it so that more people can find it, and follow me on <a href="https://www.linkedin.com/in/nsyed9/">Linkedin</a> for more content on data engineering and AI. See you there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bccab587b56b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake Migration Agent: Migrate in 5 Minutes (While Your Coffee Brews)]]></title>
            <link>https://medium.com/@nazeer.td/snowflake-migration-agent-migrate-in-5-minutes-while-your-coffee-brews-5d92be2ef580?source=rss-0a9bc48881dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d92be2ef580</guid>
            <category><![CDATA[snowflake-cortex]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[snowflake-migration]]></category>
            <category><![CDATA[snowflake-data-cloud]]></category>
            <dc:creator><![CDATA[Nazeer Syed]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 21:47:45 GMT</pubDate>
            <atom:updated>2026-07-07T05:31:42.748Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVBGI-HhUSjIrTT-eWNRhg.png" /></figure><blockquote>Hi Agent, can you migrate my tables and stored procedures from sql server to snowflake. By time you go and get your coffee, data and SP’s are in snowflake. I will show you how in this example.</blockquote><p>Database migrations are often one of the most complex and time-consuming phases of modernizing a data platform. Snowflake’s <strong>Migration Agent</strong>, built into Cortex Code, simplifies this process by using AI to automate and guide the migration workflow. In this blog, I’ll walk through an end-to-end migration from a SQL Server database containing <strong>10 tables and 5 stored procedures</strong> to Snowflake..</p><h3>1. Prerequisites and setup of Cortex Code</h3><p>Download Cortex Code from the link below, select the appropriate executable for your operating system, and ensure it is installed correctly on your local machine.</p><p><a href="https://www.snowflake.com/en/product/snowflake-coco/downloads/">https://www.snowflake.com/en/product/snowflake-coco/downloads/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PrQQGDinYWtkW44ryndTvw.png" /></figure><blockquote>Important Note: Cortex Code is not fully available in standard Snowflake free trial accounts, as some AI and agent-based features are restricted or require explicit enablement. Before starting the migration, ensure your Snowflake account has Cortex Code access enabled (or use a paid/approved trial), along with required compute and role permissions.</blockquote><h4>make sure you connected to paid snowflake account in cortex code.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LypCT514_-jCZpOx5ofpgA.png" /></figure><p><strong>Note:</strong> Since I am using a paid Snowflake account, Multi-Factor Authentication (MFA) is mandatory. I configured MFA using the Authenticator app in Snowsight, and when connecting to Cortex Code, I selected <strong>Local OAuth</strong> as the authentication method.</p><h4>2. Ensure SQL Server is installed and running locally, which will be used as the reference database for this migration example.</h4><p>The SQL Server database <strong>RetailDB</strong> consists of 10 tables and 5 stored procedures, with each table containing approximately 100 rows of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACVBv-EWMaKxTFoEDGhVjA.png" /></figure><h3>2. Verify connection in Cortex Code.</h3><p>Once the connection is successfully established in Cortex Code, verify it by querying the existing tables with simple test questions to ensure the connection is working correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*vqyG5_pDSeGwaq1wAcx6ww.png" /></figure><h3>3. Now Lets start the action</h3><p>I asked cortex code in simple and plain english and then it asked me to enter connection details</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*zC1_GR5q-q_jrAUg7PplXg.png" /></figure><p>I entered the following connection details in the command prompt. For security reasons, I have masked the password in the screenshot below.</p><pre>Host: localhost<br>Port: 1433<br>Database: RetailDB<br>Username: sa <br>Password: XXXXXXXXXXXXXX</pre><p>Once the connection is established in Cortex Code, the agent switches to planning mode, creates a 5 step plan and begins validating the required prerequisites. During this stage, it may prompt you to approve necessary actions or permissions to proceed.</p><p><strong>a. asking permission to install packages:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*YfNprR3wuYaPNbDPQJv9lg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fQWdDuA604eZKxvS42DGQ.png" /><figcaption>left side image is 5 step plan and right side image is asking for permission to install necessary package.</figcaption></figure><p><strong>b. Now it tries to establish a connection to sql server</strong></p><p>During this process, I encountered several challenges while enabling the cortex agent to connect to SQL Server. I used ChatGPT to troubleshoot and resolve these issues. Below are the issues I faced along with their solutions for reference. You may or may not encounter the same issues depending on your environment and configuration.</p><pre>Issue : Confusion Between Windows Login and SQL Login   -- Distinguished between Windows Authentication and SQL Server Authentication.<br>Issue : Original SQL Login Password Could Not Be Retrieved  --Reset the SQL login password instead of attempting to recover it.<br>Issue : SQL Server Connection Refused on Port 1433   -- Enabled TCP/IP networking and configured SQL Server to listen on port 1433.<br>Issue : SQL Server Configuration Manager Not Available  --Located the correct SQL Server instance (MSSQL17.MSSQLSERVER)<br>Issue : Registry Modification Failed  --Reopened PowerShell using Run as Administrator before making system-level configuration changes.<br>Issue : Login Failed (SQL Server Error 18456)  -- Enabled SQL Server and Windows Authentication Mode (Mixed Mode Authentication).</pre><p><strong>c. Converts SQL Server DDL scripts into Snowflake-compatible DDL and creates those table objects in Snowflake.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*GYdEb5CVJerJ-ayRs3nXfA.png" /></figure><p>Every time it will ask you permission to create table in snowflake. just click “allow”.</p><p><strong>d. Migrate data from SQL Server to snowflake.</strong></p><p>While migrating data from SQL Server to Snowflake, the agent encounters data type compatibility issues. It automatically identifies and resolves these differences, then successfully loads the data from SQL Server into Snowflake. Below is the screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*rm85mUxjZAeRBkdNhek_CA.png" /></figure><p><strong>e. Validation.</strong></p><p>Agent automatically validates data between sql server and snowflake by comparing the no of records</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*SgxttY334iEVTDoB0rfyMg.png" /></figure><p><strong>f. Verify the objects in snowflake.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8V_PKbluqRSXRqcYjQ9nQ.png" /></figure><p><strong>g. Now ask agent to migrate Stored procedures.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*dGQFHXLIHb2guNbou1HixQ.png" /></figure><p>While migrating stored procedures from SQL Server to Snowflake, the agent encounters several function and syntax compatibility issues. It automatically identifies and resolves these differences, then successfully converts and deploys the stored procedures in Snowflake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*fmKIvIs5i3vwcvroCDIdHg.png" /></figure><p><strong>h. verify the stored procedures in snowflake.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W8VgRzl1Z6fts7YK1nQHsg.png" /></figure><p>i. <strong>The python scripts which are created by agent are available in below workspace. we can refer the code from this workspace location.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlOZAfLl_tps-2waYOndtw.png" /></figure><p><strong>j.</strong> I asked the agent to generate an HTML report summarizing the migration, including the migration process, object conversion details, and execution results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*MRpK7CFn4otZNoOPdH5vkQ.png" /></figure><p>k. Here is the report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*no_hxEnmvgWMr7p3HHxO1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TeqivQpsQtnyNZkMtVgdyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UUMcRlInoGjDEHOaa1VFWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gAYJVxHAbQVDAZHmb5SBTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ub1uwDrNXAdZzoKiQ0KLUg.png" /></figure><h3>Conclusion:</h3><p>With AI agents performing migrations at unprecedented speed by automating analysis, code conversion, compatibility fixes, and data movement, the traditional migration lifecycle is rapidly changing. As these capabilities continue to evolve, the role of data engineers may shift from manually executing migration tasks to focusing more on architecture, validation, optimization, and strategic data solutions(<strong>honestly nothing much left to do for data engineers</strong>).</p><p>I used SQL Server for simplicity and ease of demonstration. however, the overall migration process remains the same for other supported databases.</p><blockquote>“Just ask — that’s it. The agent takes care of the rest.”</blockquote><p>Found this useful? 👏 Clap it so that more people can find it, and follow me on <a href="https://www.linkedin.com/in/nsyed9/">Linkedin</a> for more content on data engineering and AI. See you there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d92be2ef580" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>