<?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 Vivek Sunny on Medium]]></title>
        <description><![CDATA[Stories by Vivek Sunny on Medium]]></description>
        <link>https://medium.com/@viveksunny.sunny?source=rss-3e7d590131a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gSYz0QZEZnIhhj9t1ocvJA@2x.jpeg</url>
            <title>Stories by Vivek Sunny on Medium</title>
            <link>https://medium.com/@viveksunny.sunny?source=rss-3e7d590131a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:12:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@viveksunny.sunny/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[I tried Snowflake DCM Projects with GitHub. Here’s how it works, step by step]]></title>
            <link>https://medium.com/@viveksunny.sunny/i-tried-snowflake-dcm-projects-with-github-heres-how-it-works-step-by-step-0ab38879ea62?source=rss-3e7d590131a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ab38879ea62</guid>
            <category><![CDATA[sql-database]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Vivek Sunny]]></dc:creator>
            <pubDate>Sat, 05 Dec 2026 16:28:17 GMT</pubDate>
            <atom:updated>2026-12-05T16:28:17.331Z</atom:updated>
            <content:encoded><![CDATA[<h4>A small project, two versions in Git, and one notebook you can run on a free trial account</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxbAQIwFMBVMTpboS352Ng.jpeg" /></figure><p>A lot of Snowflake teams still ship changes as a folder of SQL scripts. V12__add_column.sql, V13__fix_grant.sql, and so on.</p><p>This works, but over time you start seeing problems:</p><ul><li>Someone changes a warehouse size in the UI, and nobody writes it down.</li><li>A script runs twice by mistake.</li><li>DEV and PROD stop matching, and nobody can say what is different.</li></ul><p>Snowflake has a feature for this called DCM Projects. I wanted to see how it works, so I built a small project, kept it in my GitHub, and deployed it into Snowflake directly from Git. Everything below, including the screenshots, comes from that run.</p><h3>What is a DCM Project?</h3><p>DCM means Database Change Management.</p><p>In the usual way, you write every step yourself: CREATE a table, ALTER a column, DROP a view.</p><p>With DCM, you only write what the end result should look like. You use DEFINE instead of CREATE:</p><pre>DEFINE TABLE MEETUP{{env_suffix}}.RAW.RSVPS (<br>  RSVP_ID     NUMBER,<br>  EVENT_ID    NUMBER,<br>  MEMBER_NAME VARCHAR,<br>  RSVP_TS     TIMESTAMP_NTZ,<br>  CHECKED_IN  BOOLEAN<br>);</pre><p>Snowflake compares your files with what is already in the account, and works out the CREATE, ALTER and DROP for you.</p><p>It has three steps:</p><ul><li><strong>Define:</strong> write what you want in SQL files</li><li><strong>Plan:</strong> Snowflake shows what it will change, without changing anything</li><li><strong>Deploy:</strong> Snowflake makes the changes</li></ul><p>If you have used Terraform, it is the same idea. The difference is that this is plain SQL, and it runs inside Snowflake.</p><h3>What I built</h3><p>A small “meetup” project with event and RSVP data (an RSVP is a person saying “I will come”):</p><ul><li>A warehouse, a database and two schemas</li><li>Two tables: EVENTS and RSVPS</li><li>A dynamic table that counts how many people actually came to each event</li><li>Two views on top of it</li><li>A read-only analyst role</li><li>Two data quality rules</li></ul><pre>meetup_ops/<br>├── manifest.yml               DEV and PROD settings<br>└── sources/definitions/<br>    ├── infrastructure.sql     warehouse, database, schemas<br>    ├── raw.sql                tables<br>    ├── analytics.sql          dynamic table + views<br>    ├── access.sql             analyst role + grants<br>    └── expectations.sql       data quality rules</pre><p>The manifest.yml file keeps the settings for each environment. DEV gets a _DEV suffix in the names and an X-Small warehouse. PROD gets no suffix and a Small warehouse. Both use the same SQL files.</p><p>In GitHub I created two tags (a tag is a name for a saved version):</p><ul><li>v1: the first version</li><li>v2: one commit later. It adds a column and a new view, and removes an old debug view.</li></ul><h3>Step 1: Connect Snowflake to GitHub</h3><p>My repo is public, so I didn’t need a password or token. I created one API integration, and then the repo became an object inside Snowflake:</p><pre>CREATE GIT REPOSITORY DCM_DEMO.PROJECTS.MEETUP_OPS_REPO<br>  API_INTEGRATION = GITHUB_DCM_DEMO<br>  ORIGIN = &#39;https://github.com/vivek8759/snowflake-dcm-projects-demo.git&#39;;</pre><p>Now Snowflake can read every branch and tag as a path, for example @MEETUP_OPS_REPO/tags/v1/meetup_ops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*451h6VXkc_iu5nVo.png" /><figcaption>Snowflake can see both tags, with the same commit IDs as GitHub.</figcaption></figure><p>I also created two DCM project objects, one for each environment: MEETUP_OPS_DEV and MEETUP_OPS_PROD. Both use the same files with different settings.</p><h3>Step 2: Plan before you deploy</h3><p>PLAN is a dry run. Snowflake reads the files, compares them with the account, and lists every change. Nothing is created yet.</p><pre>EXECUTE DCM PROJECT DCM_DEMO.PROJECTS.MEETUP_OPS_DEV<br>  PLAN<br>  USING CONFIGURATION DEV<br>  FROM &#39;@DCM_DEMO.PROJECTS.MEETUP_OPS_REPO/tags/v1/meetup_ops&#39;;</pre><p>The result comes back as JSON, which is hard to read. So I wrote a small Python helper in the notebook that turns it into a table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AwuABpNmjas5dQrS.png" /><figcaption>Version v1: 13 planned changes. Roles, a warehouse, the database, schemas, tables, a dynamic table and views.</figcaption></figure><p>When the plan looked right, I changed PLAN to DEPLOY AS &quot;v1 (git tag v1)&quot; and ran it again. This time the objects were created. The name in quotes is saved in the deploy history, like a commit message.</p><p>One note: DCM creates the structure (tables, views, roles). It does not load data. So I loaded some generated sample rows with a normal INSERT.</p><h3>Step 3: Ship v2 without writing a single ALTER</h3><p>The new question: <em>which RSVP channel (Meetup.com, LinkedIn or WhatsApp) brings people who actually come?</em></p><p>So in v2 I changed the files:</p><ul><li>Added an RSVP_SOURCE column to RSVPS</li><li>Added a new view, V_SHOW_UP_BY_CHANNEL, and gave the analyst role access to it</li><li>Deleted the old debug view</li></ul><p>The notebook reads both tags from GitHub and shows the difference, all inside Snowflake:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uJyJtGgQy67Jv9mn.png" /><figcaption>The difference between v1 and v2, read from GitHub inside Snowflake.</figcaption></figure><p>Then I ran PLAN for v2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ECEdZI0XmSPwhDbJ.png" /><figcaption>One ALTER TABLE, one CREATE VIEW, one DROP VIEW, and the grants. I didn’t write any of them.</figcaption></figure><p>This was my favourite part. <strong>I deleted a </strong><strong>DEFINE from the file, and DCM planned a </strong><strong>DROP for that view.</strong> With scripts, someone has to remember to write the drop. Here, if an object is no longer in Git, DCM removes it.</p><h3>Step 4: Someone changes things by hand</h3><p>This happens in every team. A query is slow, so someone opens the UI and makes the warehouse LARGE. Nothing changes in Git. This is called drift: the account no longer matches the code.</p><p>I did exactly that, and then ran PLAN again on main:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7dgN-pumb15UvOgK.png" /><figcaption>Git did not change, but the account did. The plan shows it: warehouse size Large → X-Small.</figcaption></figure><p>When I ran DEPLOY, the warehouse went back to X-Small, which is what Git says. This is why I would run a PLAN on PROD every day. It is a simple way to catch changes made by hand.</p><h3>Step 5: Same code, PROD settings</h3><p>PROD has its own project object. It deploys the main branch with the PROD settings:</p><pre>EXECUTE DCM PROJECT DCM_DEMO.PROJECTS.MEETUP_OPS_PROD<br>  DEPLOY AS &quot;prod: main&quot;<br>  USING CONFIGURATION PROD<br>  FROM &#39;@DCM_DEMO.PROJECTS.MEETUP_OPS_REPO/branches/main/meetup_ops&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RVmPUAc-hX2V540w.png" /><figcaption>Same files. DEV: X-Small warehouse with a _DEV suffix. PROD: Small warehouse, no suffix.</figcaption></figure><h3>Step 6: Data quality rules in Git</h3><p>The file expectations.sql adds two data quality checks to the RSVPS table, using Snowflake&#39;s built-in data metric functions:</p><pre>ATTACH DATA METRIC FUNCTION SNOWFLAKE.CORE.NULL_COUNT<br>  TO TABLE MEETUP{{env_suffix}}.RAW.RSVPS<br>  ON (MEMBER_NAME)<br>  EXPECTATION NO_ANONYMOUS_RSVPS (value = 0);</pre><p>Then I added two bad rows on purpose: one RSVP without a name, and one RSVP ID used twice. Then I ran EXECUTE DCM PROJECT ... TEST ALL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1RLkfXAQrAjfm4y3.png" /><figcaption>Both rules fail, as expected. You can run this check in CI before or after a deploy.</figcaption></figure><h3>Step 7: Deploy history</h3><p>Snowflake keeps a record of every deploy, with its name and the Git path it came from:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ONYa-z0rwSWZkg2_.png" /><figcaption>Each deploy shows the Git tag or branch it came from.</figcaption></figure><p>So when someone asks “who changed this, and from which version?”, one SHOW DEPLOYMENTS query gives the answer.</p><h3>Problems I hit, and how I fixed them</h3><ol><li><strong>A deploy name can be used only once per project.</strong> When I ran the notebook a second time, the deploy failed with “There is already a version exists with alias”. Clean up first, or add something unique to the name, like the commit ID.</li><li><strong>You need one project object per environment.</strong> One project object tracks one deployed state, so DEV and PROD each need their own.</li><li><strong>A project cannot define the database or schema it is stored in.</strong> I kept my project objects in a separate schema, DCM_DEMO.PROJECTS.</li><li><strong>Give account-level privileges first.</strong> The role that deploys needs CREATE DATABASE, CREATE WAREHOUSE, CREATE ROLE and the data metric grants before the first deploy.</li><li><strong>Tables with data quality rules need </strong><strong>DATA_METRIC_SCHEDULE.</strong> I used TRIGGER_ON_CHANGES, so the checks run when the data changes.</li><li><strong>Old tests leave objects behind.</strong> My first run deployed on top of objects from an older test. SHOW DEPLOYMENTS showed me the old deploys, and PURGE removed everything so I could start clean.</li></ol><h3>Where I would use it</h3><ul><li>Databases, roles and grants that today live in numbered scripts</li><li>Teams that want to see the plan in a pull request before anything changes</li><li>A daily PLAN on PROD, to catch changes made by hand</li></ul><p>It does not replace dbt or your data loading tools. It looks after the objects they run on.</p><h3>Try it yourself</h3><p>Everything is in one repo: <a href="https://github.com/vivek8759/snowflake-dcm-projects-demo"><strong>https://github.com/vivek8759/snowflake-dcm-projects-demo</strong></a></p><ol><li>In Snowsight, go to <strong>Workspaces → Add new → Upload files</strong> and upload notebooks/dcm_projects_meetup_ops.ipynb</li><li>Connect with the <strong>ACCOUNTADMIN</strong> role and the <strong>COMPUTE_WH</strong> warehouse</li><li>Run the cells from top to bottom. It works on a trial account, and the last cell cleans everything up</li></ol><p>Docs I used:</p><ul><li>DCM Projects overview: <a href="https://docs.snowflake.com/en/user-guide/dcm-projects/dcm-projects-overview">https://docs.snowflake.com/en/user-guide/dcm-projects/dcm-projects-overview</a></li><li>Project files and templates: <a href="https://docs.snowflake.com/en/user-guide/dcm-projects/dcm-projects-files">https://docs.snowflake.com/en/user-guide/dcm-projects/dcm-projects-files</a></li><li>EXECUTE DCM PROJECT: <a href="https://docs.snowflake.com/en/sql-reference/sql/execute-dcm-project">https://docs.snowflake.com/en/sql-reference/sql/execute-dcm-project</a></li><li>Snowflake Labs quickstarts: <a href="https://github.com/Snowflake-Labs/snowflake-dcm-projects">https://github.com/Snowflake-Labs/snowflake-dcm-projects</a></li></ul><p>How do you ship Snowflake changes in your team today? Numbered scripts, Terraform, or something else? Tell me in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ab38879ea62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlit in Snowflake vs App Runtime: What Actually Changes When You Move]]></title>
            <link>https://medium.com/@viveksunny.sunny/streamlit-in-snowflake-vs-app-runtime-what-actually-changes-when-you-move-41f8a75cf865?source=rss-3e7d590131a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/41f8a75cf865</guid>
            <category><![CDATA[snowflake-data-cloud]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Vivek Sunny]]></dc:creator>
            <pubDate>Sat, 05 Dec 2026 15:09:23 GMT</pubDate>
            <atom:updated>2026-12-05T15:09:23.514Z</atom:updated>
            <content:encoded><![CDATA[<h4>The old setup, the new setup, and the one login line that breaks everything</h4><p>If you’ve built a Streamlit app inside Snowflake, you’ve probably hit the moment where you want it to behave like a “real” web app. Proper links. Your own layout. A page you can share with one click.</p><p>That’s what Snowflake App Runtime is for. But moving to it changes more than the UI library, and it’s easy to get confused about what stays the same and what you now own.</p><p>Daan Bakboord recently moved one of his demos from Streamlit in Snowflake to App Runtime and documented every step. I’m using his migration as the example here, and I’ve kept this post to the question I get asked most: what was the problem with the old setup, and what’s different in the new one?</p><h3>The old setup: Streamlit in Snowflake</h3><p>Streamlit in Snowflake lets you write a data app in one Python file and run it right next to your data. No hosting, no credentials to manage.</p><p><strong>What makes it easy:</strong></p><ul><li>One file. Tabs, dropdowns, tables and charts come built in.</li><li>The connection is handed to you. One call, get_active_session(), and you&#39;re querying Snowflake.</li><li>Deploying is a stage plus CREATE STREAMLIT, and access is a GRANT USAGE ON STREAMLIT.</li></ul><p><strong>Where it starts to hurt:</strong></p><ul><li>You get Streamlit’s layout, not yours. That’s fine for dashboards and limiting for anything that should feel like a product.</li><li>App state lives inside the session. You can’t easily send someone a link to “this tab, this filter, this question”.</li><li>Every click reruns the script from the top.</li><li>The connection only works inside Snowflake, so running the same app on your laptop isn’t straightforward.</li></ul><p>None of this is a bug. Streamlit is Python-first by design. It just has a ceiling.</p><h3>The new setup: Snowflake App Runtime</h3><p>App Runtime lets you run a full web app inside Snowflake (Daan used Next.js). You push your code, Snowflake installs, builds and runs it next to the data, and people sign in through Snowflake.</p><p><strong>What you get:</strong></p><ul><li>Your own UI: real links, server-rendered pages, any layout you want.</li><li>Every state of the app can be a URL (for example ?tab=compare&amp;question=...), so it&#39;s easy to test, share and record.</li><li>The same code runs on your laptop (npm run dev) and in Snowflake.</li><li>One manifest file, app.yml, describes the install, build and run steps. Deploying is one command: snow app deploy.</li></ul><p><strong>What you now own:</strong></p><ul><li>The widgets. Tabs, pickers, tables and charts are yours to build.</li><li>The connection. There’s no get_active_session() any more. Your code reads the session token Snowflake provides and connects with it.</li><li>The permissions. More on that below.</li></ul><h3>Old vs new, side by side</h3><ul><li><strong>Code:</strong> one Python file → a small web project (pages, components, helpers)</li><li><strong>Connection:</strong> get_active_session() → your own code, using the session token Snowflake gives the app</li><li><strong>UI parts:</strong> st.tabs, st.selectbox, st.dataframe, st.bar_chart → links, forms, HTML tables, your own chart component</li><li><strong>App state:</strong> inside the Streamlit session → in the URL</li><li><strong>Rendering:</strong> the script reruns on every click → the page is rendered on the server per request</li><li><strong>Definition:</strong> CREATE STREAMLIT over a stage → an app.yml manifest</li><li><strong>Deploy:</strong> upload the file and run a SQL script → snow app deploy</li><li><strong>Access:</strong> GRANT USAGE ON STREAMLIT → GRANT USAGE ON APPLICATION SERVICE</li><li><strong>Local run:</strong> needs the Snowflake runtime → npm run dev with your local connection settings</li></ul><h3>The one line that breaks the login</h3><p>This is the part that will cost you an afternoon if nobody warns you.</p><p>In App Runtime, the app connects with an OAuth token that Snowflake hands it, and that token already says who the app is. Daan’s connection code also passed a username, and when none was set it fell back to a placeholder. Snowflake compared the two, saw they didn’t match, and refused every query with a “user doesn’t match the token” error.</p><p>Worse, the app’s own error message said to re-run the setup scripts, which pointed him in the wrong direction.</p><p>The fix: when you connect with the token, don’t send a username.</p><pre>// Connecting inside App Runtime<br>options.authenticator = &quot;OAUTH&quot;;<br>options.token = token;<br>// No options.username here: the token already carries the identity</pre><p>In Streamlit, get_active_session() hid all of this. In App Runtime the login is your code, so check it before you trust any error message around it.</p><h3>Signing in is not the same as “runs as me”</h3><p>This one is easy to miss. A viewer signing in to the app does not mean their queries run with their permissions. In Daan’s demo, the queries ran as the app’s own service identity.</p><p>If different users should see different data, choose that explicitly (owner’s rights vs caller’s rights) and grant what caller’s rights need. Decide it on day one, not after someone sees a number they shouldn’t.</p><h3>The real lesson: keep business logic out of the app</h3><p>Daan’s demo compares revenue with and without a semantic view. After the move, every number matched the Streamlit version exactly.</p><p>Why? The metric definitions lived in a Snowflake semantic view, not in the Python code. So he could throw away the whole interface and rebuild it without touching what “revenue” means.</p><p>If your definitions live inside your Streamlit file, a migration means porting business logic too. That’s where numbers quietly change.</p><h3>So, should you move?</h3><p><strong>Stay on Streamlit if:</strong></p><ul><li>It’s an internal dashboard or a quick prototype</li><li>Python widgets already do the job</li><li>You don’t want to own a front end</li></ul><p><strong>Move to App Runtime if:</strong></p><ul><li>You need a custom UI, real routing or shareable links</li><li>It’s turning into a product people use, not just a dashboard</li><li>Your team is comfortable owning a web app</li></ul><p><strong>Before you switch:</strong></p><ol><li>Move metric definitions into a semantic view first.</li><li>Budget time to rebuild the widgets.</li><li>Connect with the session token only, and decide whose permissions your queries run under.</li><li>Put app state in the URL.</li><li>Keep the Streamlit version running until both give the same answers.</li></ol><h3>Quick summary</h3><p><strong>Streamlit in Snowflake:</strong> quick, Python-only, and the layout and login are handled for you.</p><p><strong>App Runtime:</strong> a full web app inside Snowflake’s security boundary, but the UI, the connection and the permissions are now yours.</p><p>The data and the definitions stay where they are. Only the app around them changes.</p><p>Thanks to Daan Bakboord for the detailed write-up. His full walkthrough, with the code and the complete app.yml, is here: <a href="https://www.daanalytics.nl/from-streamlit-in-snowflake-to-snowflake-app-runtime/">From Streamlit in Snowflake to Snowflake App Runtime</a></p><p>Have you moved a Streamlit app yet, or are you waiting? What’s holding you back?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41f8a75cf865" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Local Services Marketplace on Snowflake with Next.js]]></title>
            <link>https://medium.com/@viveksunny.sunny/i-built-a-local-services-marketplace-that-runs-entirely-inside-snowflake-7e5f9135a970?source=rss-3e7d590131a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e5f9135a970</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[snowpark]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Vivek Sunny]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 07:17:11 GMT</pubDate>
            <atom:updated>2026-12-01T07:45:35.414Z</atom:updated>
            <content:encoded><![CDATA[<h4>Birpur Sewa: a Next.js app where users, listings and bookings all live in Snowflake</h4><p>Most of my Snowflake work happens behind a dashboard: pipelines, governance, Cortex agents for analysts. This time I wanted to see how far Snowflake can go as the backbone of a real consumer app.</p><p>So I built <strong>Birpur Sewa</strong>, a local services marketplace for the town of Birpur. People can find trusted carpenters, delivery, transport, repair and more, book them, and track the booking. Service providers list what they offer, and an admin approves listings before they go live. Real customers and providers use it today.</p><p>The code is public here: <a href="https://github.com/vivek8759/birpur-sewa-snowflake-app">github.com/vivek8759/birpur-sewa-snowflake-app</a></p><p><em>Note: the live site (birpur-sewa.vercel.app) is under maintenance while I roll out a new version, so some features may be unavailable for a few days.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d49h870pgnixCqDipxksdw.png" /><figcaption>The home page in Hindi</figcaption></figure><h3>What the app does</h3><ul><li><strong>Public browsing:</strong> anyone can search services by name, category and city.</li><li><strong>Registration without a Snowflake account:</strong> customers and providers sign up inside the app, with a 6-digit email code to verify the address.</li><li><strong>Approval workflow:</strong> providers list services, and an admin approves them.</li><li><strong>Bookings with a lifecycle:</strong> customers request a service, and providers accept, reject or complete it. Customers can cancel or reschedule.</li><li><strong>Role-based dashboards</strong> for admins, providers and customers.</li><li><strong>Hindi and English</strong> throughout. Service titles and descriptions are stored in both languages in Snowflake (TITLE_HI, DESCRIPTION_HI).</li><li><strong>Dark mode</strong> that follows the phone’s setting.</li></ul><p>Under the hood that is 10 pages and 27 API routes in one Next.js project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*T2FEwJQc-TJOCKpqw64eMg.png" /><figcaption>Customers and service providers sign up inside the app, no Snowflake account needed</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*4ECBV2DXWEbnY5NQCsa7gA.png" /><figcaption>How it works: providers list services, an admin approves them, customers book</figcaption></figure><h3>The architecture in one picture</h3><ul><li><strong>Frontend and API:</strong> Next.js 16 (App Router), React 19 and Tailwind CSS.</li><li><strong>Runtime:</strong> the live site runs on Vercel. The same codebase is also set up as a Snowflake App (app.yml + snow app deploy), so it can run on Snowpark Container Services inside Snowflake.</li><li><strong>Data:</strong> everything is in one schema, BIRPUR_SEWA.PUBLIC: USERS, SERVICES, BOOKINGS, OTP_CODES, FEEDBACK, LOGIN_AUDIT, NOTIFICATIONS and LEADS.</li><li><strong>Compute:</strong> an XSMALL warehouse with a 60-second auto-suspend, which is plenty for a town-sized app and keeps the bill tiny.</li><li><strong>App users vs Snowflake users:</strong> people who use the app never get a Snowflake login. The app keeps its own USERS table, hashes passwords with bcrypt and issues signed session tokens. Snowflake access happens only on the server.</li></ul><h3>Deploying a Next.js app to Snowflake</h3><p>To run it inside Snowflake as a Snowflake App, the whole build and run setup is one small app.yml:</p><pre>install:<br>  commands:<br>    - [&quot;npm&quot;, &quot;ci&quot;, &quot;--include=dev&quot;]</pre><pre>build:<br>  commands:<br>    - [&quot;npm&quot;, &quot;run&quot;, &quot;build&quot;]<br>    - [&quot;cp&quot;, &quot;-r&quot;, &quot;.next/static&quot;, &quot;.next/standalone/.next/static&quot;]<br>    - [&quot;cp&quot;, &quot;-r&quot;, &quot;public&quot;, &quot;.next/standalone/public&quot;]<br>    - [&quot;rm&quot;, &quot;-rf&quot;, &quot;node_modules&quot;]</pre><pre>run:<br>  command: [&quot;node&quot;, &quot;.next/standalone/server.js&quot;]</pre><p>Next.js builds in standalone mode, so the container only carries the server and the files it actually needs. After that, the loop is:</p><pre>snow app deploy   # build and deploy the application service<br>snow app events   # stream deployment events and logs<br>snow app open     # open the app in the browser</pre><h3>Talking to Snowflake from Next.js</h3><p>All database access goes through one helper, querySnowflake. Every value a user types goes in as a bind variable, never as part of the SQL string:</p><pre>const rows = await querySnowflake(<br>  &quot;SELECT * FROM BIRPUR_SEWA.PUBLIC.SERVICES WHERE STATUS = &#39;approved&#39; AND CATEGORY = ? AND CITY = ?&quot;,<br>  { binds: [category, city] },<br>)</pre><p>The helper also picks the right authentication on its own:</p><ol><li><strong>As a Snowflake App</strong>, it reads the short-lived service token that Snowpark Container Services mounts at /snowflake/session/token. No passwords or keys live in the app.</li><li><strong>On Vercel and in local development</strong>, it falls back to environment variables or the default connection in ~/.snowflake/config.toml.</li></ol><p>It keeps a connection pool and rebuilds it when the service token rotates. For heavy work there is a long-running variant that submits the query asynchronously and polls for the result instead of holding a request open.</p><h3>Vercel today, a Snowflake App next</h3><p>The live site runs on Vercel with Snowflake as the backend. That works, but it means managing a service user, an RSA key pair and a set of environment variables outside Snowflake.</p><p>Running the same code as a Snowflake App removes most of that. The app gets its identity from the platform, the data never leaves the account, and governance, auditing and cost all live in one place. That is the move I am making next.</p><h3>What I learned</h3><ol><li><strong>Keep secrets out of the deploy file.</strong> It is tempting to put an app secret straight into app.yml. Don&#39;t. Store it as a Snowflake SECRET, declare it in app.yml and read it at runtime. I learned this one the hard way.</li><li><strong>Give the app its own small role.</strong> Grant it only the warehouse and schema it needs, not an admin role.</li><li><strong>Pin the Next.js 16 project root.</strong> Next.js 16 with Turbopack walks up the folders looking for a lockfile and can silently re-root the project. Symptoms: / returns 404 and chunk URLs get the wrong prefix. Setting outputFileTracingRoot (and turbopack.root) to the app&#39;s own folder fixed it for good.</li><li><strong>Use bind variables everywhere.</strong> One helper that only accepts binds removes a whole class of SQL injection bugs.</li><li><strong>Treat a public app like a production system.</strong> I added rate limits on login, admin login and registration, an audit table for logins, and email verification before anyone can register.</li></ol><h3>Try it yourself</h3><pre>git clone https://github.com/vivek8759/birpur-sewa-snowflake-app<br>cd birpur-sewa-snowflake-app<br>npm install<br>npm run dev     # needs a Snowflake connection in ~/.snowflake/config.toml<br>snow app deploy</pre><p>Snowflake Apps make the platform a place to build and run whole products, not just store their data. If you are building one, or thinking about it, I would love to hear what you are making. Find me on <a href="https://www.linkedin.com/in/vivek-sunny-vs/">LinkedIn</a>.</p><p><em>I lead the Snowflake practice at ThoughtFocus and spoke on Apache Iceberg at the Snowflake Bengaluru user group this year. Views are my own.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e5f9135a970" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Guide to Snowflake FLATTEN: JSON, Arrays, LATERAL Joins, and Real Examples]]></title>
            <link>https://medium.com/@viveksunny.sunny/the-ultimate-guide-to-snowflake-flatten-json-arrays-lateral-joins-and-real-examples-e1bfcbd15ef9?source=rss-3e7d590131a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1bfcbd15ef9</guid>
            <category><![CDATA[semi-structured-data]]></category>
            <category><![CDATA[snowflake-data-ingestion]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[snowflake-lateral-flatten]]></category>
            <dc:creator><![CDATA[Vivek Sunny]]></dc:creator>
            <pubDate>Sat, 06 Dec 2025 08:30:11 GMT</pubDate>
            <atom:updated>2025-12-06T08:45:24.657Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Nla5GpoFaI5QLK6l" /><figcaption>Photo by <a href="https://unsplash.com/@uxindo?utm_source=medium&amp;utm_medium=referral">UX Indonesia</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Agenda for the Blog: “Snowflake FLATTEN Explained: A Complete Beginner-to-Advanced Guide”</h3><h3>1. Introduction</h3><ul><li>What is semi-structured data (JSON/ARRAY/OBJECT)?</li><li>Why Snowflake provides the FLATTEN function.</li><li>What this blog will teach you (beginner → advanced).</li></ul><h3>2. What Is Snowflake FLATTEN?</h3><ul><li>Simple definition in plain English.</li><li>Why FLATTEN is needed when working with arrays or nested data.</li></ul><h3>3. Understanding LATERAL</h3><ul><li>What LATERAL means.</li><li>Why FLATTEN must be used with LATERAL.</li><li>Very simple illustration of row-by-row expansion.</li></ul><h3>4. How FLATTEN Works Internally (Explained Simply)</h3><ul><li>One input row → multiple output rows (like cross join behavior).</li><li>Explanation of FLATTEN output columns (value, index, key, etc.).</li><li>Visual breakdown.</li></ul><h3>5. Basic FLATTEN Example (Employee Dataset)</h3><ul><li>Employee table with JSON skills.</li><li>Convert JSON array into rows using FLATTEN.</li><li>Beginner output and explanation.</li></ul><h3>6. Advanced FLATTEN Options</h3><p>A complete breakdown of the FLATTEN parameters with tiny examples:</p><h4>6.1 OUTER</h4><ul><li>What it does.</li><li>When to use it.</li><li>Example with empty array.</li></ul><h4>6.2 PATH</h4><ul><li>Flattening only specific nested elements.</li><li>Simple example drilling into JSON structure.</li></ul><h4>6.3 MODE (ARRAY / OBJECT / BOTH)</h4><ul><li>Handling objects vs arrays.</li><li>Examples of each mode.</li></ul><h4>6.4 RECURSIVE</h4><ul><li>Flattening deeply nested JSON.</li><li>When recursive mode is useful.</li><li>Tiny example for clarity.</li></ul><h3>8. Common Mistakes and Best Practices</h3><ul><li>Forgetting LATERAL</li><li>Using FLATTEN before filtering → huge row explosion</li><li>When NOT to use recursive flatten</li><li>Optimizing queries with filters</li></ul><h3>9. Complete End-to-End Example</h3><ul><li>A full query showing:</li><li>LATERAL</li><li>PATH</li><li>OUTER</li><li>MODE</li><li>Recursive</li><li>Step-by-step explanation.</li></ul><h3>1. Introduction</h3><blockquote><em>Semi-structured data like JSON is everywhere — API responses, logs, events, and NoSQL exports. Snowflake’s FLATTEN function makes it incredibly easy to transform these complex structures into clean, analyzable tables. In this blog, we’ll start with the absolute basics of FLATTEN and gradually move all the way to advanced topics like PATH, OUTER, MODE, RECURSIVE, and LATERAL. Every concept is explained with small, easy examples so anyone — from beginner to experienced developer — can understand and apply FLATTEN confidently.</em></blockquote><ul><li><strong>What is semi-structured data (JSON/ARRAY/OBJECT)?</strong></li></ul><p>Semi-structured data(<strong>JSON/ARRAY/OBJECT)</strong> is data that does not reside in a traditional relational database (like SQL) but still has some organizational properties, such as tags or markers, that make it easier to analyze than completely unstructured data.</p><ul><li><strong>Why Snowflake provides the FLATTEN function.</strong></li></ul><p>Semi-structured data often contains arrays like this:</p><blockquote>{</blockquote><blockquote>“name”: “Alice”,</blockquote><blockquote>“skills”: [ “SQL”, “Python”, “Snowflake” ]</blockquote><blockquote>}</blockquote><p>A normal SQL query cannot loop through an array.<br> FLATTEN <strong>explodes</strong> the array into multiple rows so you can work with it like a table.</p><p>This makes querying semi-structured data <strong>simple and SQL-friendly</strong>.</p><ul><li><strong>What this blog will teach you (beginner → advanced).</strong></li></ul><p>This blog is designed to take you from <strong>zero to expert</strong> in understanding and using the FLATTEN function in Snowflake. Whether you are just starting with JSON data or want to master advanced nested structures, this guide walks you through each step with clear explanations and simple examples.</p><h3>2. What Is Snowflake FLATTEN?</h3><h4>Simple definition in plain English.</h4><p>Suppose you have this JSON for an employee:</p><blockquote>{</blockquote><blockquote>“name”: “Alice”,</blockquote><blockquote>“skills”: [ “SQL”, “Python”, “Snowflake” ]</blockquote><blockquote>}</blockquote><p>The skills field is an <strong>array</strong> (a list of values).</p><p>SQL cannot natively loop through lists, so Snowflake provides <strong>FLATTEN</strong>.</p><blockquote><strong><em>FLATTEN takes a list (like </em></strong><strong><em>skills) inside JSON and produces one row for each item in that list.</em></strong></blockquote><p>Before Flatten —</p><p>name skills Alice [“SQL”, “Python”, “Snowflake”]</p><blockquote>After Flatten —</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*UOTrS20qCJ4XsCbDRs5lig.png" /><figcaption>FLATTEN turns each skill into a <strong>separate row</strong>:</figcaption></figure><h4>Why FLATTEN is needed when working with arrays or nested data.</h4><p>Modern JSON data often contains <strong>arrays</strong> — lists of values — or <strong>nested structures</strong>.<br>SQL, however, is designed to work with <strong>rows and columns</strong>, not lists inside a single cell.</p><h3>3. Understanding LATERAL</h3><h3>What LATERAL means.</h3><p>LATERAL allows a table function — like <strong>FLATTEN</strong> — to use columns from the row that comes before it in the FROM clause.</p><blockquote><strong><em>LATERAL means: “For each row on the left, run the function on the right using that row’s data.”</em></strong></blockquote><p>Without LATERAL, Snowflake would not know which row’s JSON to flatten.</p><h3>Why LATERAL Is Needed</h3><p>Let’s use our example JSON:</p><blockquote>{<br> “name”: “Alice”,<br> “skills”: [“SQL”, “Python”, “Snowflake”]<br>}</blockquote><p>when you run —</p><p>FROM employees,<br> LATERAL FLATTEN(input =&gt; emp_data:skills)</p><p>Snowflake does this:</p><ul><li>Take <strong>one row</strong> from employees</li><li>Look at its emp_data:skills array</li><li>Produce <strong>multiple rows</strong> (one per skill)</li><li>Attach those rows <strong>back to the original row</strong></li></ul><p>Simple analogy —</p><p>Imagine you have a list of employees, and for each employee you want to open their “skills list” and read it.</p><blockquote><em>LATERAL</em> is like saying:</blockquote><blockquote><em>“For every employee, please run this function that looks inside their skills list.”</em></blockquote><p>Without LATERAL, the function cannot access the employee’s row.</p><ul><li>Why FLATTEN must be used with LATERAL.</li><li>Very simple illustration of row-by-row expansion.</li></ul><h3>Why FLATTEN must be used with LATERAL.</h3><p>Snowflake’s <strong>FLATTEN</strong> function is a <em>table function</em> — meaning it returns <strong>multiple rows</strong>, not just a single value. Because of this, FLATTEN needs to know <strong>which row of the main table it is expanding</strong>.</p><p>This is where <strong>LATERAL</strong> comes in.</p><blockquote>LATERAL allows FLATTEN to look inside each row’s JSON and expand the array for that specific row.</blockquote><p>Without LATERAL, FLATTEN cannot reference columns from the table on the left (like emp_data), so it would have <strong>nothing to flatten</strong>.</p><blockquote><em>FROM employees,<br> LATERAL FLATTEN(input =&gt; emp_data:skills)</em></blockquote><p>If you try to run FLATTEN without LATERAL:</p><ul><li>It cannot access emp_data</li><li>It cannot link results to the employee row</li><li>You will get errors or empty results</li></ul><h3>With LATERAL (explicit)</h3><pre>SELECT <br>    emp_id,<br>    f.value::string AS skill<br>FROM employees e,<br>     LATERAL FLATTEN(input =&gt; e.emp_data:skills) f;</pre><figure><img alt="For each row in employees, Snowflake looks at e.emp_data:skills. It explodes the array into one row per skill." src="https://cdn-images-1.medium.com/max/628/1*ADyVdoCDnT0CiLZlv-_fdA.png" /><figcaption>For each row in employees, Snowflake looks at e.emp_data:skills.It explodes the array into one row per skill.</figcaption></figure><h3>Without LATERAL keyword (Snowflake-specific behavior)</h3><p>In Snowflake, you can write the <em>same</em> query <strong>without writing the word </strong><strong>LATERAL</strong>, and it still works:</p><pre>SELECT <br>    emp_id,<br>    f.value::string AS skill<br>FROM employees e,<br>     FLATTEN(input =&gt; e.emp_data:skills) f;</pre><p>In some environments (especially <strong>Snowflake Notebooks</strong>), you may get an error like:</p><pre>NotebookSqlException: 001003: SQL compilation error: <br>syntax error line 5 at position 12 unexpected &#39;(&#39;.</pre><p>This happens because:</p><ul><li>The parser sees FLATTEN(input =&gt; e.emp_data:skills)</li><li>It notices you are referencing e.emp_data (a column from the left table)</li><li>But you <strong>did not</strong> specify LATERAL</li><li>So it doesn’t treat FLATTEN as a correlated table function and fails on the (</li></ul><p>Here is a <strong>very simple, super beginner-friendly illustration</strong> of <strong>row-by-row expansion</strong> that you can paste directly into your blog.</p><h3>Very Simple Illustration of Row-by-Row Expansion (How FLATTEN Works)</h3><p>Think of the employees table like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*gwmfftTtV8zkdw51stiyVg.png" /><figcaption>employees table</figcaption></figure><p>The skills column contains <strong>3 items</strong>, but Snowflake sees this as <strong>one row</strong>.</p><p>When we use:</p><pre>LATERAL FLATTEN(input =&gt; emp_data:skills)</pre><p>Snowflake processes rows <strong>one at a time</strong>:</p><h3>Step 1: Take the first row</h3><pre>emp_id = 101<br>skills = [&quot;SQL&quot;, &quot;Python&quot;, &quot;Snowflake&quot;]</pre><h3>Step 2: Open the array and pull out each item</h3><pre>SQL<br>Python<br>Snowflake</pre><h3>Step 3: Create one new row for each item</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*VBblG6rGxdF_yAnGTphc3A.png" /><figcaption>emp_id 101 is cross-joined with the values returned by FLATTEN for that employee’s skills array.</figcaption></figure><h3>4. How FLATTEN Works Internally (Explained Simply)</h3><p>At its core, Snowflake’s FLATTEN function takes <strong>one input row</strong> that contains an array or nested JSON and turns it into <strong>multiple output rows</strong> — one for each element inside that structure.</p><p>Think of FLATTEN as a tiny “machine” that expands nested values into a regular table format.</p><h3>5. Basic FLATTEN Example (Employee Dataset)</h3><h3>1. One Input Row → Multiple Output Rows</h3><p>Suppose a row contains this JSON:</p><pre>{<br>  &quot;name&quot;: &quot;Alice&quot;,<br>  &quot;skills&quot;: [&quot;SQL&quot;, &quot;Python&quot;, &quot;Snowflake&quot;]<br>}</pre><p>Inside Snowflake:</p><ul><li>FLATTEN opens the array</li><li>Extracts each item</li><li>Creates <strong>one new row per item</strong></li></ul><p>So one row:</p><blockquote>emp_id skills</blockquote><blockquote>101 [“SQL”, “Python”, “Snowflake”]</blockquote><p>Becomes three rows:</p><blockquote>emp_id skill</blockquote><blockquote>101 SQL</blockquote><blockquote>101 Python</blockquote><blockquote>101 Snowflake</blockquote><p>This is similar to a <strong>cross join</strong> between:</p><ul><li>the employee row</li><li>the flattened array values</li></ul><p>But importantly:<br> it happens <strong>one row at a time</strong>, thanks to the <strong>LATERAL</strong> keyword.</p><h3>2. FLATTEN Returns a Table of Columns</h3><p>FLATTEN is a <strong>table function</strong>, meaning it returns a set of rows with several helpful columns.</p><p>When you run:</p><pre>SELECT <br>    emp_id,<br>    f.value::string AS skill<br>FROM employees e,<br>     FLATTEN(input =&gt; e.emp_data:skills) f;</pre><p>You get columns like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LyCHdUTwvlDYhRZxiZO91w.png" /><figcaption>Output of above query</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*L2Jl-Wx2OWbenO6xWhrKaA.png" /></figure><p>These columns allow you to:</p><ul><li>Select values</li><li>Preserve order</li><li>Extract nested fields</li><li>Debug or explore JSON structure</li></ul><p>Most of the time, you only need:</p><pre>f.value</pre><p>But understanding all columns helps when working with complex JSON.</p><h3>Visual Breakdown (Super Simple)</h3><h3>Input row</h3><pre>Row:<br>emp_id = 101<br>skills = [&quot;SQL&quot;, &quot;Python&quot;, &quot;Snowflake&quot;]</pre><h3>Step 1: FLATTEN reads the array</h3><pre>[&quot;SQL&quot;, &quot;Python&quot;, &quot;Snowflake&quot;]</pre><h3>Step 2: FLATTEN produces a mini table</h3><p>indexvalue0SQL1Python2Snowflake</p><h3>Step 3: Snowflake cross joins the mini table with the original row</h3><pre>(101, SQL)<br>(101, Python)<br>(101, Snowflake)</pre><h3>Final Output</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*wj2HCW9tcH4kf_hN2-kcvA.png" /><figcaption>final output</figcaption></figure><h3>6.1 OUTER</h3><h3>What OUTER Does</h3><p>By default, if the array you’re flattening is <strong>empty</strong>, FLATTEN returns <strong>no rows</strong> for that record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*H3VGOvKY3WI1wtRD40Nv_w.png" /><figcaption>base table employees</figcaption></figure><ul><li>Alice: [&quot;SQL&quot;,&quot;Python&quot;,&quot;Snowflake&quot;] → 3 rows</li><li>Bob: [&quot;Excel&quot;,&quot;Power BI&quot;] → 2 rows</li><li>Carol: [] → <strong>0 rows</strong> (disappears)</li></ul><p>OUTER =&gt; TRUE ensures that <strong>even if the array is empty</strong>, Snowflake still returns <strong>one row</strong> — with NULL in the flattened value.</p><p>In simple terms:</p><blockquote><strong><em>OUTER keeps the original row even when there’s nothing to flatten.</em></strong></blockquote><h3>When to Use OUTER</h3><p>Use OUTER =&gt; TRUE when:</p><ul><li>You want to <strong>keep all employees</strong>, even if they have no skills yet.</li><li>You’re doing a <strong>LEFT-like behavior</strong>: “show me everyone, plus their skills if they have them.”</li><li>You want to easily spot <strong>missing or empty values</strong> (e.g., skills not assigned).</li></ul><h3>Example With Empty Array (Carol)</h3><p>Recall your table:</p><pre>CREATE OR REPLACE TABLE employees AS<br>SELECT <br>    column1 AS emp_id,<br>    PARSE_JSON(column2) AS emp_data<br>FROM VALUES<br>    (101, &#39;{&quot;name&quot;: &quot;Alice&quot;, &quot;skills&quot;: [&quot;SQL&quot;, &quot;Python&quot;, &quot;Snowflake&quot;]}&#39;),<br>    (102, &#39;{&quot;name&quot;: &quot;Bob&quot;,   &quot;skills&quot;: [&quot;Excel&quot;, &quot;Power BI&quot;]}&#39;),<br>    (103, &#39;{&quot;name&quot;: &quot;Carol&quot;, &quot;skills&quot;: []}&#39;);</pre><h4>Without OUTER</h4><pre>SELECT <br>    e.emp_id,<br>    f.value::string AS skill<br>FROM employees e,<br>     LATERAL FLATTEN(input =&gt; e.emp_data:skills) f;</pre><p><strong>Result:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*jbfKndysTE3O1Q_s6CR94w.png" /><figcaption>without outer Carol (103) is <strong>missing</strong>.</figcaption></figure><h4>With OUTER</h4><pre>SELECT <br>    e.emp_id,<br>    f.value::string AS skill<br>FROM employees e,<br>     LATERAL FLATTEN(<br>         input =&gt; e.emp_data:skills,<br>         OUTER =&gt; TRUE<br>     ) f;</pre><p><strong>Result:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*coD9FVjw3Z_1IRQQZbCmbw.png" /><figcaption>Now Carol is included with NULL skill because her array is empty.</figcaption></figure><h3>6.2 PATH</h3><h3>Flattening Only Specific Nested Elements</h3><p>PATH lets you tell FLATTEN:</p><blockquote><em>“Don’t flatten everything. Go to this specific nested location and flatten </em><strong><em>only that</em></strong><em>.”</em></blockquote><p>To illustrate this using your employee-style example, let’s extend the JSON slightly to include <strong>projects</strong>:</p><pre>CREATE OR REPLACE TABLE employees_projects AS<br>SELECT <br>    column1 AS emp_id,<br>    PARSE_JSON(column2) AS emp_data<br>FROM VALUES<br>    (101, &#39;{<br>      &quot;name&quot;: &quot;Alice&quot;,<br>      &quot;skills&quot;: [&quot;SQL&quot;, &quot;Python&quot;, &quot;Snowflake&quot;],<br>      &quot;projects&quot;: {<br>        &quot;current&quot;: [&quot;Billing System&quot;, &quot;Data Warehouse&quot;],<br>        &quot;past&quot;: [&quot;Reporting Portal&quot;]<br>      }<br>    }&#39;),<br>    (102, &#39;{<br>      &quot;name&quot;: &quot;Bob&quot;,<br>      &quot;skills&quot;: [&quot;Excel&quot;, &quot;Power BI&quot;],<br>      &quot;projects&quot;: {<br>        &quot;current&quot;: [&quot;Dashboard Migration&quot;],<br>        &quot;past&quot;: []<br>      }<br>    }&#39;);</pre><p>We now have JSON like:</p><pre>{<br>  &quot;name&quot;: &quot;Alice&quot;,<br>  &quot;projects&quot;: {<br>    &quot;current&quot;: [<br>      &quot;Billing System&quot;,<br>      &quot;Data Warehouse&quot;<br>    ],<br>    &quot;past&quot;: [<br>      &quot;Reporting Portal&quot;<br>    ]<br>  },<br>  &quot;skills&quot;: [<br>    &quot;SQL&quot;,<br>    &quot;Python&quot;,<br>    &quot;Snowflake&quot;<br>  ]<br>}</pre><h3>Example: Flatten Only projects.current</h3><pre>SELECT<br>    emp_id,<br>    f.value::string AS current_project<br>FROM employees_projects e,<br>     LATERAL FLATTEN(<br>         input =&gt; e.emp_data,<br>         path  =&gt; &#39;projects.current&#39;<br>     ) f;</pre><p><strong>What PATH does:</strong></p><ul><li>input =&gt; e.emp_data says: start from the whole JSON</li><li>path =&gt; &#39;projects.current&#39; says: go <strong>inside</strong> projects.current and flatten <strong>that array only</strong></li></ul><p><strong>Result:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*4jYTOApVKstL5QzaxQ98pQ.png" /><figcaption>You’re avoiding everything else (skills, projects.past, etc.) and targeting <strong>only one nested array</strong>.</figcaption></figure><h3>6.3 MODE (ARRAY / OBJECT / BOTH)</h3><p>MODE tells FLATTEN what kind of things to flatten:</p><ul><li>MODE =&gt; &#39;ARRAY&#39; → flatten array elements</li><li>MODE =&gt; &#39;OBJECT&#39; → flatten object key/value pairs</li><li>MODE =&gt; &#39;BOTH&#39; → handle both at the top level</li></ul><h3>Handling Objects vs Arrays</h3><p>Let’s create an example using your employee theme.</p><pre>CREATE OR REPLACE TABLE employees_details AS<br>SELECT <br>    column1 AS emp_id,<br>    PARSE_JSON(column2) AS emp_data<br>FROM VALUES<br>    (101, &#39;{<br>      &quot;name&quot;: &quot;Alice&quot;,<br>      &quot;skills&quot;: [&quot;SQL&quot;, &quot;Python&quot;],<br>      &quot;ratings&quot;: { &quot;2023&quot;: 4.5, &quot;2024&quot;: 4.8 }<br>    }&#39;),<br>    (102, &#39;{<br>      &quot;name&quot;: &quot;Bob&quot;,<br>      &quot;skills&quot;: [&quot;Excel&quot;],<br>      &quot;ratings&quot;: { &quot;2023&quot;: 4.0 }<br>    }&#39;);</pre><p>Now we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*S5cSHKirSSLDl2wWOlTrBA.png" /><figcaption>v</figcaption></figure><ul><li>skills → an <strong>array</strong></li><li>ratings → an <strong>object</strong> (key/value pairs)</li></ul><h3>MODE = ‘ARRAY’</h3><p>Flatten the skills array:</p><pre>SELECT<br>    emp_id,<br>    f.value::string AS skill<br>FROM employees_details e,<br>     LATERAL FLATTEN(<br>         input =&gt; e.emp_data:skills,<br>         MODE  =&gt; &#39;ARRAY&#39;<br>     ) f;</pre><p><strong>Result:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*VwR_XrMvmASIkFoRIZpaKg.png" /><figcaption>Mode =&gt; ‘ARRAY’</figcaption></figure><h3>MODE = ‘OBJECT’</h3><p>Flatten the ratings object (keys and values):</p><pre>SELECT<br>    emp_id,<br>    f.key::string   AS year,<br>    f.value::number AS rating<br>FROM employees_details e,<br>     LATERAL FLATTEN(<br>         input =&gt; e.emp_data:ratings,<br>         MODE  =&gt; &#39;OBJECT&#39;<br>     ) f;</pre><p><strong>Result:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*cTBAEDWzZ8fn-WSgwINYIA.png" /></figure><p>Here:</p><ul><li>f.key → &quot;2023&quot;, &quot;2024&quot;</li><li>f.value → 4.5, 4.8, etc.</li></ul><h3>MODE = ‘BOTH’</h3><p>Flatten both arrays and objects at the <strong>top level</strong> of a JSON document.</p><p>Simple example:</p><pre>CREATE OR REPLACE TABLE employees_mixed AS<br>SELECT PARSE_JSON(&#39;{<br>  &quot;skills&quot;: [&quot;SQL&quot;, &quot;Python&quot;],<br>  &quot;ratings&quot;: { &quot;2023&quot;: 4.5 }<br>}&#39;) AS emp_data;</pre><pre>SELECT<br>    f.key,<br>    f.value<br>FROM employees_mixed e,<br>     LATERAL FLATTEN(<br>         input =&gt; e.emp_data,<br>         MODE  =&gt; &#39;BOTH&#39;<br>     ) f;</pre><p><strong>Result:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*iovaK_-5Dh2bzwX8j-BU0A.png" /><figcaption>MODE = ‘BOTH’</figcaption></figure><blockquote><em>Note: </em><em>MODE = &#39;BOTH&#39; doesn’t recursively explode everything. It just flattens the </em><strong><em>top level</em></strong><em> keys/arrays. You can then FLATTEN again if needed.</em></blockquote><h3>6.4 RECURSIVE</h3><h3>Flattening Deeply Nested JSON</h3><p>RECURSIVE =&gt; TRUE tells FLATTEN:</p><blockquote><em>“Don’t just flatten the top level. Walk through </em><strong><em>all levels</em></strong><em> of the JSON and return every nested element.”</em></blockquote><p>Let’s build a small nested example still based on our employee theme:</p><pre>CREATE OR REPLACE TABLE employees_nested AS<br>SELECT PARSE_JSON(&#39;{<br>  &quot;name&quot;: &quot;Alice&quot;,<br>  &quot;skills&quot;: [&quot;SQL&quot;, &quot;Python&quot;],<br>  &quot;performance&quot;: {<br>    &quot;2023&quot;: {<br>      &quot;projects&quot;: [&quot;Billing System&quot;, &quot;Data Warehouse&quot;]<br>    }<br>  }<br>}&#39;) AS emp_data;</pre><h3>Example: RECURSIVE = TRUE</h3><pre>SELECT<br>    f.value,<br>    f.path<br>FROM employees_nested e,<br>     LATERAL FLATTEN(<br>         input     =&gt; e.emp_data,<br>         RECURSIVE =&gt; TRUE<br>     ) f;</pre><p>You’ll see multiple rows, showing <strong>all nested values</strong> and where they came from:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*Z1F-vrQyYfWN0WjNu4BlNQ.png" /><figcaption>RECURSIVE =&gt; TRUE</figcaption></figure><h3>When Recursive Mode Is Useful</h3><p>Use RECURSIVE =&gt; TRUE when:</p><ul><li>You don’t know the exact structure of the JSON ahead of time.</li><li>The nesting can vary between rows (deep, shallow, etc.).</li><li>You want to <strong>explore</strong> or <strong>debug</strong> the shape of a complex JSON document.</li><li>You’re building generic logic to search for values anywhere in the tree.</li></ul><h3>8. Common Mistakes and Best Practices</h3><h3>8.1 Forgetting LATERAL</h3><p><strong>Mistake:</strong></p><pre>SELECT <br>    emp_id,<br>    f.value::string AS skill<br>FROM employees e,<br>     FLATTEN(input =&gt; e.emp_data:skills) f;  -- may error in some environments</pre><p>In environments like Snowflake Notebooks, this can cause:</p><pre>SQL compilation error: unexpected &#39;(&#39;</pre><p><strong>Best Practice:</strong></p><p>Always write LATERAL explicitly when FLATTEN uses columns from the table:</p><pre>FROM employees e,<br>     LATERAL FLATTEN(input =&gt; e.emp_data:skills) f;</pre><h3>8.2 Using FLATTEN Before Filtering → Huge Row Explosion</h3><p>If you flatten first and filter later, you can create <strong>many more rows</strong> than necessary.</p><p><strong>Less efficient:</strong></p><pre>-- Flattens all employees, all skills, then filters<br>SELECT *<br>FROM employees e,<br>     LATERAL FLATTEN(input =&gt; e.emp_data:skills) f<br>WHERE f.value::string = &#39;Python&#39;;</pre><p><strong>Better approach:</strong></p><p>If possible, filter <strong>before</strong> or <strong>on the JSON</strong> to reduce data:</p><pre>-- Example: filter employees with &quot;Python&quot; in JSON before flattening (when possible)<br>SELECT *<br>FROM employees e<br>WHERE e.emp_data::string LIKE &#39;%Python%&#39;;</pre><p>Then apply FLATTEN on a <strong>smaller set</strong>.</p><h3>8.3 When NOT to Use Recursive FLATTEN</h3><p>RECURSIVE =&gt; TRUE can be <strong>expensive</strong>, especially for very large or deeply nested JSON.</p><p>Avoid using it when:</p><ul><li>You already know the exact path you care about (use PATH instead).</li><li>You only need one array (like skills) and not the whole JSON tree.</li><li>The JSON documents are huge and performance matters.</li></ul><p><strong>Prefer:</strong></p><ul><li>PATH for targeted flattening</li><li>Non-recursive FLATTEN where possible</li></ul><h3>8.4 Optimizing Queries With Filters</h3><p>Good patterns:</p><ul><li>Use OUTER =&gt; TRUE only when you really need to keep empty arrays.</li><li>Add WHERE conditions on:</li><li>value</li><li>key</li><li>path<br> to minimize results early.</li><li>Consider projecting only the columns you actually need (value, index, key) rather than SELECT *.</li></ul><p>Example:</p><pre>SELECT <br>    e.emp_id,<br>    f.value::string AS skill<br>FROM employees e,<br>     LATERAL FLATTEN(input =&gt; e.emp_data:skills) f<br>WHERE f.value::string IN (&#39;SQL&#39;, &#39;Python&#39;);</pre><p>This keeps the result set focused and efficient.</p><h3>9. Complete End-to-End Example</h3><p>Let’s build a slightly richer example based on your employee theme and show:</p><ul><li>LATERAL</li><li>PATH</li><li>OUTER</li><li>MODE</li><li>RECURSIVE (lightly)</li></ul><h3>9.1 Sample Data</h3><pre>CREATE OR REPLACE TABLE employees_full AS<br>SELECT <br>    column1 AS emp_id,<br>    PARSE_JSON(column2) AS emp_data<br>FROM VALUES<br>    (101, &#39;{<br>      &quot;name&quot;: &quot;Alice&quot;,<br>      &quot;skills&quot;: [&quot;SQL&quot;, &quot;Python&quot;, &quot;Snowflake&quot;],<br>      &quot;projects&quot;: {<br>        &quot;current&quot;: [&quot;Billing System&quot;, &quot;Data Warehouse&quot;],<br>        &quot;past&quot;: [&quot;Reporting Portal&quot;]<br>      },<br>      &quot;ratings&quot;: { &quot;2023&quot;: 4.5, &quot;2024&quot;: 4.8 }<br>    }&#39;),<br>    (102, &#39;{<br>      &quot;name&quot;: &quot;Bob&quot;,<br>      &quot;skills&quot;: [&quot;Excel&quot;, &quot;Power BI&quot;],<br>      &quot;projects&quot;: {<br>        &quot;current&quot;: [&quot;Dashboard Migration&quot;],<br>        &quot;past&quot;: []<br>      },<br>      &quot;ratings&quot;: { &quot;2023&quot;: 4.0 }<br>    }&#39;),<br>    (103, &#39;{<br>      &quot;name&quot;: &quot;Carol&quot;,<br>      &quot;skills&quot;: [],<br>      &quot;projects&quot;: {<br>        &quot;current&quot;: [],<br>        &quot;past&quot;: []<br>      },<br>      &quot;ratings&quot;: {}<br>    }&#39;);</pre><h3>9.2 Full Query Combining the Concepts</h3><p>Goal: For each employee, list:</p><ul><li>Each <strong>skill</strong> (with OUTER)</li><li>Each <strong>current project</strong></li><li>Each <strong>rating year/value</strong></li></ul><p>We’ll use:</p><ul><li>LATERAL for row-by-row expansion</li><li>PATH to target nested sections</li><li>OUTER to keep rows even when arrays/objects are empty</li><li>MODE for object flattening (ratings)</li><li>A small RECURSIVE exploration at the end</li></ul><h4>Step 1: Flatten Skills With OUTER</h4><pre>WITH skills_cte AS (<br>    SELECT<br>        e.emp_id,<br>        f.value::string AS skill<br>    FROM employees_full e,<br>         LATERAL FLATTEN(<br>             input =&gt; e.emp_data:skills,<br>             OUTER =&gt; TRUE<br>         ) f<br>)</pre><ul><li>Keeps Carol (103) even if she has no skills.</li><li>skill will be NULL for her.</li></ul><h4>Step 2: Flatten Current Projects Using PATH</h4><pre>, projects_cte AS (<br>    SELECT<br>        e.emp_id,<br>        f.value::string AS current_project<br>    FROM employees_full e,<br>         LATERAL FLATTEN(<br>             input =&gt; e.emp_data,<br>             path  =&gt; &#39;projects.current&#39;,<br>             OUTER =&gt; TRUE<br>         ) f<br>)</pre><ul><li>Uses PATH to go directly to projects.current.</li><li>OUTER =&gt; TRUE ensures we keep employees with no current projects.</li></ul><h4>Step 3: Flatten Ratings Using MODE = ‘OBJECT’</h4><pre>, ratings_cte AS (<br>    SELECT<br>        e.emp_id,<br>        f.key::string   AS rating_year,<br>        f.value::number AS rating_value<br>    FROM employees_full e,<br>         LATERAL FLATTEN(<br>             input =&gt; e.emp_data:ratings,<br>             MODE  =&gt; &#39;OBJECT&#39;,<br>             OUTER =&gt; TRUE<br>         ) f<br>)</pre><ul><li>MODE =&gt; &#39;OBJECT&#39; converts { &quot;2023&quot;: 4.5, &quot;2024&quot;: 4.8 } into rows.</li><li>OUTER =&gt; TRUE keeps employees who have no ratings yet.</li></ul><h4>Step 4: Join Everything Together</h4><pre>SELECT<br>    COALESCE(s.emp_id, p.emp_id, r.emp_id) AS emp_id,<br>    s.skill,<br>    p.current_project,<br>    r.rating_year,<br>    r.rating_value<br>FROM skills_cte   s<br>FULL OUTER JOIN projects_cte p ON s.emp_id = p.emp_id<br>FULL OUTER JOIN ratings_cte  r ON COALESCE(s.emp_id, p.emp_id) = r.emp_id<br>ORDER BY emp_id;</pre><p>This gives you a combined, flattened view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*jrwTPNqR7FBy6slyaHnCyg.png" /><figcaption>The output is completely flattened into a structured dataset.</figcaption></figure><h4>If this guide helped you understand FLATTEN more clearly, I’d love to hear your thoughts.</h4><h4>If you want more practical Snowflake deep-dives like this, feel free to <strong>follow</strong><a href="https://www.linkedin.com/in/vivek-sunny-vs/"><strong> Vivek Sunny</strong></a><strong> on </strong><a href="https://www.linkedin.com/in/vivek-sunny-vs/"><strong>LinkedIn</strong></a><strong> and </strong><a href="https://medium.com/@viveksunny.sunny"><strong>Medium</strong></a></h4><h4>I publish hands-on tutorials, engineering patterns, and real-world data problems that most teams face but few talk about.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1bfcbd15ef9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>