<?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 Raghid Bsat on Medium]]></title>
        <description><![CDATA[Stories by Raghid Bsat on Medium]]></description>
        <link>https://medium.com/@raghid.bsat?source=rss-c777743c17a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*k5Nfr360TqmZibDj</url>
            <title>Stories by Raghid Bsat on Medium</title>
            <link>https://medium.com/@raghid.bsat?source=rss-c777743c17a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:30:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raghid.bsat/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[Migrating a Data Platform: 20% technology, 80% everything else]]></title>
            <link>https://medium.com/datamindedbe/migrating-a-data-platform-20-technology-80-everything-else-6a24472650f4?source=rss-c777743c17a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a24472650f4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-assisted-coding]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[cloud-migration]]></category>
            <dc:creator><![CDATA[Raghid Bsat]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 13:21:15 GMT</pubDate>
            <atom:updated>2026-07-27T13:21:15.929Z</atom:updated>
            <content:encoded><![CDATA[<p>At some point, when the bills become too high, or the platform is not scalable anymore, almost every organisation with a data platform reaches the same crossroads: “We need to migrate”. Sometimes it is out of the hands of the engineers if a vendor sunsets a tool you built everything on. Or a license renewal comes with a heavy price tag that nobody wants to sign off on. Whatever happens after is rarely about the technology itself. It is about whether the organisation and its people are ready to go through a migration.</p><p>I have gone through this experience more than once myself, moving pipelines, tables, and being in the middle of different delivery teams that are expecting their dashboards to just keep working, regardless of the backend changing. If there is one thing I keep relearning, it is this: Migrations do not fail because the SQL was hard to translate. Migrations fail because nobody agreed upfront about when is it ”done”, who owns what, or what happens when the numbers do not match.</p><h3>Why is this more relevant now?</h3><p>Today’s platforms are far more complex than 10 years ago . They are made up of orchestrators, lakehouses, dozens/hundreds of dashboards, APIs, and legacy pipelines that nobody remembers building but are crucial to the everyday work of different teams. Moreover, platforms are being retired at a much faster pace. Every vendor now seems to a have a new “unified” offering they want you to move into. Whether or not that pressure is justified is a separate discussion.</p><h3>Who this is actually for?</h3><p>This is written for the people who actually sit around the table during a migration, and what is at stake for each of them specifically, not just the engineers writing the code</p><p>If you are a <em>migration architect </em>or a <em>data</em> <em>platform owner</em>, this is about not reinventing the wheel every time, and making sure that the strategy and success criteria are defined from the beginning.</p><p>If you are a <em>platform architect</em>, this is about knowing early whether the target platform can truly support what you already have, before the time gap starts to grow</p><p>If you are a data engineer doing the actual migration, this is not about being handed ambiguous work like <em>migrate everything </em>and being expected to figure out priority and validation thresholds on your own.</p><p>Finally, if you are a <em>data owner</em> or a <em>consumer team</em>, and your dependency sits downstream, this concerns you more than you might think. You are the one that will be asked whether those numbers look right to you or not. It is much better to be part of that conversation early on than to be surprised by it before decommissioning of the old platform.</p><h3><strong>What tends to go wrong?</strong></h3><p>The technical part of a migration, in my experience, is rarely the hardest part, and it is becoming easier. A few years ago, translating SQL dialects or rewriting a pipeline for a different scheduler was a lot of manual work: reading legacy code line by line, guessing the intent where comments were missing and heavily testing to make sure nothing broke. With AI-assisted coding on the rise, giving agents the task of migrating from platform A to B or between different SQL dialects has become quite trivial. What is much harder to solve is the stuff that should have been agreed on before a single pipeline was touched:</p><ul><li>Nobody defined what “success” really means for a given pipeline. Does it need to match the legacy output, or is a 95% similarity fine? If this gets decided later in the project you end up negotiating thresholds with a stakeholder while the clock could potentially be running on a deadline.</li><li>The discovery phase usually gets rushed or entirely skipped because it does not feel like actual progress being made. A dependency diagram or a source-to-target mapping sheet is not super impressive. Teams are usually tempted to jump right into execution. Migration is usually close to 75% analysis and 25% execution with AI-assisted coding. Spending more time here can save up a lot of time down the line.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZBjtc-7Cy_MfaefWMgfIw.png" /><figcaption>Building the priority list as part of the Discovery phase.</figcaption></figure><ul><li>Access to the legacy system and outdated documentation is essential to the engineering team. This alone can stall migration for quite some time.</li><li>Consumer teams and data owners end up being part of the loop quite late. By then, the trust relationship is already broken, and you end up trying to repair it instead of repairing their broken pipelines.</li><li>In some cases, other teams are still developing on the legacy systems while the migration team is still trying to map out what exists. Every new table or new job being introduced is a new dependency that might be missed.</li></ul><p>None of these are technology problems. They are alignment problems and they are exactly the kind of thing that is cheap to fix in advance, but expensive to fix mid-project.</p><h3>Why I ended up writing a guidebook about it</h3><p>After going through the cycle myself a couple of times across different projects, the pattern became too repetitive to ignore. So I put together a small <a href="https://migrations.cloudrun.datamaturitytest.com/">migration guidebook</a> that breaks the whole process into five phases: Vision, Governance, Discovery, Execution, and Cutover. At a high level, it walks through who should be involved at each stage, and what decisions should come out before moving forward to the next phase. It also includes where AI agents can meaningfully take over at the execution level with some examples.</p><h3>In Conclusion</h3><p>A failed migration might look differently depending on the situation. Nobody sends out an email saying “the migration didn’t work.” Instead, a dashboard quietly starts showing numbers people stop trusting. A consumer team builds a workaround instead of raising the discrepancy, because raising it feels like more friction than it’s worth. It shows up months later, as a slow decay of confidence in the platform itself, and that is a hard thing to win back.</p><p>The technical side of a migration is the part getting easier every year, and I expect that trend to continue. The part that decides whether people trust the platform afterwards is the part that has nothing to do with code. This includes agreeing early on what success looks like, giving discovery the time it actually needs, and bringing in the teams downstream early on. Get that right and the execution tends to take care of itself. Get it wrong, and no amount of clever tooling will fix it after the fact. If you are about to start one, treat scope, ownership, and validation as the actual project, and treat the migration itself as the execution of that plan. The guidebook can be found <a href="https://migrations.cloudrun.datamaturitytest.com/">here</a>. If you are about to start a migration, or you are trying to convince your organisation that a migration is needed, this is where I would point you next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a24472650f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datamindedbe/migrating-a-data-platform-20-technology-80-everything-else-6a24472650f4">Migrating a Data Platform: 20% technology, 80% everything else</a> was originally published in <a href="https://medium.com/datamindedbe">Dataminded</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft Fabric’s Migration Hurdles: My Experience]]></title>
            <link>https://medium.com/datamindedbe/microsoft-fabrics-migration-hurdles-my-experience-b8fbd9a334fb?source=rss-c777743c17a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8fbd9a334fb</guid>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[microsoft-fabric]]></category>
            <dc:creator><![CDATA[Raghid Bsat]]></dc:creator>
            <pubDate>Thu, 08 Aug 2024 14:42:50 GMT</pubDate>
            <atom:updated>2024-08-08T14:42:50.609Z</atom:updated>
            <content:encoded><![CDATA[<p>It has been more than a year since Microsoft announced their new all-mighty Fabric data platform. It offers a wide range of capabilities, including data science, data warehousing, real-time analytics, Lakehouse, data workflows, and Power BI integration. Made generally available back in November 2023, IT managers and data enthusiasts ask this question: Should my organisation dive into the Fabric ecosystem, or should we hold off?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueXmn92yY6UL4jhgHR8CQQ.png" /><figcaption><a href="https://datamonkeysite.com/2023/05/27/first-impression-of-microsoft-fabric/">Image source</a></figcaption></figure><p>Before trying to answer this question, it is probably better to think about why we are considering it in the first place. Do you already have a data platform that follows a modular approach and would like to integrate some of Fabric’s capabilities? Or are you starting from scratch and want to adopt it as a whole? In this blog post, I will talk about my experience with Microsoft Fabric, looking at it from a modular point of view: shifting our tables using the Microsoft Synapse SQL engine to the Fabric SQL engine, and can we configure the fabric control plane with our Infrastructure as Code (IaC) Terraform codebase?</p><h3>Querying Unmanaged Tables:</h3><p>I am currently working with a client on their data platform, where we use Synapse Serverless SQL Pool as our main SQL engine to read data from delta tables. Delta tables are made up of parquet files that are open-source column-oriented data format and a delta log file that describes transactions that occurred on those parquet files and column statistics.</p><p>In our use case, these tables are external and are being updated by a general-purpose data pipeline that pushes parquet files to Azure’s Data Lake Storage (ADLS). It is possible to allow Synapse to read from your storage by creating external views with its own managed identity:</p><pre>SELECT *<br>FROM OPENROWSET(<br> BULK &#39;path/to/delta_table&#39;,<br> DATA_SOURCE = &#39;adls_data_source&#39;,<br> FORMAT = &#39;DELTA&#39;<br>) AS [result];</pre><p>You achieve cost-effective queries compared to traditional SQL database models by storing your data in ADLS. Additionally, you gain the advantage of on-demand scaling, ensuring optimal performance without the need for manual resource management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJxj-wHkXz_pr1brabBIWA.png" /></figure><p>The reason we started looking into Fabric is because Microsoft decided to stop its development on Azure Synapse Analytics. This puts us in a spot where we need to find a different SQL engine to query our tables.</p><p>Can you replicate this setup on Fabric? It appears to be a straightforward migration, at least from an infrastructure and implementation standpoint. Replicating a similar Synapse data architecture isn’t feasible with Fabric. OPENROWSET() is not a supported feature in the Fabric ecosystem, and it is not part of the Fabric <a href="https://learn.microsoft.com/en-gb/fabric/release-plan/">roadmap</a>. While Fabric enables the creation of shortcuts that point to storage locations (e.g., ADLS), they ultimately manifest as managed tables. These managed tables are completely managed by Fabric, both the schema metadata and the data files. This is a bottleneck since it deviates from the idea of an external table, where you would want your SQL engine to only manage the schema metadata.</p><p>With managed tables, Microsoft Fabric’s Lake-Warehouse employs a query engine for generating SQL execution plans. The query optimiser assesses potential plans and estimates the workload for each operation. This estimation heavily relies on critical data insights derived from regularly updated <a href="https://learn.microsoft.com/en-us/fabric/data-warehouse/statistics">statistics</a>, typically calculated whenever the delta log undergoes changes. This means that whenever the delta log changes in your delta table, the statistics and query plan have to be updated. Note that the update of the statistics only happens when a manual query of the newly created delta table occurs.</p><p>If you worked with delta tables before, you might have already noticed that the delta logs already contain statistical information about the columns. However, the Fabric engine calculates additional statistics that will be used in the query plan. This might be due to Fabric utilising a proprietary Pyspark image within their environment. For tables updated through Fabric DataFactory or Fabric DataPipelines, this optimization might be essential. Moreover, this proprietary version of Pyspark has a feature called <a href="https://learn.microsoft.com/en-us/fabric/data-engineering/delta-optimization-and-v-order?tabs=sparksql">V-Order,</a> a delta table optimiser known for dramatically speeding up query performance. What I am trying to say is that there seems to be high support for the tables that are updated through the Fabric environment; not those being updated from external sources.</p><p>Since I could not find any proper explanation about this on Microsoft documentation, this is what I believe is happening under the hood:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5ormx8ljsbF7ojk2wZ6Qg.png" /></figure><p>To test my theory, I added a table shortcut with an external connection to ADLS for a 4 billion row-sized delta table. It took 33 minutes for the initial query to pass through, after which queries were very quick (even quicker than Synapse Analytics!). After the delta table had been updated from our pipeline with almost 4 million rows, the initial query took 20 minutes, after which the rest of the queries were quick. What happened in these 20 minutes is that the delta log was not in sync anymore with the ‘manifest’ file that Fabric keeps with the new statistics calculated. It recalculates statistics to update its manifest file when an initial query is targeted towards that table.</p><p>Is there a solution around this? Possibly, but not recommended. I spoke with Microsoft support engineers about whether or not we can disable the statistics calculations or control them through the external pipeline itself. They mention that it is possible with their help, only on a workspace level. They also said that this is generally not recommended practice, as they do not entitle this feature to be controlled by the consumer for now.</p><p>Finally, if your table is not updated frequently — say daily, weekly, or monthly — it might make sense to try using table shortcuts with Fabric. The downtime caused by statistics calculation would be negligible compared to the time needed for table updates.</p><h3>Incomplete Infrastructure as Code — Yet</h3><p>If you are a fan of streamlined engineering processes, you also prefer to automate these different access controls, workspace configurations, managed identities, and associated infrastructure rules. It is quite impressive that the Microsoft Fabric team has already released their <a href="https://learn.microsoft.com/en-us/rest/api/fabric/articles/">API</a> (in preview), but there is still more work to be done before it can be adopted as IaC.</p><p>For starters, a Terraform resource for handling Fabric-related tasks is yet to be released. While there’s a Python Fabric SDK developed by <a href="https://github.com/DaSenf1860/ms-fabric-sdk-core?tab=readme-ov-file#working-with-one-lake-shortcuts">DaSenf1860</a>, the Fabric API still lacks essential features. One significant limitation is the inability to manage connections and share them between users for access control through the API. A connection is an authentication method to let a lakehouse load the data files (through an organisational account, SAS token or Access key). These connections can be re-used for different tables and can also be shared with groups, service principals, and users. This process can be done via the UI only, which provides an associated connection Id that can then be used to create these shortcuts. Using connections can be important for IaC: You can streamline the process of governing the access of schemas, tables, or views.</p><p>While interacting with the API, I noticed that the “connection_id” can be leaked with some GET requests.</p><pre>POST https://api.fabric.microsoft.com/v1/workspaces/workspace_id/items/lakehouse_id/shortcuts<br><br>body:<br>{<br>  &quot;path&quot;: &quot;Tables&quot;,<br>  &quot;name&quot;: &quot;demo_table2&quot;,<br>  &quot;target&quot;: {<br>    &quot;adlsGen2&quot;: {<br>             &quot;connectionId&quot;: &quot;connection_id&quot;, //needs to be created<br>            &quot;location&quot;: &quot;https://&lt;storageaccountname&gt;.dfs.core.windows.net&quot;,<br>            &quot;subpath&quot;: &quot;/&lt;containername&gt;/path/to/table_demo2&quot;    <br>    },<br>  },<br>}</pre><p>There is no POST request that can be sent to the API to create a new connection. I was able to get my connection Id that was already created in the UI only. This suggests that the Fabric API is still unreliable to be used as part of an IaC codebase.</p><h3>Bonus: Navigating Uncharted Errors</h3><p>When I was trying to test out the Fabric Lakehouse capabilties, I encountered numerous “Internal Errors”. Given that Fabric is a relatively new product, ongoing bug discovery is expected, which can impede developer experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*-tfxJdGGRZx4WAdsAI1hzw.png" /><figcaption>Image adopted from <a href="https://medium.com/@techformindful/how-to-manage-frustration-when-it-comes-to-tech-failures-ad450da42400">here</a></figcaption></figure><p>For example, I experienced extended query durations (&gt;8 minutes) when using special characters like the pipe (|) symbol within a delta partition:</p><blockquote>path/to/delta/partition=54|A/*.parquet.</blockquote><p>This occurs because the delta log URL-encodes the special character as “<em>%7C</em>”. Subsequently, Fabric performs internal transformations, converting the “<em>%</em>” symbol to ‘<em>%25</em>’, resulting in a string of %25%7C:</p><blockquote>path/to/delta/partition=54%25%7CA/*.parquet.</blockquote><p>This intricacy causes the SQL engine to query for a long time before returning a result which in theory should not take more than a second. This case was not a problem for us with our Synapse views, since the engine was partition pruning directly from the delta logs. In the case of Fabric, an extra manifest file is created in between which is used for partition pruning. This causes a mismatch of file name. between the manifest file and what is truly in the storage location.</p><p>This error is what led me to believe that the new Fabric SQL engine is not relying on the delta logs anymore after it performs its calculations and creates its own manifest file. When it does get stuck in this process, it goes back to the delta log after 10 minutes or throws an internal error.</p><h3>Conclusion</h3><p>In our case, looking at other SQL engines other than Fabric’s made the most sense. My general impression is that Fabric appeals to organisations that do not have a data platform yet. It should be adopted as a whole platform. It also makes sense for organisations that heavily rely on Microsoft Data Factory as their cloud based ETL solution.</p><p>For organisations that follow a modular approach in their data platform design, there might not be any kind of benefit to Microsoft Fabric yet. By a modular architecture, I mean adopting Microsoft Fabric as a SaaS to provide some functionalities while managing everything centrally.</p><p>In conclusion, my experience led me to believe that the Fabric SQL engine might not be a good feature to integrate into your already existing data platform. There could be other Fabric features that can integrate well however — to be explored more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8fbd9a334fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datamindedbe/microsoft-fabrics-migration-hurdles-my-experience-b8fbd9a334fb">Microsoft Fabric’s Migration Hurdles: My Experience</a> was originally published in <a href="https://medium.com/datamindedbe">Dataminded</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering for a Better SQL Code Generation With LLMs]]></title>
            <link>https://medium.com/datamindedbe/prompt-engineering-for-a-better-sql-code-generation-with-llms-263562c0c35d?source=rss-c777743c17a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/263562c0c35d</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Raghid Bsat]]></dc:creator>
            <pubDate>Wed, 29 May 2024 12:42:23 GMT</pubDate>
            <atom:updated>2024-05-29T12:42:23.518Z</atom:updated>
            <content:encoded><![CDATA[<p>Picture yourself as a marketing executive tasked with optimising advertising strategies to target different customer segments effectively. You are required to answer the following question: “Which customer segments yield the highest return on investment for our advertising campaign?”. You might want to look at customer segment profitability and compare it with Customer Lifetime Value (CLV) to answer such questions. The following SQL query could be the answer:</p><pre>with customer_segment_profitability as (<br>    select<br>        customer_segment,<br>        avg(order_total) as avg_order_value,<br>        count(distinct customer_id) as num_customers,<br>        sum(order_total) as total_sales,<br>        sum(advertising_cost) as total_ad_cost,<br>        (sum(order_total) - sum(advertising_cost)) / count(distinct customer_id) as segment_profit<br>    from<br>        orders<br>    group by<br>        customer_segment<br>),<br>customer_clv as (<br>    select<br>        customer_segment,<br>        sum(total_sales) as total_spent,<br>        count(distinct customer_id) as num_customers,<br>        DATEDIFF(MAX(order_date), MIN(order_date)) as lifespan_days,<br>        sum(total_sales) / DATEDIFF(MAX(order_date), MIN(order_date)) as clv_per_day,<br>        (sum(total_sales) / DATEDIFF(MAX(order_date), MIN(order_date))) * 365 as clv_yearly<br>    from<br>        orders<br>    where<br>        customer_id is not NULL<br>    group by<br>        customer_segment<br>)<br>select<br>    csp.customer_segment,<br>    csp.avg_order_value,<br>    csp.num_customers as segment_customers,<br>    csp.total_sales,<br>    csp.total_ad_cost,<br>    csp.segment_profit,<br>    cc.total_spent as clv_total_spent,<br>    cc.num_customers as clv_num_customers,<br>    cc.clv_yearly<br>from<br>    customer_segment_profitability csp<br>join<br>    customer_clv cc on csp.customer_segment = cc.customer_segment<br>order by<br>    csp.segment_profit desc;</pre><p>Crafting such complex query demands expertise and context beyond the scope of many business professionals and would require more time to create. There is often a database-language barrier between business leaders and the data-driven decisions they are required to make. This is typically encoded by SQL which many business professionals find daunting or hardly practical. The rise of GenAI has opened the door for AI assistants to overcome such barriers where Large Language Models (LLMs) have demonstrated the ability to understand and generate natural language. Using LLMs as a way to create SQL statements from natural language can ease the issue of data access for non-technical profiles.</p><p>As of today, there have been many attempts in creating a state of the art LLM SQL query generator. Such example is MotherDuck’s “AI that Quacks, <a href="https://motherduck.com/blog/duckdb-text2sql-llm/">DUCKDB NSQL-7B</a>”. This blogpost explains the efforts done by MotherDuck and Numbers Station to create a text-to-SQL LLM. They created an open source LLM model using CodeLLama’s base model and fine-tune it with their custom training set that is a modified version of <a href="https://numbersstation.ai/duckdb-nsql-how-to-quack-in-sql/">NSText2SQL</a>. They have reported exceptionally good performance on the SQL benchmarks used. While this tool sounds amazing and training your own open-source model on a custom SQL training dataset can be a significant leap forward compared to simply using pre-existing models, it is important to provide additional <strong>context</strong> to the model. This involves crafting precise and contextually appropriate prompts to elicit desired responses from language models. By having a suitable prompt, it gives better context for the LLM to create error-free queries. In this blogpost, I will address the following: challenge of prompt engineering and explore the scenarios where leveraging a Retrieval Augmented Generation (RAG) solution is advantageous, compared to including all information directly in the prompt.</p><h3>How to build an effective prompt?</h3><ol><li><em>Include database schema</em></li></ol><p>The main challenge with using an LLM to generate SQL code is allowing the model to know the schema of the tables we are trying to query. Such information can be given in what we call a ‘context window’, which is the number of tokens (~words) the model can take as input when generating responses. In the case of generating SQL code, we can include our database schema into the context before asking our question. The catch is that LLMs come with a limited context window. For example, GPT-4 comes with a window of 128,000 tokens (~96,000 words). If your database is small enough, you can provide the full schema as part of the prompt.</p><p>This is an example of a prompt with the database schema included:</p><pre>You are a helpful assistant specialising in data analysis in a snowflake warehouse.<br>Answer the questions by providing SQL code that is compatible with the snowflake environment.<br>This is the question you are required to answer: <br><strong><em>What is the total number of customers in the Chocolate Haven branch?</em><br></strong><br>Here is the relevant context of the database:<br><strong><em>create or replace TABLE CUSTOMER_DETAILS (<br>    CUSTOMER_ID NUMBER(38,0) NOT NULL,<br>    FIRST_NAME VARCHAR(255),<br>    LAST_NAME VARCHAR(255),<br>    EMAIL VARCHAR(255),<br>    PHONE VARCHAR(20),<br>    ADDRESS VARCHAR(255),<br>    primary key (CUSTOMER_ID)<br>);</em></strong></pre><p>Testing this out on the snowflake sample dataset (TPCH_SF1), I noticed that in general the easy queries were answered correctly. These queries are characterised by having simple filters and multiple conditions:</p><pre>-- Give me all the customers where the marketing segment is &#39;MACHINERY&#39;<br>select *<br>  from customer<br>where <br>  c_mktsegment = &#39;MACHINERY&#39;;<br>-- Give me all the orders where the order priority is &#39;3-MEDIUM&#39; and the total price is above 100 000 euros<br>select *<br>  from orders<br>where <br>  o_orderpriority = &#39;3-MEDIUM&#39; and o_totalprice &gt; 100000;<br>-- Give me all the order keys where the order priority is &#39;5-LOW&#39; and the total price is below 250 000 euros and where the status is not &#39;F&#39;<br>select o_orderkey<br>  from orders<br>where <br>  o_orderpriority = &#39;5-LOW&#39; and o_totalprice &lt;= 250000 and o_orderstatus &lt;&gt; &#39;F&#39;;</pre><p><em>2. Include user feedback (session history)</em></p><p>In the case of complex queries with multiple joins and aggregations, the LLM was not able to reproduce accurate results. There were two main issues the LLM faced:</p><ul><li><strong>Semantic Complexity between tables</strong>: Complex queries often involve specific relationships between tables, nested subqueries, and conditional logic. LLMs may struggle to grasp the full semantic meaning of these complex structures, leading to inaccuracies in understanding and reproducing the intended query semantics.</li><li><strong>Business Vagueness</strong>: There can be certain ambiguous references, such as column aliases or ambiguous table references. Resolving these ambiguities requires contextual understanding and inference capabilities, which may be challenging for LLMs. In the case of query 2 (below), the LLM assumed that some columns exist already in the schema which produced an invalid SQL statement.</li></ul><pre>-- What is for each customer the total amount spent and the average order amount? Show our best customers (= most-paying) first.<br>-- This query has a join/group by that the LLM failed to identify.<br>select<br>  min(c_name) as customer_name,<br>  sum(coalesce(o_totalprice, 0)) as total_spent,<br>  avg(o_totalprice) as avg_order<br>from customer<br>  left join orders on c_custkey = o_custkey<br>group by <br>  c_custkey<br>order by <br>  total_spent desc;<br>-- Show me all the customers that have placed more than 40 orders<br>select<br>  min(c_name) as customer_name,<br>  count(*) as num_orders<br>from customer<br>  join <br>    orders on c_custkey = o_custkey<br>group by <br>  c_custkey<br>having <br>  count(*) &gt; 40;<br>-- For each nation, show me our top-3 highest-revenue customers in that nation. Don’t consider discounts.<br>-- There is a subquery to find the rank_in_nation the LLM failed to reproduce. It gave an inaccurate schema <br>-- by assuming that rank already exists in the table.<br>with<br>customer_with_rank as (<br>  select<br>    c_name,<br>    c_nationkey,<br>    sum(o_totalprice) as total_revenue,<br>    rank() over (<br>      partition by c_nationkey<br>      order by total_revenue desc<br>    ) as rank_in_nation<br>  from customer<br>  join orders on c_custkey = o_custkey<br>  join nation on c_nationkey = n_nationkey<br>  group by c_name, c_nationkey<br>)<br>select *<br>from customer_with_rank<br>join nation on c_nationkey = n_nationkey<br>where rank_in_nation &lt;= 3;</pre><p>User feedback can ‘push’ the LLM in the right direction that results in a correct query after a failed attempt. This is the next step of prompt engineering: Adding more relevant context other than database schemas can be crucial for optimised SQL code generation. You can include the session history as part of the prompt like this:</p><pre>You are a helpful assistant specialising in data analysis in a snowflake warehouse.<br>Answer the questions by providing SQL code that is compatible with the snowflake environment.<br>This is the question you are required to answer: <br><strong><em>What is the total number of customers in the Chocolate Haven branch?</em><br></strong><br>Here is the relevant context of the database:<br><strong><em>create or replace TABLE CUSTOMER_DETAILS (<br>    CUSTOMER_ID NUMBER(38,0) NOT NULL,<br>    FIRST_NAME VARCHAR(255),<br>    LAST_NAME VARCHAR(255),<br>    EMAIL VARCHAR(255),<br>    PHONE VARCHAR(20),<br>    ADDRESS VARCHAR(255),<br>    primary key (CUSTOMER_ID)<br>);<br><br></em></strong>The user has reported the following feedback:<br><strong><em>You should not be looking in the orders table</em></strong></pre><p><em>3. Include business information</em></p><p>For more in-depth business context, large organisations tend to have relevant data scattered everywhere in different formats and sources. I suggest to split the data into three different categories:</p><ul><li><strong>Domain specific knowledge: </strong>This is the information that can be relevant to the question. For example, we can include statements such as:</li></ul><blockquote>The Belgian branch is called the “Chocolate Haven” branch</blockquote><blockquote>Benelux region is made up of Luxembourg, Netherlands, and Belgium branches;</blockquote><blockquote>Marketing campaigns in the “Ardennes” region have historically shown higher conversion rates.</blockquote><ul><li><strong>Historical Used Queries:</strong> These are queries that are often used by business analysts and are go-to queries for common analytical needs: Monthly sales report by region, customer churn analysis by product category, top-selling products by quarter, profitability analysis by customer segment.</li><li><strong>Data Transformation and Enrichment Logic</strong>: This category includes the logic and rules applied to transform and enrich raw data into meaningful business insights. Some examples include: Calculations for derived metrics such as customer lifetime value (CLV), average order value (AOV), or conversion rates; Time-based calculations for trends analysis, seasonality adjustments, or cohort analysis.</li><li><strong>Bonus Category: Business Rules and Policies</strong>: While this might be still experimental and there is no set solution for handling data governance with genAI, I would generally handle this with care. This category includes rules such as access control policies that determine who within the organisation has permission to view or modify certain tables or data retention policies. I would instead push this to be an sql sanitising logic based module after the LLM returns an answer.</li></ul><p>The final prompt in action:</p><pre>You are a helpful assistant specialising in data analysis in a snowflake warehouse.<br>Answer the questions by providing SQL code that is compatible with the snowflake environment.<br>This is the question you are required to answer: <br><strong><em>What is the total number of customers in the Chocolate Haven branch?</em><br></strong><br>Here is the relevant context of the database:<br><strong><em>create or replace TABLE CUSTOMER_DETAILS (<br>    CUSTOMER_ID NUMBER(38,0) NOT NULL,<br>    FIRST_NAME VARCHAR(255),<br>    LAST_NAME VARCHAR(255),<br>    EMAIL VARCHAR(255),<br>    PHONE VARCHAR(20),<br>    ADDRESS VARCHAR(255),<br>    primary key (CUSTOMER_ID)<br>);</em></strong><br><br>The user has reported the following feedback:<br><strong><em>You should not be looking in the orders table</em><br></strong><br>This is some business context that is relevant to the question:<br><strong><em>1. The Belgian branch is called the Chocolate Haven branch.<br>2. Benelux region is made up of Luxembourg, Netherlands, <br>and Belgium branches</em></strong><em><br></em> <br>Historically, business analysts have used these queries <br>for answering similar questions:<br><strong><em>Query to analyse profitability by customer segment:<br>WITH customer_profitability AS (<br> SELECT<br>        .... <br>)</em><br></strong><br>If certain aggregations or data derived metrics are needed<br>to answer the user&#39;s question, these are the most relevant<br>pieces of information needed:<br><strong><em>Rule to calculate Customer Lifetime Value (CLV):<br>SELECT<br>    SUM(total_sales) AS total_spent,<br>    COUNT(DISTINCT order_id) AS total_orders,<br>      ...<br>ORDER BY<br>    clv_yearly DESC;</em></strong></pre><h3>Take your LLM-SQL bot to the next level with data engineering:</h3><p>For a potential future client, we created a proof-of-concept that showcases the possibility of LLMs with SQL code generation on top of their data warehouse. We created a simple user interface where business professionals can interact with a chatbot, generate SQL statements, and print out the resulting table.</p><p>In the case of the demo I worked on, the database contained only 8 tables; with a varying schema length between 3 columns to 18 columns. Making up the Data Definition Language (DDL) SQL commands (CREATE TABLE …) sums up to 1k tokens. In this small example, I had enough room with the token limit to provide it all within the same context. However, that might not be the case for large organisations that tend to have few hundreds of tables within their databases. This is where the power of Retrieval-Augmented Generation (RAG) comes in.</p><p>I relied on the architecture that was proposed by Kaarthik in his <a href="https://blog.streamlit.io/snowchat-leveraging-openais-gpt-for-sql-queries/#what-is-snowchat">blogpost</a>. His main idea was to use a RAG that retrieves information from a vector database built with the table schemas. The result of the retrieval would later be engineered in the prompt given to the LLM through an API. In summary, this is the architecture followed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7TFJJYHg2gbgiqoezZ0gQ.png" /></figure><p>By using a RAG, you would not need to include the full context in the prompt; but rather the most relevant parts only. The idea of a RAG is to rely on pre-existing knowledge or data to provide accurate responses. The relevant information is retrieved and provided in the prompt of the LLM to generate better answers. In the case of this demo, it was the table schemas (data definition language queries) assembled as readme files with some context for each table added to the vector database. Relevant schemas will be retrieved with a similarity search before it gets engineered into the prompt and passed to the LLM as an API call. Vectors are created in the vector database by representing the input query as a numerical vector and is compared to the numerical vector stored. The retrieval function would return N-similar records. You can read more about how to store and retrieve similarities between vector embeddings <a href="https://bergum.medium.com/four-mistakes-when-introducing-embeddings-and-vector-search-d39478a568c5">here</a>.</p><p>Having the business context categories, database schema, and user feedback stored and indexed efficiently in a vector database is where the magic of data engineering should happen: Whether the data sources are pdfs, word documents, text files, or databases, they can be ingested into a centralised database where they are structured, indexed, and made searchable.</p><p>Domain-specific knowledge can be stored in a knowledge graph, where entities and their relationships are represented as nodes and edges. Historically used queries can be stored in a query table, where they are categorised and tagged based on their purpose and usage. Data transformation and enrichment logic can be stored in a rules book database. As a data engineer myself, we strive to build systems that are not only efficient but also flexible and responsive to change. By using the power of ETL (Extract, Transform, Load) pipelines, we can create dynamic processes that automatically update our business knowledge databases as new insights emerge and business contexts evolve. This can include a monitoring ETL pipeline to continuously observe these different data sources, applies the necessary transformation, and updates the related databases.</p><h3>Large Context Windows</h3><p>Google’s Gemini 1.5 has included a 128k token context window size. However, a limited number of developers are already able to try their refined version which includes a window of up to <a href="https://blog.google/technology/ai/google-gemini-next-generation-model-february-2024/#sundar-note">1 million tokens</a>. This begs the question, is a RAG really needed at this point? With such huge window size, these models can capture 10 times more information within one prompt, without the need to retrieve relevant information in a vector database. This can lead to more efficient inference and training process, since the middle man of a RAG is cut out, allowing the model to directly access all important context.</p><p>However, I would argue that a RAG would still be relevant in this case: the goal is to thoroughly understand which context the LLM model considered “relevant” when generating a query. It might not be enough to magically generate a query for a business analyst. Retrieving the relevant context can be returned to explain how this particular query was generated for the human to evaluate.</p><h3>Conclusion:</h3><p>In conclusion, my recommendation for an LLM-SQL bot is to train your own open source model (similar to that of DuckDB NSQL) and also include the business categories mentioned in this blogpost. This ensures that the model is well aware of important context when generating responses. Motherduck’s NSQL-7B does a good job in validating whether the generated SQL statement works on the provided schema or not. This validation process essentially acts as a sanitisation step for your query statements, helping to catch any potential errors or mismatches before they cause problems in your database. Depending on the volume of data within the organisation, one could opt to either include all information directly in the prompt or create a RAG solution.</p><p>It’s equally essential to emphasise the importance of clean and meaningful data along with having a well-crafted prompt that captures relevant business context. If organisations are set to create their own LLM-SQL bot, my advice is to prioritise data quality control, data collection, and data cleaning. Normalising the data into structured format is also proven to be a better format for the LLM to understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=263562c0c35d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datamindedbe/prompt-engineering-for-a-better-sql-code-generation-with-llms-263562c0c35d">Prompt Engineering for a Better SQL Code Generation With LLMs</a> was originally published in <a href="https://medium.com/datamindedbe">Dataminded</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>