<?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 Shyam Rao on Medium]]></title>
        <description><![CDATA[Stories by Shyam Rao on Medium]]></description>
        <link>https://medium.com/@shyamrao_2844?source=rss-82fab063cf46------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BpJ8iwI6VRs7dhfA</url>
            <title>Stories by Shyam Rao on Medium</title>
            <link>https://medium.com/@shyamrao_2844?source=rss-82fab063cf46------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:38:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shyamrao_2844/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[Introducing Stored Procedures in Databricks]]></title>
            <link>https://medium.com/dbsql-sme-engineering/introducing-stored-procedures-in-databricks-bb4ece0c9539?source=rss-82fab063cf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb4ece0c9539</guid>
            <category><![CDATA[databricks-sql]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[stored-procedure]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <dc:creator><![CDATA[Shyam Rao]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 18:05:39 GMT</pubDate>
            <atom:updated>2025-07-08T18:40:25.851Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*kO4ihxWt5e9O9MQnDEZgDA.png" /></figure><h3>Introduction</h3><p>If you’re a data engineer familiar with stored procedures in traditional databases, you’ll be glad to know that <strong>Databricks SQL</strong> now supports stored <a href="https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-ddl-create-procedure"><strong>procedures</strong></a> — bringing modular and reusable logic directly into your Lakehouse.</p><blockquote><em>Included below: Sample </em><strong><em>procedure</em></strong><em> to populate an audit table as part of your ETL flow!</em></blockquote><h3>What Are Stored Procedures in Databricks?</h3><p>A <a href="https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-ddl-create-procedure"><strong>procedure</strong></a> in Databricks is a stored routine that encapsulates one or more SQL statements, allowing complex logic to be executed as a single callable unit. This functionality is supported in <strong>Unity Catalog</strong> and requires <strong>Databricks Runtime 17.0 or later</strong>.</p><p>Procedures can:</p><ul><li>Accept input parameters</li><li>Return output values</li><li>Modify data through SQL operations</li><li>Include control-flow logic (like loops and conditionals)</li></ul><h3>Key Features</h3><h4>▶ Creation</h4><p>Stored procedures are created using the CREATE PROCEDURE (<a href="https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-ddl-create-procedure">AWS</a>|<a href="https://learn.microsoft.com/en-us/azure/databricks/sql/language-manual/sql-ref-syntax-ddl-create-procedure">Azure</a>|<a href="https://docs.databricks.com/gcp/en/sql/language-manual/sql-ref-syntax-ddl-create-procedure">GCP</a>) statement. You can define:</p><ul><li>Parameters with modes: IN, OUT, or INOUT</li><li>Additional characteristics such as SQL security and determinism</li></ul><h4>▶ Parameter Modes</h4><ul><li><strong>IN</strong>: Input only (default)</li><li><strong>OUT</strong>: Output only; initialized to NULL and set inside the procedure</li><li><strong>INOUT</strong>: Acts as both input and output</li></ul><h4>▶ Example</h4><pre>CREATE OR REPLACE PROCEDURE main.default.get_ins_upd_metrics(table_name STRING, OUT num_recs_inserted INT, OUT num_recs_updated INT)<br>  LANGUAGE SQL<br>  SQL SECURITY INVOKER<br>  COMMENT &#39;Get number of records inserted/updated in table_name by previous DML&#39;<br>  AS BEGIN<br>    DECLARE sqlstr STRING;<br><br>    SET sqlstr = CONCAT(<br>      &#39;CREATE OR REPLACE TEMPORARY VIEW op_metrics AS<br>       SELECT<br>         COALESCE(operationMetrics.numTargetRowsInserted, operationMetrics.numOutputRows) AS num_inserted,<br>         COALESCE(operationMetrics.numTargetRowsUpdated, operationMetrics.numUpdatedRows) AS num_updated<br>       FROM (DESCRIBE HISTORY &#39;, table_name, &#39;)<br>       WHERE operation IN (\&#39;MERGE\&#39;, \&#39;WRITE\&#39;, \&#39;CREATE TABLE AS SELECT\&#39;, \&#39;REPLACE TABLE AS SELECT\&#39;, \&#39;UPDATE\&#39;)<br>       ORDER BY `timestamp` DESC LIMIT 1&#39;);<br><br>    EXECUTE IMMEDIATE sqlstr;<br><br>    /*  Optionally INSERT record into the main ETL log table */<br><br>    SET (num_recs_inserted, num_recs_updated) = (SELECT num_inserted, num_updated FROM op_metrics);<br>END;</pre><p><em>The procedure is created within a schema in Unity Catalog.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*Ch9vjG3TGp2v2mci" /></figure><h4>▶ Execution</h4><p>Procedures are executed with the CALL statement:</p><pre>DECLARE OR REPLACE VARIABLE num_inserted int;<br>DECLARE OR REPLACE VARIABLE num_updated int;<br><br>/* Perform DML operation on sales.gold.sales_fact */<br><br>CALL main.default.get_ins_upd_metrics(&#39;sales.gold.sales_fact&#39;, num_inserted, num_updated);</pre><h4>▶ Control Flow Support</h4><p>Databricks procedures support:</p><ul><li>IF, CASE, WHILE, LOOP, REPEAT, FOR</li><li>Nested blocks and conditional logic</li></ul><h4>▶ Why Use Procedures?</h4><p>Stored procedures in Databricks improve:</p><ul><li><strong>Modularity</strong>: Define logic once, reuse many times</li><li><strong>Maintainability</strong>: Centralize business logic in SQL</li><li><strong>Performance</strong>: Reduce client-server round trips by batching logic</li><li><strong>Governance</strong>: Secure and cataloged under Unity Catalog</li></ul><h3>Requirements &amp; Limitations</h3><ul><li>Public Preview in DBR 17.0</li><li>Unity Catalog must be enabled</li></ul><h3>Summary</h3><p>Procedures in Databricks SQL bring enterprise-grade SQL programming to the Lakehouse, and provide a direct path to migrate legacy stored procedures. With parameterization, control flow, and Unity Catalog integration, you can now design robust, modular pipelines and business logic directly within Databricks SQL.</p><blockquote>For more on SQL Scripting in Databricks please see: <a href="https://medium.com/dbsql-sme-engineering/databricks-sql-scripting-elevate-your-data-operations-ead9741b6a8a?source=post_settings_page-----ead9741b6a8a----0-----------------------------------">Databricks SQL Scripting: Elevate Your Data Operations</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb4ece0c9539" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dbsql-sme-engineering/introducing-stored-procedures-in-databricks-bb4ece0c9539">Introducing Stored Procedures in Databricks</a> was originally published in <a href="https://medium.com/dbsql-sme-engineering">DBSQL SME Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Integrate Databricks Unity Catalog with Immuta]]></title>
            <link>https://medium.com/@shyamrao_2844/how-to-integrate-databricks-unity-catalog-with-immuta-a8da4a8efc93?source=rss-82fab063cf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8da4a8efc93</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[immuta]]></category>
            <category><![CDATA[databricks-unity-catalog]]></category>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[lakehouse-architecture]]></category>
            <dc:creator><![CDATA[Shyam Rao]]></dc:creator>
            <pubDate>Sat, 10 May 2025 19:34:17 GMT</pubDate>
            <atom:updated>2025-05-10T19:34:17.399Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/0*iWXtTGWwaJdQ5Y50" /></figure><h3>Introduction</h3><p>In today’s data-driven world, securing sensitive information is paramount. <strong>Databricks Unity Catalog provides a unified governance solution for data and AI, while Immuta offers data access control and policy enforcement for your entire data estate</strong>.</p><p>Combining these tools creates a centralized solution for your data environment. This post will walk you through how to integrate Immuta with Databricks Unity Catalog, enabling you to manage and protect your data estate with ease.</p><p>Unity Catalog provides the mechanism for authorization, row-level security, and column-level masking natively. You can define security within the databricks platform to control access to structured data (including external and foreign tables), unstructured data, and AI models. In addition, when Immuta is included in the overall architecture, data policies can be defined centrally and pushed down to Unity Catalog for enforcement.</p><h3>Integrating Immuta with Databricks Unity Catalog</h3><p>The first step is to establish a connection between Immuta and your Databricks workspace. Here’s a breakdown of the process:</p><p><strong>1. Service Principal Setup</strong></p><ul><li>Create a Service Principal (SP) in your Databricks Workspace.</li><li>Generate a secret for the SP.</li><li>Assign the `CREATE CATALOG` privilege to the SP.</li><li>Grant read access to the System tables.</li><li><em>Example: Create a Service Principal named `</em>HLSImmutaSP`<em> for this integration.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*mAG0daUQt1ePwXe8" /></figure><p><strong>2. Adding a Native Integration in Immuta</strong></p><ul><li>Navigate to App Settings in Immuta and click on the Integrations tab.</li><li>Click “Add Native Integration”.</li></ul><p><strong>3. Configuration Details</strong></p><ul><li><strong>Native Integration Type:</strong> Databricks Unity Catalog.</li><li><strong>Databricks Workspace Server Hostname:</strong> Enter the hostname of your Databricks workspace.</li><li><strong>SQL Warehouse HTTP Path:</strong> Provide the HTTP Path for your SQL Warehouse endpoint.</li><li><em>Note: You can find these details, Hostname and HTTP Path, in your Databricks SQL Warehouse settings under Connection details.</em></li><li><em>Note: Ensure that the Immuta server can communicate with the Databricks Workspace; modify any IP Enable List if required.(??)</em></li><li><strong>Catalog Name:</strong> Specify the name of the catalog in Unity Catalog that Immuta will manage. Example: `immuta_integration`<em>.</em></li></ul><p><strong>4. Authentication</strong></p><ul><li>Enter the Client ID and Client Secret generated for your Service Principal (e.g., <em>`</em>HLSImmutaSP`).</li></ul><p><strong>5. Automatic Setup</strong></p><ul><li>Choose “Automatic setup” and save the integration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kFQtEd5oWXQVHi_s" /></figure><ul><li>The Immuta catalog is created in UC.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fYTl8dDhRXlAjBeq" /></figure><h3>Creating and Syncing Data Policies</h3><p>Once the integration is enabled, you can begin creating and syncing data policies between Immuta and Unity Catalog.</p><h4>Data Source Setup</h4><p><strong>1. Identify UC Tables</strong></p><ul><li>For example, four tables (`patient_br`, `patient_si`, `code_m`, `g_patient_d`) were created in the `main` catalog and `clinical` schema in Unity Catalog.</li></ul><p><strong>2. Create Data Sources in Immuta</strong></p><ul><li>Navigate to the Data Sources section in Immuta and click New Data Source.</li><li>Choose Databricks as the Data Platform.</li><li>Specify the connection information to Databricks.</li><li>Select the relevant Virtual Population, i.e., the tables in Databricks.</li><li>In this case, select the four tables in `main.clinical` schema.</li><li>Create the data sources.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FNbX7-FK_ndKnKyN" /></figure><h4>Access Policies in Immuta</h4><p>Immuta allows you to define Data Policies to control access to your data sources. For Databricks with Unity Catalog, Immuta translates these policies into native Unity Catalog row filters, and masking policies.</p><p><strong>Column Masking Example:</strong></p><p><strong>1. Scenario</strong></p><ul><li>We want to mask the `ssn` column in the `main.clinical.g_patient_d` table, replacing it with “REDACTED”.</li><li>Note that the ssn column has been tagged with “Social Security Number”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/0*YcuO55VOgPC1aVRr" /></figure><p><strong>2. Create a Global Data Policy</strong></p><ul><li>In Immuta, create a global data policy that masks any column tagged as “Social Security Number” with “REDACTED.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/0*Rbj_VEO13ABsuCxs" /></figure><p><strong>3. Policy Syncing</strong></p><ul><li>Immuta automatically syncs this policy with Unity Catalog, creating a masking function in the `immuta_integration` catalog.</li><li>Note: The integration service principal (<em>`</em>HLSImmutaSP`) has to be granted MANAGE and MODIFY privileges on the table.</li><li>The following SQL statements are executed via the integration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/0*oYeCU8nH8OLc5mF-" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/0*w_Ej8xo9R3o4MF4s" /></figure><p><strong>Row Filtering Example:</strong></p><p><strong>1. Scenario</strong></p><ul><li>We want to implement a row filter for the `g_patient_d` table:</li><li>Users in the `hls-admin` Databricks group can see all rows.</li><li>Other users can only see rows where the `data_source` column contains “ABC Systems”.</li></ul><p><strong>2. Create a Local Data Policy</strong></p><ul><li>Create a local data policy in Immuta that defines these conditions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*pLlk-RGZRVBsV7Wq" /></figure><p><strong>3. Policy Syncing</strong></p><ul><li>Immuta syncs this policy with Unity Catalog, creating a Row Filter SQL function in the `immuta_integration` catalog.</li><li>Note: The integration service principal (<em>`</em>HLSImmutaSP`) has to be granted MANAGE and MODIFY privileges on the table.</li><li>The following SQL statements are executed via the integration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/0*PMvnPtzCK44fFc28" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/0*Q-mZdOuq_6NsFM9P" /></figure><h4><strong>Querying the Table in Databricks</strong></h4><p><strong><em>Catalog Explorer view of the table:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*alKms83YxTH81HbZ" /></figure><p><strong><em>SELECT rows from g_patient_d:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M_A1AHvW0sfhO6ew" /></figure><h3>Conclusion</h3><p>Integrating Immuta with Databricks Unity Catalog provides a powerful solution for securing and governing your data in a central fashion. Immuta’s policy-driven approach, combined with Unity Catalog’s unified governance, ensures that your data is protected and accessed appropriately. By automatically syncing policies with Unity Catalog, Immuta streamlines the process of centrally managing data access controls.</p><p><strong>Key Takeaways</strong></p><ul><li>Unity Catalog supports external access control solutions like Immuta.</li><li>Immuta policies are translated into native Unity Catalog row filters and masks.</li><li>Synchronization is handled via REST APIs.</li></ul><p><strong>Call to Action</strong></p><p>Explore how Immuta and Databricks Unity Catalog can enhance your data security and governance. Try implementing these steps in your own environment to see the benefits firsthand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8da4a8efc93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for Building the Presentation Layer in a Lakehouse]]></title>
            <link>https://medium.com/dbsql-sme-engineering/data-warehouse-design-presentation-layer-62e0b192691d?source=rss-82fab063cf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/62e0b192691d</guid>
            <category><![CDATA[data-warehousing]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[databricks-sql]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[how-to]]></category>
            <dc:creator><![CDATA[Shyam Rao]]></dc:creator>
            <pubDate>Fri, 02 May 2025 18:58:39 GMT</pubDate>
            <atom:updated>2026-03-17T22:00:11.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*o3n6iJRpp8MDuBFG" /></figure><p><em>By </em><a href="https://www.linkedin.com/in/shyamrrao/"><em>Shyam Rao</em></a><em>, </em><a href="https://www.linkedin.com/in/ambarish-dongaonkar-35512511/"><em>Ambarish Dongaonkar</em></a></p><p>The <strong>Presentation Layer</strong> is the final stage in the Lakehouse data architecture. This layer contains curated, user-friendly data for business analysts, decision-makers, and BI applications. The data is generally organized into star schemas, aggregated summary tables, business views, and APIs, enabling integration with BI tools such as <a href="https://www.databricks.com/product/business-intelligence">Databricks AI/BI</a>, Tableau, and Power BI for interactive analysis and reporting.</p><h4>Key Features</h4><ul><li><strong>User-Centric</strong>: Tailored for analysts and decision-makers, providing clean and accessible data.</li><li><strong>Abstracts Complexity</strong>: Simplifies raw data into enriched, pre-aggregated views, encapsulating business logic.</li><li><strong>Supports Reporting</strong>: Optimizes for fast querying, visualizations, and calculated measures.</li><li><strong>Secure</strong>: Enables governed, masked, and role-based access to sensitive data.</li></ul><h4>Best Practices</h4><ol><li><strong>Simplify Data</strong>: Use business-friendly schemas with clear relationships.</li><li><strong>Optimize Performance</strong>: Precompute aggregations and materialize views for efficiency.</li><li><strong>Enforce Security</strong>: Implement role-based access control, data masking, and audit trails.</li><li><strong>Monitor Usage</strong>: Track query performance and usage patterns for optimization.</li></ol><p>The Presentation Layer bridges technical complexity and business needs, ensuring <strong>fast, secure, and actionable data</strong> for decision-making.</p><h4>How Databricks Fits into the Presentation Layer</h4><p>Databricks has several tools to implement the presentation layer:</p><ol><li><strong>Delta Universal Format</strong>: Store pre-aggregated or denormalized data for BI consumption.</li><li><strong>Materialized Views</strong>: Precompute results of complex queries and aggregations for optimized performance.</li><li><strong>Databricks SQL</strong>: Create queries, dashboards, and visualizations directly in Databricks.</li><li><strong>Integration with BI Tools</strong>: Connect Databricks directly with tools like Power BI, Tableau, or Looker for seamless visualization and reporting.</li><li><strong>Unity Catalog (UC)</strong>: Unified data and AI governance for enhanced security and compliance.</li></ol><h3>How do I build my presentation layer?</h3><p>The presentation layer comprises queryable objects such as <strong>tables</strong>, <strong>materialized views,</strong> and <strong>views</strong>.</p><h3>Materialized Views</h3><h4>What Are Materialized Views in Databricks?</h4><p>In Databricks SQL, materialized views are UC-managed tables that allow users to precompute results based on the latest version of data in source tables. CREATE and REFRESH operations on materialized views are powered by serverless DLT pipelines.</p><h4>Why Use Materialized Views?</h4><p>a. Performance Optimization</p><ul><li><strong>Reduced Query Time</strong>: Materialized views precompute and store the results of complex or computationally expensive queries. When users query the materialized view, they access the precomputed data, leading to faster query responses.</li><li><strong>Efficient Aggregations</strong>: Instead of recalculating aggregations (for example, sums, averages) each time, a materialized view can store these precomputed results. For repetitive queries, materialized views reduce compute overhead and optimize resources.</li></ul><p>b. Simplified Querying</p><ul><li><strong>Abstracts Complexity</strong>: Users can query the materialized view without worrying about the underlying data’s complexity or transformations. Transformations like joins, aggregations, and filters are encapsulated in the view.</li><li><strong>Business-Friendly Data Models</strong>: Materialized views can expose preprocessed data tailored for business use cases.</li></ul><p>c. Incremental Updates</p><ul><li>Many queries can be incrementally refreshed when running updates on materialized views using serverless pipelines. Incremental refreshes save compute costs by detecting changes in the data sources used to define the materialized view and incrementally computing the result.</li></ul><p>d. Compatibility with BI Tools</p><ul><li>Materialized views integrate well with BI tools (for example, Power BI, Tableau). They offer pre-aggregated or preprocessed datasets that speed up dashboard loading times.</li></ul><p>e. Cost Savings</p><ul><li><strong>Lower Compute Costs</strong>: Precomputing results in materialized views reduces the need for repetitive expensive computations, saving on Databricks compute costs.</li><li><strong>Resource Efficiency</strong>: The cluster resources can be allocated more efficiently because fewer resources are needed to serve end-user queries.</li></ul><h4>Limitations of Materialized Views</h4><ul><li>Not real-time: Materialized views are not updated in real-time. The frequency of updates depends on your refresh schedule.</li><li>Storage-overhead: Since materialized views store pre-computed data, they consume additional storage.</li></ul><h4>How to Create and Refresh Materialized Views in Databricks</h4><p><strong>Create a Materialized View (</strong><a href="https://docs.databricks.com/en/sql/language-manual/sql-ref-syntax-ddl-create-materialized-view.html"><strong>AWS</strong></a><strong>|</strong><a href="https://learn.microsoft.com/en-us/azure/databricks/sql/language-manual/sql-ref-syntax-ddl-create-materialized-view"><strong>Azure</strong></a><strong>|</strong><a href="https://docs.databricks.com/gcp/en/sql/language-manual/sql-ref-syntax-ddl-create-materialized-view"><strong>GCP</strong></a><strong>):</strong></p><ol><li>Write a query for your materialized view (for example, aggregations, joins).</li></ol><pre>CREATE MATERIALIZED VIEW sales_by_region_mv<br>AS<br>SELECT region, customer, item, SUM(sales) AS total_sales<br>FROM transactions<br>GROUP BY region<br>CLUSTER BY AUTO;</pre><p>Note: <a href="https://www.databricks.com/resources/demos/tours/governance-uc/row-and-column-level-security-with-unity-catalog">Row-Level Security and Column-Level Masking</a> can be defined on MVs.</p><p><strong>Refresh a Materialized View (</strong><a href="https://docs.databricks.com/en/sql/language-manual/sql-ref-syntax-ddl-refresh-full.html"><strong>AWS</strong></a><strong>|</strong><a href="https://learn.microsoft.com/en-us/azure/databricks/sql/language-manual/sql-ref-syntax-ddl-refresh-full"><strong>Azure</strong></a><strong>|</strong><a href="https://docs.databricks.com/gcp/en/sql/language-manual/sql-ref-syntax-ddl-refresh-full"><strong>GCP</strong></a><strong>):</strong></p><p>1. Refresh the MV periodically using a Databricks Workflows Job:</p><pre>REFRESH MATERIALIZED VIEW sales_by_region_mv;</pre><p>2. Configure the schedule with the SCHEDULE clause during CREATE or using ALTER:</p><pre>...SCHEDULE EVERY 2 HOURS...<br>...SCHEDULE CRON &#39;0 0 0 * * ? *...</pre><p>Note: Refresh can be performed in either <strong>SYNC</strong> or <strong>ASYNC</strong> mode.</p><p><strong>Monitoring Maintenance Activities</strong></p><pre>SELECT<br>*<br>FROM<br>event_log(TABLE(catalog.schema.table))<br>WHERE event_type in (&#39;maintenance_progress&#39;, &#39;background_operation&#39;)<br>ORDER BY<br>timestamp desc;</pre><h4>Improving Performance Using Materialized Views</h4><ol><li>Use Liquid Clustering to optimize the data layout and maximize query performance. Take advantage of <strong>Predictive Optimization</strong> (<a href="https://docs.databricks.com/aws/en/optimizations/predictive-optimization">AWS</a>|<a href="https://learn.microsoft.com/en-us/azure/databricks/optimizations/predictive-optimization">Azure</a>|<a href="https://docs.databricks.com/gcp/en/optimizations/predictive-optimization">GCP</a>) and Auto Clustering.</li><li>Creating a wide table, for example, including attributes from a dimension, can result in better data skipping based on column statistics.</li><li>To generate optimized plans, specify constraints such as <a href="https://www.databricks.com/blog/primary-key-and-foreign-key-constraints-are-ga-and-now-enable-faster-queries">PRIMARY KEY..RELY</a> and column constraints such as NOT NULL.</li></ol><h3>Views</h3><p>Enhance your dashboarding and reporting processes by creating and exposing views on top of dimension and fact tables. <strong>Create a view on a table or a materialized view</strong>.</p><h4>Views can be used to:</h4><ol><li><strong>Tailor the presentation</strong>: Expose only essential attributes (for example, primary address).</li><li><strong>Simplify attribute representation</strong>: ARRAY and STRUCT (and <a href="https://www.databricks.com/blog/introducing-open-variant-data-type-delta-lake-and-apache-spark">VARIANT</a>) types might not be compatible with all BI tools.</li><li><strong>Create role-playing dimensions</strong>: For example, shipping facility vs. receiving facility.</li><li><strong>Use consistent formulas</strong>: Encapsulate business logic.</li><li><strong>Make extensible</strong>: Easily include new calculated measures based on user request.</li><li><strong>Focus on relevant data</strong>: Use filters to include only the necessary data. For instance, exclude soft-deleted records or outdated versions based on your specific use case.</li></ol><h4>Agile Data Modeling with Views</h4><p>Views are beneficial in an agile environment, where business users frequently request new metrics. A well-designed Lakehouse architecture enables simple modifications, such as adding calculated columns in views. You also have the freedom to change the data representation in the backing table or materialized view. I have benefited from this design on multiple occasions.</p><h3>Query Optimization Tip</h3><p>When querying data, retrieve only the columns essential for analysis to optimize performance using predictive I/O and reduce fetch times.</p><h3>Conclusion</h3><p>By following these guidelines, you can effectively design and optimize your Star Schema (or other models such as Business Views) in Databricks SQL, leveraging advanced features and best practices to enable high performance and scalability. <a href="https://www.databricks.com/product/databricks-sql">Get Started!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62e0b192691d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dbsql-sme-engineering/data-warehouse-design-presentation-layer-62e0b192691d">Best Practices for Building the Presentation Layer in a Lakehouse</a> was originally published in <a href="https://medium.com/dbsql-sme-engineering">DBSQL SME Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Databricks SQL Scripting: Elevate Your Data Operations]]></title>
            <link>https://medium.com/dbsql-sme-engineering/databricks-sql-scripting-elevate-your-data-operations-ead9741b6a8a?source=rss-82fab063cf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/ead9741b6a8a</guid>
            <category><![CDATA[databricks-sql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[sql-scripting]]></category>
            <dc:creator><![CDATA[Shyam Rao]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 19:06:24 GMT</pubDate>
            <atom:updated>2025-04-25T19:06:24.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*EPbbTnC6i19Y69Npqor3gQ.png" /></figure><h3>Introduction</h3><p>Databricks continues to innovate, and its SQL Scripting feature, now in Public Preview (Databricks Runtime 16.3 and later), is a powerful addition to the Lakehouse Platform. While SQL is fundamental for data analysis, SQL Scripting extends its capabilities, enabling you to build sophisticated, automated, and efficient data pipelines. Let’s dive into how this feature can transform your workflows.</p><h3>What is Databricks SQL Scripting?</h3><p>SQL Scripting allows you to execute multiple SQL statements sequentially within a single script, using SQL/PSM standard-based syntax. Each script begins with a `BEGIN … END` compound statement block. This block can include variable declarations, condition handlers for exceptions, and a body containing various SQL operations and control flow statements.</p><h3>Key Features and Benefits</h3><ul><li><strong>Procedural Logic:</strong> Go beyond simple queries with loops (`FOR`, `WHILE`), conditional logic (`IF`, `CASE`), and control statements (`LEAVE`, `ITERATE`).</li><li><strong>Comprehensive SQL Support:</strong> Execute DDL (`ALTER`, `CREATE`, `DROP`), DCL (`GRANT`, `REVOKE`), and DML (`INSERT`, `UPDATE`, `DELETE`, `MERGE`) statements within your scripts.</li><li><strong>Dynamic SQL:</strong> Use `EXECUTE IMMEDIATE` to construct and execute SQL statements dynamically.</li><li><strong>Robust Error Handling:</strong> Implement condition handlers to catch exceptions (`DIVIDE_BY_ZERO`, SQLSTATEs, SQLEXCEPTION) and manage script execution flow.</li><li><strong>Modularity and Reusability:</strong> Structure your scripts for better organization and maintainability, setting the stage for reusable components.</li><li><strong>Integration with Databricks Ecosystem:</strong> Seamlessly integrate SQL scripts with notebooks, jobs, and Delta Lake for end-to-end data workflows.</li></ul><h3>Diving into the Details</h3><p><strong>Compound Statements (`BEGIN … END`):</strong> These are the foundation of SQL Scripting. They allow you to declare local variables, define condition handlers, and structure your script’s logic.</p><p><strong>Passing Data:</strong></p><ul><li><strong>Session Variables:</strong> Ideal for passing scalar values or small sets of arrays/maps between SQL scripts.</li><li><strong>Parameter Markers:</strong> Use these to pass data from external environments (notebook widgets, Python) into your SQL scripts.</li></ul><p><strong>Variable Scoping:</strong> Variables are scoped within their compound statements. Databricks uses name resolution to find the correct variable, starting from the innermost scope. You can use labels to disambiguate duplicate variable names.</p><p><strong>Condition Handling:</strong></p><ul><li>Intercept and process exceptions using `RESIGNAL`, `SIGNAL`, or exit without an exception.</li><li>Handle named conditions, SQLSTATEs, or generic `SQLEXCEPTION` to ensure robust error management.</li><li>The “most appropriate handler” is selected based on specificity and scope.</li></ul><p><strong>Control Flow Statements:</strong> Databricks supports a rich set of control flow statements:</p><ul><li>`CASE`, `IF THEN ELSE` for conditional logic.</li><li>`FOR`, `LOOP`, `REPEAT`, `WHILE` for iterations.</li><li>`LEAVE`, `ITERATE` for loop control.</li><li>`SIGNAL`, `RESIGNAL` for exception handling.</li></ul><h3>Practical Use Cases</h3><ol><li><strong>Automating Operational Tasks: a) </strong>Modifying object ownership across catalogs or schemas <strong>b)</strong> Creating “current” views for Type 2 dimensions.</li><li><strong>Row-by-row conditional logic with error logging:</strong> E.g., checking file headers for schema conformance during ETL.</li><li><strong>Procedural Retry Logic:</strong> E.g., retry the same or other operation based on catching a transient error, or based on the results of a previous query.</li><li><strong>Dynamic SQL with procedural branching:</strong> Automate data population by executing different logic based on metadata or config tables.</li></ol><h4>Example: Creating “Current” Views</h4><blockquote>SQL Scripting is in public preview. Run on SQL Warehouse, Preview channel.</blockquote><pre>-- Catalog and Schema to use for the example<br>DECLARE OR REPLACE VARIABLE catalog_name STRING = &#39;main&#39;;<br>DECLARE OR REPLACE VARIABLE full_schema_name STRING = catalog_name || &#39;.patient_visit_star&#39;;</pre><blockquote>Example tables will be created in schema main.patient_visit_star. The variables above can be updated to specify a different catalog and schema. Ensure that the current user has the required privileges such as USE CATALOG, CREATE SCHEMA (if required) and CREATE TABLE.</blockquote><pre>/* Example Data Setup */<br><br>-- Create schema in an existing catalog, if new<br>CREATE SCHEMA IF NOT EXISTS IDENTIFIER(full_schema_name);<br><br>-- Set default schema<br>USE IDENTIFIER(full_schema_name);<br><br>-- Create a Type 2 dimension table<br>CREATE OR REPLACE TABLE patient_ss_dim (patient_sk BIGINT GENERATED BY DEFAULT AS IDENTITY,<br>  patient_src_id STRING, first_name STRING, last_name STRING, gender_code STRING,<br>  effective_start_date DATE, effective_end_date DATE, current_flag CHAR(1), insert_date TIMESTAMP);<br><br>-- Add rows<br>INSERT INTO patient_ss_dim(patient_src_id, first_name, last_name, gender_code,<br>  effective_start_date, effective_end_date, current_flag, insert_date)<br>VALUES (&#39;P12113&#39;, &#39;Alaine226&#39;, &#39;Willms744&#39;, &#39;F&#39;, to_date(&#39;2021–01–01&#39;, &#39;yyyy-MM-dd&#39;), to_date(&#39;2025–04–01&#39;, &#39;yyyy-MM-dd&#39;), &#39;N&#39;, CURRENT_TIMESTAMP);<br><br>INSERT INTO patient_ss_dim(patient_src_id, first_name, last_name, gender_code,<br>  effective_start_date, effective_end_date, current_flag, insert_date)<br>VALUES (&#39;P12113&#39;, &#39;Alaine226&#39;, &#39;Benny518&#39;, &#39;F&#39;, to_date(&#39;2025–04–01&#39;, &#39;yyyy-MM-dd&#39;), NULL, &#39;Y&#39;, CURRENT_TIMESTAMP);<br><br>-- Create a Type 1 dimension table<br>CREATE TABLE IF NOT EXISTS organization_ss_dim (organization_sk BIGINT GENERATED BY DEFAULT AS IDENTITY,<br>  organization_src_id STRING, organization_name STRING, insert_date TIMESTAMP);</pre><blockquote>Note that the SQL Script is included in an individual cell that starts with the BEGIN statement. Adding the SQL Script below!</blockquote><pre>-- Create a view for every Type 2 dimension, that<br>-- restricts the rows in the table to the current version<br>BEGIN<br>  DECLARE createview_sql STRING;<br>  DECLARE num_views_created INT DEFAULT 0;<br><br>  cv:<br>  FOR (SELECT table_name FROM main.information_schema.columns<br>       WHERE table_catalog || &#39;.&#39; || table_schema = session.full_schema_name AND table_name LIKE &#39;%dim&#39; AND column_name = &#39;current_flag&#39;)<br>  DO<br>    -- Loop over each Type 2 dimension table (name)<br><br>    -- Build the CREATE VIEW statement<br>    SET createview_sql = &quot;CREATE OR REPLACE VIEW &quot;<br>      || session.full_schema_name || &quot;.&quot; || table_name || &quot;_curr_v&quot;<br>      || &quot; AS SELECT * EXCEPT(effective_start_date, effective_end_date, current_flag) FROM &quot;<br>      || session.full_schema_name || &quot;.&quot; || table_name<br>      || &quot; WHERE current_flag = &#39;Y&#39;&quot;;<br><br>    -- Execute the CREATE VIEW statement<br>    EXECUTE IMMEDIATE createview_sql;<br><br>    -- Count the number of views created<br>    SET num_views_created = num_views_created + 1;<br>  END FOR cv;<br><br>  -- Display a result message<br>  IF num_views_created &gt; 0 THEN<br>    SELECT num_views_created || &#39; view(s) created.&#39; AS result;<br>  ELSE<br>    SELECT &#39;No dimension tables found.&#39; AS result;<br>  END IF;<br><br>END;</pre><pre>-- Select from dimension table<br>SELECT * FROM patient_ss_dim;</pre><pre>-- Select from current view<br>SELECT * FROM patient_ss_dim_curr_v;</pre><h4>Why SQL Alone Isn’t Enough for these Use Cases</h4><p>Without procedural extensions like SQL Scripting, you can’t construct and execute dynamic SQL conditionally based on row data. While most DML is performant when using set-based (SQL) operations, complex scenarios require procedural logic.</p><h3>Conclusion</h3><p>Databricks SQL Scripting (<a href="https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-scripting">AWS</a>|<a href="https://learn.microsoft.com/en-us/azure/databricks/sql/language-manual/sql-ref-scripting">Azure</a>|<a href="https://docs.databricks.com/gcp/pt/sql/language-manual/sql-ref-scripting">GCP</a>) empowers data professionals to move beyond basic SQL queries and build sophisticated, automated data pipelines. By combining the simplicity of SQL with the power of procedural logic, error handling, and dynamic execution, you can streamline your workflows and unlock new possibilities in data engineering. Harness the power of SQL Scripting and transform how you manage and process data in Databricks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ead9741b6a8a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dbsql-sme-engineering/databricks-sql-scripting-elevate-your-data-operations-ead9741b6a8a">Databricks SQL Scripting: Elevate Your Data Operations</a> was originally published in <a href="https://medium.com/dbsql-sme-engineering">DBSQL SME Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement Star Schema & OBT in Databricks SQL]]></title>
            <link>https://medium.com/@shyamrao_2844/implement-star-schema-obt-in-databricks-sql-46504fc37be2?source=rss-82fab063cf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/46504fc37be2</guid>
            <category><![CDATA[databricls-sql]]></category>
            <category><![CDATA[star-schema]]></category>
            <category><![CDATA[one-big-table]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Shyam Rao]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 01:46:34 GMT</pubDate>
            <atom:updated>2025-04-22T01:53:05.307Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the context of Star Schemas and One Big Table, Databricks SQL enables ELT developers and analytics engineers to design, transform, validate, and optimize data pipelines effectively. SQL proficiency empowers ELT and analytics engineers to manage the end-to-end data lifecycle and ensure the quality and integrity of data within the organization’s data infrastructure.</p><h3>Star Schema</h3><h4>Definition</h4><p>The Star Schema is a popular database design used in data warehousing where data from transactional databases is extracted, transformed, and loaded into a schema consisting of a central fact table surrounded by dimension tables.</p><h4>Components</h4><p><strong>Fact Table</strong>: Contains metrics or facts related to the business process events. It typically consists of foreign key columns referencing dimension tables and numeric fact columns.</p><p><strong>Dimensions</strong>: Provide context to the facts by modeling entities and attributes of interest as labels in reports. Dimension tables are denormalized for easy browsing and often include a numeric surrogate key.</p><h4>Characteristics</h4><ul><li><strong>Optimized for Analytical Queries</strong>: Star schemas are designed for analytical queries and reporting, making them suitable for data warehousing environments.</li><li><strong>Simplicity and Understandability</strong>: The structure of star schemas is intuitive and easy to understand, featuring centralized fact tables surrounded by related dimension tables.</li><li><strong>Performance Optimization</strong>: Analytical queries on star schema databases tend to perform well due to simple joins between the fact table and dimension tables.</li><li><strong>Scalability</strong>: Star schemas can effectively handle large datasets and support efficient indexing strategies.</li><li><strong>Enhanced Data Analysis</strong>: The design promotes better data analysis and reporting capabilities by providing comprehensive context through dimension tables.</li><li><strong>Query Flexibility</strong>: Star schema design allows for flexible querying, enabling ad-hoc analysis and reporting.</li></ul><h4>Pros</h4><ol><li>Ease of Maintenance</li><li>Support for Business Intelligence (BI) Tools</li></ol><h4>Cons</h4><ol><li>Complexity in Updates</li><li>Performance Challenges with Complex Queries</li></ol><h3>One Big Table</h3><h4>Definition</h4><p>The One Big Table design pattern refers to a database modeling approach where all data is stored in a single table, typically denormalizing the data and combining multiple entities or relations into one large table. This corresponds to creating wide tables that include all the data items and metrics required to perform a specific set of analyses.</p><h4>Characteristics</h4><ul><li><strong>Single Table Storage</strong>: All data is stored in a single table, combining multiple entities or relations into one large table.</li><li><strong>Denormalization</strong>: The data is typically denormalized, meaning that redundant data may exist to avoid joins.</li><li><strong>Wide Tables</strong>: Tables are designed to be wide, including all necessary data elements and metrics for specific analyses.</li><li><strong>Suited for Specific Use Cases</strong>: Primarily used for one-off analysis, prototyping, and data munging tasks.</li></ul><h4>Pros</h4><ol><li>Simplified Queries</li><li>Performance for predictable Query Patterns</li><li>Prototyping and Rapid Development</li></ol><h4>Cons</h4><ol><li>Data redundancy</li><li>Maintainability and Scalability</li></ol><h3>Implement in DBSQL</h3><h4>Publish Data Model</h4><ol><li><strong>Design Dimensions and Fact Tables</strong>:</li></ol><ul><li>Design your dimensions and fact tables according to your data model requirements.</li></ul><p>2. <strong>Deploy Tables</strong>:</p><ul><li>Use Databricks SQL Queries or SQL notebooks to deploy the tables. You can create tables using CREATE TABLE statements.</li><li>Optimize the data layout using Liquid Clustering for better performance.</li></ul><p>3. <strong>Utilize </strong><a href="https://www.databricks.com/product/repos"><strong>Databricks Git Folders</strong></a><strong> with CI/CD Integration</strong>:</p><ul><li>Store your SQL scripts in Git.</li><li>Implement CI/CD pipelines to automate the deployment process.</li></ul><p>4. <strong>Document Data in Unity Catalog</strong>:</p><ul><li>Add descriptions using simple Markdown, column comments, and tags for business metadata in Unity Catalog.</li><li>Create notebooks with Markdown and example queries to document your data model and usage.</li></ul><h4>Accelerate ELT</h4><p><strong>Data Profiling</strong>:</p><ul><li>Use Lakehouse Federation (<a href="https://docs.databricks.com/en/query-federation/index.html">AWS</a>|<a href="https://learn.microsoft.com/en-us/azure/databricks/query-federation/">Azure</a>|<a href="https://docs.databricks.com/gcp/en/query-federation/">GCP</a>) to connect to various data sources during the exploratory phase.</li></ul><p><strong>Data Ingestion</strong>:</p><ol><li>COPY INTO command</li></ol><ul><li>Utilize the COPY INTO command for batch file ingestion into Delta Lake.</li><li>Ingests files with exactly once semantics.</li></ul><p>2. STREAMING Tables (<a href="https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-ddl-create-streaming-table">AWS</a>|<a href="https://learn.microsoft.com/en-us/azure/databricks/sql/language-manual/sql-ref-syntax-ddl-create-streaming-table">Azure</a>|<a href="https://docs.databricks.com/gcp/en/sql/language-manual/sql-ref-syntax-ddl-create-streaming-table">GCP</a>)</p><ul><li>Create streaming tables using the CREATE STREAMING TABLE command for incremental data processing.</li></ul><p><strong>Data Quality</strong>:</p><ol><li>Data Quality Expectations</li></ol><ul><li>Expectations allow you to define specific criteria or rules that the data must adhere to.</li><li>Create EXPECT constraint on streaming tables.</li></ul><p>2. Check Constraint</p><ul><li>Rules applied to data within a table.</li><li>Add CHECK constraints to the table to ensure data quality and integrity.</li></ul><p><strong>Data Transformation</strong>:</p><p>1. <a href="https://www.databricks.com/glossary/materialized-views">Materialized Views</a></p><ul><li>Create materialized views for precomputing results based on the latest data in source tables.</li><li>Materialized views provide a simple, declarative way to process data for compliance, corrections, aggregations, or general change data capture (CDC).</li></ul><p>2. Queries and SQL pipelines</p><ul><li>Use SQL tasks within a Workflow Job to run Databricks SQL Queries on your SQL Warehouse.</li><li>Use features such as Temporary Views, MERGE, functions, SQL variables, EXECUTE IMMEDIATE, job parameters, sharing information between tasks, running tasks conditionally, etc.</li></ul><p><strong>Orchestration</strong>:</p><ul><li>Use Databricks Workflows for orchestrating your tasks and jobs.</li><li>Implement automated scheduling for Data Definition Language (DDL) operations.</li><li>Refresh tables and materialized views on a Schedule.</li></ul><h3>In Conclusion</h3><p>Databricks SQL provides all the tools required to implement data warehouses and wide tables for SQL developers, while providing the best price to performance ratio of all cloud Data Warehouses.</p><p><strong>See Also</strong>:</p><p><a href="https://medium.com/dbsql-sme-engineering/star-schema-data-modeling-best-practices-on-databricks-sql-8fe4bd0f6902">Star Schema Data Modeling Best Practices on Databricks SQL</a>.</p><p><a href="https://medium.com/dbsql-sme-engineering/databricks-sql-intelligent-performance-automatically-6f54f1920690?source=your_stories_page--------------------------------------------">Databricks SQL: Intelligent Performance, Automatically</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46504fc37be2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Databricks SQL: Intelligent Performance, Automatically]]></title>
            <link>https://medium.com/dbsql-sme-engineering/databricks-sql-intelligent-performance-automatically-6f54f1920690?source=rss-82fab063cf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f54f1920690</guid>
            <category><![CDATA[liquid-clustering]]></category>
            <category><![CDATA[predictive-optimization]]></category>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[databricks-sql]]></category>
            <category><![CDATA[query-optimization]]></category>
            <dc:creator><![CDATA[Shyam Rao]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 18:38:02 GMT</pubDate>
            <atom:updated>2025-04-17T18:38:02.607Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ihEj9P3_W_c_1o9m" /></figure><h3>Overview</h3><p>In today’s data-driven world, optimizing query performance in Databricks SQL is crucial for efficient and cost-effective analytics. Managing large datasets and ensuring fast query execution can be challenging, but Databricks offers powerful features to address these issues. Data Skipping and Predictive I/O are two key features that enhance query performance by reducing unnecessary reads and optimizing how data is retrieved. This combination leads to faster, cost-efficient analytics, especially in Databricks SQL and Photon. Data Skipping relies on file layout to be effective because it works by skipping over irrelevant data based on stored statistics (e.g., min/max values) at the file level. If data is not well organized, skipping won’t be as efficient.</p><h3>Optimizing Performance</h3><h4><strong><em>Liquid Clustering</em></strong></h4><p>Liquid Clustering (LC) for Delta tables ensures files contain similar values for better min/max statistics. Liquid Clustering is enabled at the table level, and you can select up to 4 columns as clustering keys. These columns are used to organize data dynamically, improving query performance and data skipping efficiency.</p><p>This involves:</p><ul><li>Clustering your large tables by defining the appropriate clustering keys.</li><li>Running <strong>OPTIMIZE</strong> on each table.</li></ul><h4>Table Maintenance</h4><p>Additional maintenance operations such as VACUUM and ANALYZE can lead to reduced storage cost and improved query performance.</p><p>This involves:</p><ul><li>Running <strong>VACUUM</strong> on each table.</li><li>Running <strong>ANALYZE</strong> to collect table-level and column-level statistics for the optimizer.</li></ul><p>Fortunately, Databricks offers Predictive Optimization, an automated solution that improves query performance and reduces storage costs by optimizing data layouts in the background. Maintenance operations are run as necessary, eliminating both unnecessary runs and the burden associated with tracking and troubleshooting performance.</p><h3>Predictive Optimization in Databricks</h3><p>Predictive Optimization (<a href="https://docs.databricks.com/aws/en/optimizations/predictive-optimization">AWS</a>|<a href="https://learn.microsoft.com/en-us/azure/databricks/optimizations/predictive-optimization">Azure</a>|<a href="https://docs.databricks.com/gcp/en/optimizations/predictive-optimization">GCP</a>) is an automated solution that improves query performance and reduces storage costs by optimizing data layouts in the background. Maintenance operations are run as necessary, eliminating both unnecessary runs and the burden associated with tracking and troubleshooting performance.</p><p><strong>Real-World Example:</strong></p><p>Recently, a customer encountered significant performance issues with their legacy queries. These queries involved multiple Common Table Expressions (CTEs) calling numerous tables and views, with views referencing each other and the same tables being queried repeatedly. This complex query structure resulted in slow execution and increased resource consumption. In such scenarios, Predictive Optimization is ideal. It can automatically analyze query patterns, optimize data layouts, and ensure efficient data retrieval, significantly improving the performance of these complex queries without requiring manual intervention or extensive query rewriting.</p><h4>Key Capabilities of Predictive Optimization</h4><ul><li><strong>Automatic Liquid Clustering Column Selection:</strong> Predictive Optimization (PO) monitors query workload and automatically applies/evolves clustering keys, eliminating the need for manual data layout decisions. PO sets clustering keys only when beneficial and monitors query and data patterns for continuous clustering optimization.</li><li><strong>Automated Maintenance:</strong> PO automatically runs <strong>OPTIMIZE</strong> to improve query performance and <strong>VACUUM</strong> to reduce storage costs.</li><li><strong>Set-and-Forget:</strong> Tables with the highest return-on-investment are prioritized for optimization.</li><li><strong>Serverless Compute:</strong> No need to manage clusters for optimization tasks, reducing operational overhead.</li><li><strong>Observability:</strong> Provides insights into operations performed, costs incurred, and performance impact, aiding in troubleshooting.</li></ul><h4>Predictive Optimization for Statistics</h4><ul><li><strong>Smart Delta Stats Collection:</strong> Overcomes the previous 32-column constraint, which limited the number of statistics that could be collected. By intelligently selecting relevant columns based on clustering and usage patterns, it ensures more comprehensive and effective query optimization. If a user manually specifies columns, those preferences take precedence.</li><li><strong>Query Optimizer Statistics Out-of-the-Box:</strong> With <strong>Photon</strong>, statistics are automatically gathered during write operations. Statistics become available immediately upon data loading. Subsequently, PO intelligently triggers <strong>ANALYZE</strong> in the background to ensure statistics remain current and reliable.</li><li><strong>Intelligent Backfill:</strong> Enhances statistics collection for historical data.</li></ul><h4><strong>E</strong>nabling Predictive Optimization</h4><p>You can enable predictive optimization (<a href="https://docs.databricks.com/aws/en/optimizations/predictive-optimization#enable-predictive-optimization">AWS</a>|<a href="https://learn.microsoft.com/en-us/azure/databricks/optimizations/predictive-optimization#enable">Azure</a>|<a href="https://docs.databricks.com/gcp/en/optimizations/predictive-optimization#enable-predictive-optimization">GCP</a>) for an account, a catalog, or a schema. All Unity Catalog managed tables inherit the account value by default. You can override the account default for a catalog or schema to enable or disable predictive optimization at that level.</p><h3>Recommendations for Performance</h3><p><strong>1. Test Performance</strong></p><ul><li>Conduct performance testing during development.</li><li>Test on data representative of production data.</li><li>If using non-production data, ensure that volume, file layout, and data skew are similar to production for accurate performance results. This includes the enabling of Predictive Optimization.</li></ul><p><strong>2. Enable Predictive Optimization</strong></p><p>Databricks recommends enabling predictive optimization for all Unity Catalog managed tables to simplify data maintenance and reduce storage costs. Enable automatic liquid clustering using the CLUSTER BY AUTO clause.</p><p><strong>3. Optionally set initial Cluster Keys</strong></p><p>Automatic Liquid Clustering depends on query activity and will require some lead time to activate. During this period, data skipping will still occur based on the ingestion-time clustering of the data.</p><p>When it’s critical to optimize the data layout of certain tables from the outset — such as large tables created during migration — you can manually select the cluster keys (<a href="https://docs.databricks.com/en/delta/clustering.html">AWS</a>|<a href="https://learn.microsoft.com/en-us/azure/databricks/delta/clustering">Azure</a>|<a href="https://docs.databricks.com/gcp/en/delta/clustering">GCP</a>) based on existing workloads and expected query patterns. Choose cluster keys based on common filter conditions in queries. You can also borrow from your findings during performance testing.</p><p>This ensures efficient data skipping right off the bat. You can later modify this to enable Automatic Liquid Clustering, allowing the layout to evolve and adapt to changing query patterns, by issuing the command: ALTER TABLE &lt;table_name&gt; CLUSTER BY AUTO;</p><h3>Conclusion</h3><p>By leveraging Predictive Optimization and Automatic Liquid Clustering, Databricks users can significantly reduce storage costs and improve query performance without manual intervention. These features automate essential maintenance tasks, optimize data layouts, and ensure up-to-date statistics, ultimately leading to faster and more cost-effective analytics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f54f1920690" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dbsql-sme-engineering/databricks-sql-intelligent-performance-automatically-6f54f1920690">Databricks SQL: Intelligent Performance, Automatically</a> was originally published in <a href="https://medium.com/dbsql-sme-engineering">DBSQL SME Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Star Schema Data Modeling Best Practices on Databricks SQL]]></title>
            <link>https://medium.com/@shyamrao_2844/star-schema-data-modeling-best-practices-on-databricks-sql-d285fd7bf97e?source=rss-82fab063cf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/d285fd7bf97e</guid>
            <dc:creator><![CDATA[Shyam Rao]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 18:11:56 GMT</pubDate>
            <atom:updated>2025-08-04T15:51:03.300Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/88/0*J_G6hd4EUVhv2cJ6.png" /></figure><p>Go To:</p><p><a href="https://medium.com/dbsql-sme-engineering/star-schema-data-modeling-best-practices-on-databricks-sql-8fe4bd0f6902">Star Schema Data Modeling Best Practices on Databricks SQL</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d285fd7bf97e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity Catalog: Have your cake and eat it too]]></title>
            <link>https://medium.com/@shyamrao_2844/unity-catalog-have-your-cake-and-eat-it-too-0e13515209c4?source=rss-82fab063cf46------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e13515209c4</guid>
            <category><![CDATA[data-warehousing]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[data-lake]]></category>
            <category><![CDATA[unity-catalog]]></category>
            <dc:creator><![CDATA[Shyam Rao]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 18:22:17 GMT</pubDate>
            <atom:updated>2025-05-19T03:07:38.097Z</atom:updated>
            <content:encoded><![CDATA[<p>Like I have seen, 80% of Data Warehousing projects do not have a Data Governance program. To realize later <em>“here is something I wish we had done before we spent 17 million dollars on this data warehouse</em>”.</p><p>Data governance is widely recognized as key for delivering reliable and consistent data, making it easy to build and maintain consistent analytics and AI solutions. However, there are cases where a quickstart project can de-prioritize the governance aspect in all the activity to produce dashboards and answers.</p><p>One of the tenets of the Databricks platform is to reduce data management and operational complexity so that you can focus on your business use cases and ensure data quality and achieve a positive and successful outcome for your business. To simplify data governance, the <a href="https://www.databricks.com/product/data-intelligence-platform">Databricks Data Intelligence Platform</a> offers a unified governance solution for data, analytics and AI. The nifty and hidden benefit of Databricks data governance is that it is simply baked into the implementation process. So that: you can have your cake and eat it too!</p><h3>Databricks Data Intelligence Platform</h3><p>The Databricks platform is a unified set of tools for building, deploying, sharing, and maintaining enterprise-grade data solutions at scale. Our customers use Databricks to process, store, clean, share, analyze, model, and monetize their datasets with solutions from BI to machine learning to generative AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/0*do_bPjFZJSKttgrM" /></figure><p>Use the Databricks platform to build and deploy data engineering workflows, machine learning models, analytics dashboards, and more.</p><h3>Unified Governance</h3><p>Databricks Unity Catalog is the industry’s first unified governance solution for data and AI on the <a href="https://docs.databricks.com/en/lakehouse/index.html">data lakehouse</a>. It helps simplify security and governance of your data by providing a central place to administer and audit data access. With <a href="https://www.databricks.com/product/unity-catalog">Unity Catalog</a>, organizations can seamlessly govern their structured and unstructured data, machine learning models, notebooks, dashboards and files on any cloud or platform.</p><p>Key features of Unity Catalog include:</p><ul><li>Define once, secure everywhere: Unity Catalog offers a single place to administer data access policies that apply across all workspaces and personas.</li><li>Standards-compliant security model: Unity Catalog’s security model is based on standard ANSI SQL and allows administrators to grant permissions in their existing data lake using familiar syntax, at the level of catalogs, databases (also called schemas), tables, and views.</li><li>Built-in auditing and lineage: Unity Catalog automatically captures user-level audit logs that record access to your data. Unity Catalog also captures <a href="https://docs.databricks.com/data-governance/unity-catalog/data-lineage.html">lineage</a> data that tracks how data assets are created and used across all languages and personas.</li><li>Data discovery: Unity Catalog lets you tag and document data assets, and provides a search interface to help data consumers find data.</li><li>System tables (Public Preview): Unity Catalog lets you easily access and query your account’s operational data, including audit logs, billable usage, and lineage.</li></ul><blockquote><em>The most valuable aspect of the Unity Catalog, in my opinion, is that governance is baked into the development process, that is, governance starts on day one. You start with creating one or more central catalogs for your data assets, and proceed to creating tables and other data objects. Descriptions of data objects are captured as they are created. Data lineage is generated in real time. What this means is there is no need for an external tool or service, expensive scans, or other forms of data collection.</em></blockquote><blockquote><em>All this information is transparent and available at your fingertips in the Catalog Explorer UI as you go about your daily tasks within the Databricks workspace.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6ssXg8RbZhUKEFGP" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YLYz-eMxmYOTCNh6" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XbcD7G1RtsZWo6pU" /></figure><p><em>Databricks Catalog Explorer provides a UI to explore and manage data, schemas (databases), tables, models, and permissions.</em></p><p>Unity Catalog also works with any existing data catalogs, data storage systems and governance solutions so you can leverage your existing investments and build a future-proof governance model.</p><h3>Meeting data governance objectives in Databricks</h3><p><strong>Data Quality</strong>: <a href="https://docs.databricks.com/delta-live-tables/index.html">Delta Live Tables</a> provides declarative quality constraints, or <em>expectations</em>, which can be used by data engineers and advanced SQL users to specify data quality rules even as pipelines are being developed. This applies to both batch and streaming pipelines. What is more, the pipelines provide full visibility which lends to pre-built quality dashboards and data observability.</p><p><strong>Data Security</strong>: Unity Catalog security governs both structured and unstructured data, such as files and blobs, via a single interface and common declarations. Unity Catalog supports the SQL keywords SHOW, GRANT, and REVOKE for managing privileges on catalogs, schemas, tables, views, and functions. Initially, users have no access to data in a metastore. Access can be granted by either a metastore admin, the owner of an object, or the owner of the catalog or schema that contains the object.</p><p>The <a href="https://docs.databricks.com/security/index.html">security and compliance guide</a> contains an overview of all security features and capabilities.</p><p><strong>Data Integrity</strong>: This is primarily achieved through the use of <a href="https://docs.databricks.com/introduction/delta-comparison.html#">Delta Lake</a>, a powerful storage layer that brings ACID transactions, data versioning, and rollback capabilities to the lakehouse. It allows you to handle both batch and streaming data in a unified way. Delta Lake provides data reliability via transaction control, thereby solving common challenges with concurrency, such as incomplete updates and phantom rows.</p><p>The lakehouse provides a single source of truth for both your AI and analytics applications.</p><p><strong>Data Accessibility</strong>: The Catalog Explorer provides a UI to explore and manage data, schemas (databases), tables, models, and permissions.</p><p>Databricks has built-in analysis and visualization tools for <a href="https://docs.databricks.com/exploratory-data-analysis/index.html">exploratory data analysis</a>.</p><p>Additional features include data source connectors, <a href="https://docs.databricks.com/data-sharing/index.html">Delta Sharing</a>, and integration with external tools. Complementary tools such as the Feature Store facilitate discovery and reuse of prepared data sets for ML. Databricks provides a hosted version of the MLflow Model Registry in Unity Catalog.</p><p><strong>Data Compliance</strong>: Databricks also provides controls that help meet security requirements for many compliance standards, such as HIPAA and PCI. Please see <a href="https://www.databricks.com/trust/compliance">Security and Trust Center</a> for a full list of certifications and standards by cloud. Databricks provides auditing features to enable admins to monitor user activities to detect security anomalies.</p><p>For additional information and best practices, please see the Databricks <a href="https://docs.databricks.com/data-governance/index.html#">data governance guide</a>.</p><h3>In conclusion</h3><p>For beginner projects that have not yet identified an enterprise data governance tool, and for projects that are set to put all their governance principles and policies into action, please use Unity Catalog for all these great reasons!! Happy Data Warehousing and Machine Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e13515209c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>