<?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 Sreemala Singha on Medium]]></title>
        <description><![CDATA[Stories by Sreemala Singha on Medium]]></description>
        <link>https://medium.com/@sreemala85?source=rss-9f661986e2ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mORimE8h9527ktKbT2oRhw.jpeg</url>
            <title>Stories by Sreemala Singha on Medium</title>
            <link>https://medium.com/@sreemala85?source=rss-9f661986e2ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:56:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sreemala85/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[An In-Depth Guide to Stored Procedures in SQL]]></title>
            <link>https://medium.com/@sreemala85/an-in-depth-guide-to-stored-procedures-in-sql-cc670552b3f8?source=rss-9f661986e2ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc670552b3f8</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[microsoft-sql-server]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Sreemala Singha]]></dc:creator>
            <pubDate>Wed, 11 Dec 2024 16:12:11 GMT</pubDate>
            <atom:updated>2024-12-11T16:12:11.123Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern database management, stored procedures play a crucial role in simplifying and optimizing database operations. Whether you’re automating repetitive tasks, enforcing business logic, or enhancing database security, stored procedures provide a robust solution. This article delves into what stored procedures are, their benefits, use cases, and best practices.</p><h3>What is a Stored Procedure?</h3><p>A <strong>stored procedure</strong> is a precompiled collection of one or more SQL statements stored in the database. It is designed to perform specific tasks and can be executed repeatedly. Stored procedures accept input parameters, return output parameters, or both, making them versatile tools for managing database operations.</p><h3>Key Features of Stored Procedures</h3><ol><li><strong>Precompiled Execution — </strong>Stored procedures are precompiled, meaning the database engine caches their execution plan, reducing the time required for subsequent calls.</li><li><strong>Parameterization — </strong>They can accept parameters, allowing dynamic execution based on the provided inputs.</li><li><strong>Encapsulation — </strong>Complex business logic is centralized and encapsulated, making the application code simpler and easier to maintain.</li><li><strong>Security — </strong>Permissions can be granted on the procedure, restricting direct access to underlying tables.</li><li><strong>Modularity — </strong>Stored procedures enable modular programming by dividing complex logic into reusable components.</li></ol><h3>Advantages of Stored Procedures</h3><p><strong>i. Improved Performance — </strong>Precompiled and cached execution plans reduce query processing time.</p><p><strong>ii. Reusability — </strong>The same procedure can be reused in multiple places, ensuring consistency and reducing code redundancy.</p><p><strong>iii. Enhanced Security — </strong>Users can execute procedures without needing direct access to the data, minimizing security risks.</p><p><strong>iv. Simplified Maintenance — </strong>Centralized logic in stored procedures makes updates and debugging easier.</p><p><strong>v. Transaction Management — </strong>Stored procedures can manage transactions to ensure data consistency and atomicity.</p><h3>Use Cases of Stored Procedures</h3><h4>1. Data Manipulation</h4><p>Stored procedures simplify <strong>Create, Read, Update, Delete (CRUD)</strong> operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*EYjhIdIge-Q6YvKLgG0aUQ.png" /></figure><h4>2. Enforcing Business Logic</h4><p>Encapsulate complex business rules in a stored procedure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*0Jdv4h-Jp-wO3zfydEUsKA.png" /></figure><h4>3. Dynamic SQL Execution</h4><p>Stored procedures allow the execution of dynamic SQL queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*X3KxrTn3eqWDpfQlzTjUug.png" /></figure><h4>4. Reporting</h4><p>Generate detailed reports by aggregating data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*LU73ip-lPdB0oggL9HZMcw.png" /></figure><h4>5. Auditing and Logging</h4><p>Track changes to sensitive data with audit logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*AcreCALV8NQHBpuiNDD-hQ.png" /></figure><h3>Types of Stored Procedures</h3><p><strong>i. System Stored Procedures — </strong>Built-in procedures provided by the database (e.g. <em>sp_help</em>, <em>sp_executesql</em>).</p><p><strong>ii. User-Defined Stored Procedures — </strong>Custom procedures created by users for specific tasks.</p><p><strong>iii. Extended Stored Procedures — </strong>Used to call external programs or code (deprecated in modern systems).</p><p><strong>iv. Temporary Stored Procedures — </strong>Created temporarily and scoped to a session (prefixed with # or ##).</p><h3>Best Practices for Stored Procedures</h3><p><strong>i. Error Handling — </strong>Use <em>TRY...CATCH</em> blocks for robust error handling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*Ii81SGC9yui-ov7VMaktkw.png" /></figure><p><strong>ii. Avoid Hardcoding — </strong>Use parameters for dynamic inputs instead of hardcoding values.</p><p><strong>iii. Optimize for Performance — </strong>Use indexes and avoid unnecessary joins to improve query performance.</p><p><strong>iv. Limit Permissions — </strong>Grant execute permissions on stored procedures instead of direct table access.</p><p><strong>v. Document the Logic — </strong>Include comments explaining the purpose and logic of the procedure for maintainability.</p><p><strong>vi. Test Thoroughly — </strong>Validate stored procedures with various input scenarios to ensure correctness.</p><h3>Example: Comprehensive Stored Procedure</h3><h4>Scenario:</h4><p>Create a stored procedure to:</p><ol><li>Insert new employee records.</li><li>Update salaries for existing employees.</li><li>Fetch employee details based on a salary range.</li></ol><h4>Implementation:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*dX9daGouUPBs8ZeBg5EVTQ.png" /></figure><h4>Execution:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*7ePn0AO-J1hPGstjbGjl2g.png" /></figure><h3>To sum up…</h3><p>Stored procedures are indispensable for managing complex database operations efficiently. They improve performance, ensure security, and simplify maintenance while enabling developers to focus on business logic rather than repetitive coding tasks. By following best practices and leveraging their full potential, stored procedures can significantly enhance database management and application development.</p><p><strong><em>Follow me on LinkedIn</em></strong> — <a href="http://linkedin.com/in/sreemala-singha">linkedin.com/in/sreemala-singha</a></p><p><strong><em>Follow me on Medium</em></strong> — <a href="https://medium.com/@sreemala85">https://medium.com/@sreemala85</a></p><p><strong>If you found value in this article, I’d love to hear your thoughts! Please share your feedback by leaving a comment or giving it a ‘clap’ on Medium.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc670552b3f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Impact of Dropping a Table with Dependent Views]]></title>
            <link>https://medium.com/@sreemala85/understanding-the-impact-of-dropping-a-table-with-dependent-views-061fd228b691?source=rss-9f661986e2ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/061fd228b691</guid>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[microsoft-sql-server]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Sreemala Singha]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 05:55:56 GMT</pubDate>
            <atom:updated>2024-12-10T05:55:56.364Z</atom:updated>
            <content:encoded><![CDATA[<p>In relational databases, views (both <strong>regular</strong> and <strong>materialized</strong>) often depend on underlying tables for their data. Dropping a table without considering these dependencies can lead to errors or unintended consequences. This article explores the behavior of regular and materialized views when a dependent table is dropped, along with best practices for managing these scenarios.</p><h3>What Happens When You Drop a Table?</h3><p>When a table is dropped, its schema and data are removed permanently from the database. However, if views — either regular or materialized — depend on this table, the database’s behavior depends on the type of view and the database system in use.</p><h3>1. Regular Views</h3><p>A <strong>regular view</strong> is a virtual table based on a SQL query. Since regular views do not store data physically and fetch data dynamically from base tables, they are directly tied to the existence of the underlying tables.</p><h4>Behavior Across Databases</h4><p><strong>Oracle, PostgreSQL, SQL Server, MySQL — </strong>Dropping a base table invalidates the dependent regular views. Queries against the invalidated view will fail, typically with an error indicating that the base table does not exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*W77oLmul7SImF7jR4jbO2g.png" /><figcaption><strong>Example of Error Message</strong></figcaption></figure><p>When we drop a table directly, the view is not dropped automatically; it remains in the database but becomes <strong>invalid</strong>. To avoid these issues, you should manually drop or modify the view before dropping the base table. We can query the system catalog to identify dependent views before dropping the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*bTmItsu_aKIRMg9lTl6U8Q.png" /></figure><h3>2. Materialized Views</h3><p>A <strong>materialized view</strong> is a physical table that stores the results of a SQL query. Materialized views depend on their base tables to stay consistent during refresh operations.</p><h4>Behavior Across Databases</h4><p><strong>Oracle, PostgreSQL, SQL Server — </strong>Dropping a base table without addressing the materialized view raises an error. You must explicitly drop the materialized view first, then drop the base table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*zK_mTODNOWUnVQ5vRj4yZQ.png" /><figcaption>Error Message in Oracle Database</figcaption></figure><p><strong>Cascading Drop</strong> — Some databases allow cascading behavior where dependent objects (like materialized views) are dropped automatically along with the base table. Use this option cautiously, as it removes all dependent objects without explicit confirmation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*9MYljWQi9xAFM3Ht1brZLg.png" /></figure><h3>Example Scenarios</h3><h4>Scenario 1: Dropping a Table with a Regular View</h4><p>Suppose you have a <em>regular_view</em> built on top of a <em>base_table</em>:</p><p><em>CREATE VIEW regular_view AS<br>SELECT emp_id, emp_name<br>FROM base_table;</em></p><p>If you drop <em>base_table (</em>DROP TABLE base_table),</p><p>➡️The <em>regular_view</em> remains in the database but becomes invalid.</p><p>➡️A query like SELECT * FROM <em>regular_view </em>will result in an error.</p><h4>Scenario 2: Dropping a Table with a Materialized View</h4><p>Suppose you have a <em>materialized_view</em> that precomputes data from <em>base_table</em>:</p><p><em>CREATE MATERIALIZED VIEW materialized_view AS<br>SELECT emp_id, SUM(salary) AS total_salary<br>FROM base_table<br>GROUP BY emp_id;</em></p><p>If you attempt to drop <em>base_table (</em>DROP TABLE base_table),</p><p>➡️The database raises an error, preventing the table from being dropped until the materialized view is removed. We need to drop the materialized view first followed by the <em>base_table -</em></p><p><em>DROP MATERIALIZED VIEW materialized_view;<br>DROP TABLE base_table;</em></p><h3>Best Practices for Managing Dependencies</h3><ol><li><strong>Identify Dependencies</strong>: Use system catalog views to check for objects dependent on the table.</li><li><strong>Drop Views Safely</strong>: Drop or modify dependent views explicitly before dropping a table.</li><li><strong>Use Cascading Carefully</strong>: Cascading options can remove dependencies but should be used with caution.</li><li><strong>Document Schema Dependencies</strong>: Maintain proper documentation of view dependencies for easier maintenance and troubleshooting.</li></ol><p><strong><em>Follow me on LinkedIn</em></strong> — <a href="http://linkedin.com/in/sreemala-singha">linkedin.com/in/sreemala-singha</a></p><p><strong><em>Follow me on Medium</em></strong> — <a href="https://medium.com/@sreemala85">https://medium.com/@sreemala85</a></p><p><strong>If you found value in this article, I’d love to hear your thoughts! Please share your feedback by leaving a comment or giving it a ‘clap’ on Medium.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=061fd228b691" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Recursive CTE Restrictions: A Guide with Examples]]></title>
            <link>https://medium.com/@sreemala85/understanding-recursive-cte-restrictions-a-guide-with-examples-410872e0c81b?source=rss-9f661986e2ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/410872e0c81b</guid>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[microsoft-sql-server]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Sreemala Singha]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 11:29:46 GMT</pubDate>
            <atom:updated>2024-12-07T11:29:46.652Z</atom:updated>
            <content:encoded><![CDATA[<p>Recursive Common Table Expressions (CTEs) are a powerful SQL feature used to handle hierarchical or recursive data structures, such as organizational hierarchies, file directories, or network connections. However, while incredibly useful, recursive CTEs come with specific restrictions that must be understood and adhered to for effective usage.</p><h4>1. Anchor Member and Recursive Member Rules</h4><p>A recursive CTE has two parts:</p><ul><li><strong>Anchor Member</strong>: The base query that defines the starting point of the recursion.</li><li><strong>Recursive Member</strong>: The query that repeatedly references the CTE to build the recursion.</li></ul><p>The anchor member must be a simple, non-recursive SELECT query. The recursive member must reference the CTE in its FROM clause. For example:</p><p>We have the below <strong>Employees</strong> table -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*YYWP3YexBEvKGnzmlX7Nbw.png" /><figcaption>Employees table</figcaption></figure><p>We want to show the hierarchy starting from the employee at the lowest level to the employee at the highest level —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*A_OfUsaOSKPpDzBPpINT8A.png" /><figcaption><strong>Output table</strong></figcaption></figure><p>This can be be achieved with the below SQL query —</p><p>WITH r_cte AS (<br> SELECT employee_id, employee_name, manager_id, CAST(employee_name AS VARCHAR(MAX)) AS hierarchy<br> FROM Employees<br> WHERE manager_id IS NULL<br> <br> UNION ALL<br> <br> SELECT e.employee_id, e.employee_name, e.manager_id, r.hierarchy + ‘-&gt;’ + e.employee_name<br> FROM Employees e<br> INNER JOIN r_cte r ON e.manager_id = r.employee_id<br>)<br>SELECT * FROM r_cte;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*iejjNjUWK3JxnYkt7qM2LA.png" /></figure><p>The <strong>anchor</strong> provides the starting rows (top-level employees with no managers), while the <strong>recursive member</strong> builds the hierarchy by finding employees who report to those already included.</p><h4>2. Column Requirements</h4><p>The number, order, and data types of columns in the anchor member and recursive member must match exactly. This ensures consistency as rows are added recursively.</p><p><strong>Incorrect Example</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*06Dx3BBQUGHHUWRkRJwAuQ.png" /></figure><p>This query fails because the number of columns does not match.</p><p><strong>Correct Example</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnq6T3eL8o1Msfict4nTsA.png" /></figure><h4>3. No Outer Joins in Recursive Member</h4><p>Recursive members cannot include outer joins ( LEFT JOIN, RIGHT JOIN or FULL OUTER JOIN ) because they can introduce ambiguity and potentially lead to infinite recursion.</p><p>An outer join introduces rows with <strong>NULL</strong> values when there’s no match between the tables. In a recursive CTE, this can lead to unexpected behavior or because rows with NULL in the recursive chain might not terminate properly. To prevent such issues, SQL disallows the use of outer joins in the recursive part of the CTE. Only INNER JOIN is allowed.</p><p><strong>Incorrect Example</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*67he9ff5Ga3tg2xhg7djiQ.png" /></figure><p><strong>Correct Example</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*3cA-WWozAPAtHMc7EZtvZg.png" /></figure><h4>4. No Aggregates or DISTINCT in Recursive Member</h4><p>You cannot use DISTINCT, GROUP BY or aggregate functions like SUM or COUNT in the recursive part of the CTE. However, you can apply them after the recursion completes.</p><p><strong>Incorrect Example</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*GkLEu5t6oU4NphUoemU7nQ.png" /></figure><p><strong>Correct Example</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*8fUPvi4qJ9ifqUrpwYK_Uw.png" /></figure><h4>5. Must Avoid Infinite Loops</h4><p>Recursive CTEs require a termination condition to prevent infinite recursion. Without a clear condition, the query may result in an error or exceed the database’s recursion limit.</p><p><strong>Incorrect Example</strong> (No termination condition):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*4xtffDtZ3ERmJ2oN-4yn2g.png" /></figure><p><strong>Correct Example</strong> (Using a termination condition):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*7KDoLV0zk6e4PMLBFqWfRQ.png" /></figure><h4>6. Maximum Recursion Depth</h4><p>Most SQL systems impose a maximum recursion limit:</p><ul><li><strong>SQL Server</strong>: Default is 100 levels. This can be changed using OPTION (MAXRECURSION N) .</li><li><strong>PostgreSQL</strong>: Stops when no new rows are produced, with no fixed recursion depth.</li><li><strong>MySQL</strong>: Requires the WITH RECURSIVE clause to explicitly enable recursion.</li></ul><p>To handle deep hierarchies, consider adjusting the maximum depth in SQL Server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*ggkqb4sX_5QkhIHHyW5MkQ.png" /></figure><h3>Conclusion</h3><p>Recursive CTEs are a versatile tool for navigating hierarchical data, but they come with specific rules and restrictions:</p><ol><li>Ensure matching columns in the anchor and recursive members.</li><li>Avoid using outer joins, aggregates, or DISTINCT in recursive members.</li><li>Include a clear termination condition to prevent infinite recursion.</li><li>Be mindful of maximum recursion depth limits.</li></ol><p>By adhering to these restrictions and best practices, you can write efficient and error-free recursive queries. Happy querying!</p><p><strong><em>Follow me on LinkedIn</em></strong> — <a href="http://linkedin.com/in/sreemala-singha">linkedin.com/in/sreemala-singha</a></p><p><strong><em>Follow me on Medium</em></strong> — <a href="https://medium.com/@sreemala85">https://medium.com/@sreemala85</a></p><p><strong>If you found value in this article, I’d love to hear your thoughts! Please share your feedback by leaving a comment or giving it a ‘clap’ on Medium.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=410872e0c81b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Valid Dates in the Date Dimension]]></title>
            <link>https://medium.com/@sreemala85/detecting-valid-dates-in-the-date-dimension-b2db92c7ed0b?source=rss-9f661986e2ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2db92c7ed0b</guid>
            <category><![CDATA[dax]]></category>
            <category><![CDATA[power-bi-tutorials]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[business-analytics]]></category>
            <dc:creator><![CDATA[Sreemala Singha]]></dc:creator>
            <pubDate>Fri, 15 Nov 2024 15:32:36 GMT</pubDate>
            <atom:updated>2024-12-07T11:28:31.333Z</atom:updated>
            <content:encoded><![CDATA[<p>When dealing with time intelligence in Power BI, ensuring that only valid dates are considered in calculations is crucial for accurate reporting and analysis. This becomes particularly important in scenarios involving periodic calculations such as Month-to-Date (MTD), Year-to-Date (YTD) and similar metrics. Here’s a detailed look at how to handle this effectively.</p><p><strong>Challenges with Time Intelligence</strong></p><p>One of the common challenges with time intelligence is that not all dates in the date dimension may have corresponding data in the fact table. This can result in null values or incorrect calculations, especially when future dates are included in the date dimension.</p><p><strong>Example Scenario</strong></p><p>Consider a business that requires the following calculations:<br>- Sales Month to Date (MTD)<br>- Sales Year to Date (YTD)</p><p>Using DAX, these calculations are straightforward. For instance, the MTD calculation can be written as:</p><p>Total Sales MTD = <br>TOTALMTD(<br> [Total Sales],<br> ‘Date’[Full Date])</p><p><strong><em>Note </em></strong>— Total Sales is a measure which aggregates all the sales values for every transaction in the fact table.</p><p><em>Total Sales = Sum(FactTable[Sales Value]</em></p><p>Similarly, for YTD:</p><p>Total Sales YTD = <br>TOTALYTD(<br> [Total Sales],<br> DATEADD(‘Date’[Full Date], -1, MONTH))</p><p>However, issues arise when these calculations are plotted on a visual that includes dates for which there is no corresponding sales data. Sorting the `Full Date` column in descending order often reveals null values for measures such as `Total Sales MTD` for future dates, and duplicate values for `Total Sales YTD`.</p><p>Solutions to Detecting Valid Dates</p><p><strong><em>Method 1: Blanking Invalid Dates</em></strong></p><p>One approach is to modify the measures to return `BLANK()` for dates where no transactions exist. For example:</p><p>Internet Sales MTD Blanking Invalid Dates =<br>VAR lastOrderDate = MAX(‘Internet Sales’[OrderDateKey])<br>RETURN<br>IF(<br> MAX(‘Date’[DateKey]) &lt;= lastOrderDate,<br> TOTALMTD([Internet Sales], ‘Date’[Full Date])<br>)</p><ul><li>This measure checks if the `DateKey` is less than or equal to the last order date. If it is, it performs the MTD calculation; otherwise, it returns `BLANK()`.</li></ul><p><strong><em>Method 2: Creating an IsValidDate Column</em></strong></p><p>A more efficient approach is to create a calculated column in the `Date` table to flag valid dates. This column can be used to filter visuals and ensure only valid dates are considered in calculations. The `IsValidDate` column can be created with the following DAX expression:</p><p>IsValidDate =<br>AND(<br> ‘Date’[DateKey] &gt;= MIN(‘Internet Sales’[OrderDateKey]),<br> ‘Date’[DateKey] &lt;= MAX(‘Internet Sales’[OrderDateKey])<br>)</p><p>You can now use the `IsValidDate` column as a visual filter. This ensures that only valid dates are displayed in the visual, without modifying the DAX expressions of the original measures.</p><p><strong>Benefits of Using IsValidDate</strong></p><p>Using the `IsValidDate` flag not only ensures accuracy in calculations but also improves the user experience by filtering slicer visuals to show only valid dates. This avoids confusion and enhances the clarity of reports.</p><p>In summary, detecting and handling valid dates in the date dimension is essential for accurate time intelligence calculations in Power BI. By creating an `IsValidDate` column and using it effectively, you can ensure your reports are both accurate and user-friendly.</p><p><strong><em>Follow me on LinkedIn</em></strong> — <a href="http://linkedin.com/in/sreemala-singha">linkedin.com/in/sreemala-singha</a></p><p><strong><em>Follow me on Medium</em></strong> — <a href="https://medium.com/@sreemala85">https://medium.com/@sreemala85</a></p><p><strong>If you found value in this article, I’d love to hear your thoughts! Please share your feedback by leaving a comment or giving it a ‘clap’ on Medium.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2db92c7ed0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Power BI Desktop Projects: A New Way to Build and Save Reports]]></title>
            <link>https://medium.com/@sreemala85/power-bi-desktop-projects-a-new-way-to-build-and-save-reports-6f52b51fe8e5?source=rss-9f661986e2ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f52b51fe8e5</guid>
            <category><![CDATA[microsoft-power-bi]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <dc:creator><![CDATA[Sreemala Singha]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 14:02:09 GMT</pubDate>
            <atom:updated>2024-11-14T14:02:09.801Z</atom:updated>
            <content:encoded><![CDATA[<p>Power BI Desktop Projects make it easier to work on reports and data models. When you save your work as a <strong>Power BI Project (PBIP)</strong> file, all the different parts of your report are saved as separate, simple text files inside folders. This makes it easier to understand, edit, and share your work with others.</p><p>Here’s how Power BI Projects work and why they’re useful!</p><h3>Why Use Power BI Projects?</h3><p><strong>✅Edit with a Simple Text Editor</strong> When you save your project as a PBIP file, each part of your report — like data tables, calculations, and charts — is saved as a <strong>JSON file</strong>. JSON files are plain text, so you can read and edit them easily. You could use a basic text editor like Notepad, but a tool like <strong>Visual Studio Code (VS Code)</strong> works best. VS Code makes editing easier by showing suggestions and errors and by working with <strong>Git</strong> (more on this below).</p><p><strong>Example</strong>: Say you have a file describing a chart in your report. Opening it in VS Code might suggest properties you can add, like colors or labels. It’s like a “hint” tool as you make edits!</p><p><strong>✅ Make Changes Automatically with Scripts</strong><br>Because PBIP files are simple text, you can use scripts to update parts of your project automatically. <strong>Tabular Model Scripting Language (TMSL)</strong> is a scripting tool that can automate changes, so you don’t have to update each part by hand.</p><p><strong>Example</strong>: Imagine you’re creating several charts that all need the title “Monthly Sales.” Instead of changing each one by hand, you can use a TMSL script to update them all at once.</p><p><strong>✅ Track Changes and Collaborate with Source Control</strong><br>Power BI Projects work with <strong>Git</strong>, a tool that saves each change you make, so you have a full history of edits. Git lets you easily go back to old versions, compare changes, or even combine work with others.</p><p><strong>Example</strong>: Think of it like saving drafts of an essay in Google Docs. You can go back to see what you wrote earlier or see changes your friends suggested. In Git, each change is called a “commit,” which keeps everything organized.</p><p><strong>✅ Automated Quality Checks with CI/CD</strong><br>With Git, you can also use <strong>Continuous Integration and Continuous Delivery (CI/CD)</strong>. CI/CD is a system that automatically checks your work, testing changes to make sure they don’t break anything. It’s like a helpful robot that double-checks everything before it’s published.</p><h3>How to Enable Power BI Project Mode</h3><p>Power BI Project mode is currently a preview feature, which means you need to turn it on manually. Here’s how:</p><ol><li>Open <strong>Power BI Desktop</strong>.</li><li>Go to <strong>File &gt; Options and Settings &gt; Options &gt; Preview Features</strong>.</li><li>Check the box next to <strong>Power BI Project (.pbip)</strong>.</li></ol><p>Once it’s enabled, you’re ready to save your work as a project.</p><h3>Saving as a Power BI Project</h3><p>If you’re working on a new or existing Power BI file, you can save it as a PBIP project file. This way, Power BI saves your data model and report as folders with separate files for each part.</p><p>When you save a project, the Power BI Desktop title bar will show that you’re in “project mode.” You can click on the title to open a menu that helps you find the project files or the folder where they’re saved.</p><h3>Project Folder Structure</h3><ul><li><strong>&lt;project name&gt;.SemanticModel</strong>: A folder with files for your data model, which is like the backbone of your report.</li><li><strong>&lt;project name&gt;.Report</strong>: A folder for files that store your report layout, visuals, and settings.</li><li><strong>.gitignore</strong>: A file that tells Git which files to ignore when tracking changes. For example, you might not want to track temporary files like <em>cache.abf</em> or<em> localSettings.json</em>.</li></ul><p><strong>Example</strong>: If your project is called “SalesAnalysis,” you’ll have folders named <strong><em>SalesAnalysis.SemanticModel</em></strong> and <strong><em>SalesAnalysis.Report</em> </strong>.</p><h3>Opening a Power BI Project</h3><p>To open a Power BI Project, double-click the PBIP file, or open the <em>.pbir</em> file in the report folder. This will open the report and data model just as you left them.</p><p><strong>Tip</strong>: You don’t need a separate PBIP file for every report if they use the same data model. You can keep multiple reports in the same folder and open each one from its <em>.pbir</em> file.</p><h3>Understanding the Semantic Model and Report Folders</h3><ol><li><strong>Project Semantic Model Folder</strong><br>This folder contains files for your data model. The data model is like a map of the relationships between different data tables in your report.</li></ol><p><strong>Example</strong>: If you’re creating a report about animals, the semantic model might have tables like “Animals,” “Habitats,” and “Regions,” with relationships connecting these tables.</p><p><strong>Project Report Folder</strong><br>This folder has files for things specific to your report, like visuals, settings, and filters.</p><p><strong>Example</strong>: If you have a bar chart showing the number of lions in each habitat, the report folder will contain the setup for that chart. You could create another report with a pie chart for the same data, and it would be saved as a separate file.</p><h3>In Summary</h3><p>Power BI Desktop Projects (PBIP) are a new and organized way to save and manage your Power BI work. This feature helps you keep track of changes, collaborate with others, and even automate parts of your work. Whether you’re new to Power BI or an advanced user, PBIP makes it easier to manage and share your data projects.</p><p><strong><em>Follow me on LinkedIn</em></strong> — <a href="http://linkedin.com/in/sreemala-singha">linkedin.com/in/sreemala-singha</a></p><p><strong><em>Follow me on Medium</em></strong> — <a href="https://medium.com/@sreemala85">https://medium.com/@sreemala85</a></p><p><strong>If you found value in this article, I’d love to hear your thoughts! Please share your feedback by leaving a comment or giving it a ‘clap’ on Medium.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f52b51fe8e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating Data from TIBCO WebFOCUS to Power BI: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@sreemala85/migrating-data-from-tibco-webfocus-to-power-bi-a-step-by-step-guide-9a017b7a3b3c?source=rss-9f661986e2ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a017b7a3b3c</guid>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[microsoft-power-bi]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[data-migration]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Sreemala Singha]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 09:52:40 GMT</pubDate>
            <atom:updated>2024-11-13T09:52:40.335Z</atom:updated>
            <content:encoded><![CDATA[<p>As organizations evolve, so do their analytics and reporting needs. Many enterprises are now migrating from legacy business intelligence tools like TIBCO WebFOCUS to modern, self-service platforms like Microsoft Power BI. With Power BI’s powerful visualizations, user-friendly interface, and seamless integration with the Microsoft ecosystem, it’s become a preferred choice for data-driven organizations.</p><p>If you’re planning to migrate 1000+ files or reports from WebFOCUS to Power BI, a structured approach is essential. This article outlines the steps to make your migration smooth and successful.</p><p><strong>Overview: WebFOCUS and Power BI</strong></p><p>TIBCO WebFOCUS is a mature enterprise BI and reporting platform known for its strength in operational and large-scale reporting. It excels in centralized, production-level reporting in complex environments but is less flexible for interactive and self-service analytics.</p><p>Microsoft Power BI, on the other hand, focuses on enabling business users and analysts to create interactive dashboards and explore data visually. It’s highly suitable for ad-hoc reporting, data exploration, and collaboration across teams. Transitioning to Power BI from WebFOCUS opens up new possibilities in data accessibility and analytics.</p><p><strong>Migration Approach</strong></p><p>Since WebFOCUS doesn’t directly integrate with Power BI, migrating data and reports requires connecting Power BI to the underlying data sources used by WebFOCUS or exporting data from WebFOCUS reports. Below are the steps for a successful migration from WebFOCUS to Power BI.</p><p><strong><em>### Step 1: Identify and Analyze WebFOCUS Data Sources</em></strong></p><p>1. Determine Source Data: WebFOCUS pulls data from various sources, such as databases (SQL Server, Oracle, DB2), flat files, or its own data repositories. Identify the primary data sources and schemas that WebFOCUS is using.<br>2. Identify Relevant Reports: Review the reports you plan to migrate. Decide which ones contain essential data and whether any need to be redesigned for Power BI.<br>3. Access the Data Model: Work with your WebFOCUS administrators to understand how data is structured, including tables, views, or joins used in each report. This understanding is crucial to recreate or enhance data models in Power BI.</p><p><strong><em>### Step 2: Access WebFOCUS Data</em></strong></p><p>To connect Power BI to WebFOCUS data, you have several options:</p><p><strong>✅ Option 1: Direct Database Connection</strong></p><p>If WebFOCUS is using a database (e.g., SQL Server, Oracle) to retrieve data, you can connect Power BI directly to that database:<br> — Use Power BI Connectors: Power BI supports direct connections to major databases, allowing you to import or query data in real-time.<br> — Write SQL Queries: Recreate any data transformations from WebFOCUS using SQL queries or Power Query transformations in Power BI.<br> — Benefits: Bypassing WebFOCUS reduces complexities, as you’re working with raw data directly in Power BI.</p><p>This method is efficient and avoids dependency on WebFOCUS. However, you may need to recreate complex calculations from WebFOCUS reports in Power BI.</p><p><strong>✅ Option 2: Export Data from WebFOCUS as Flat Files (CSV, Excel)</strong></p><p>If direct database access is not possible, exporting data from WebFOCUS to flat files is another option:<br> — Export as CSV/Excel: Use WebFOCUS’s export functions to save data as CSV or Excel files.<br> — Import into Power BI: Power BI can read data from CSV, Excel, and JSON files. Use the “Get Data” feature to load these files into Power BI.<br> — Automate Exports: Set up WebFOCUS jobs to export data regularly, and configure Power BI to refresh from these files.</p><p>This approach is suitable if you need scheduled data refreshes and cannot access the database directly.</p><p><strong>✅ Option 3: Use REST API to Extract Data</strong></p><p>WebFOCUS offers a REST API for programmatically retrieving data:<br> — API Calls: Create API requests to extract data in JSON format. The WebFOCUS API supports various operations, including fetching report data.<br> — Connect Power BI to API: Use Power BI’s “Web” connector to import JSON data. You may need to configure authentication and parse JSON in Power Query.<br> — Schedule Refresh: Power BI can refresh data automatically via the API, ensuring the latest data without manual exports.</p><p>This method is flexible but may require technical expertise to handle authentication and API configurations.</p><p><strong>✅ Option 4: Use ODBC/JDBC for Data Access</strong></p><p>Some WebFOCUS environments allow access via ODBC/JDBC, which Power BI can leverage:<br> — Install Drivers: Install the required ODBC or JDBC drivers on the Power BI server/machine.<br> — Power BI ODBC Connection: Use Power BI’s ODBC connection to pull data from WebFOCUS’s data sources.<br> — Technical Setup: This method may need support from IT to set up ODBC/JDBC connections and troubleshoot any performance issues.</p><p>ODBC/JDBC offers a more seamless connection, but it’s typically complex to set up.</p><p><strong><em>### Step 3: Transform and Clean Data in Power BI</em></strong></p><p>Once the data is accessible in Power BI, you’ll need to ensure it’s ready for analysis:<br> — Data Cleaning: Remove redundant columns, handle missing data, and standardize formats.<br> — Transformation: Recreate any transformations done in WebFOCUS reports. Use Power Query for data shaping and DAX (Data Analysis Expressions) for calculated columns and measures.<br> — Build Data Model: Define relationships between tables and optimize the data model for reporting and performance.</p><p>Power BI provides robust data modeling tools that allow you to create relationships, calculated measures, and hierarchies that make data analysis more effective.</p><p><strong><em>### Step 4: Build and Visualize in Power BI</em></strong></p><p>With data loaded and cleaned, you can start building Power BI reports:<br> — Create Reports and Dashboards: Recreate WebFOCUS reports or improve upon them with Power BI’s interactive visualizations.<br> — Set Up Refresh Schedules: Configure data refresh schedules in Power BI to ensure data is up-to-date. Align this schedule with WebFOCUS data exports or API updates.</p><p>Power BI’s visual capabilities allow you to design dynamic, drillable reports that are more interactive and user-friendly than static WebFOCUS reports.</p><p><strong><em>### Step 5: Validate and Test</em></strong></p><p>To ensure the migration is successful, perform the following checks:<br> — Data Validation: Cross-verify data in Power BI reports with WebFOCUS reports to ensure accuracy and consistency.<br> — Performance Testing: If working with large datasets, optimize Power BI’s data model and visualizations to ensure responsive performance. Consider techniques like aggregations, DAX optimization, and using import mode for large datasets.</p><p>Testing and validation are critical to ensure stakeholders are confident in the new Power BI reports.</p><p><strong>### Summary</strong></p><p>Migrating from WebFOCUS to Power BI can unlock a range of benefits, from interactive dashboards to self-service analytics. Here’s a recap of the migration steps:</p><p>1. <em>Identify Source Data</em>: Understand the data sources and reports in WebFOCUS.<br>2. <em>Choose a Connection Method</em>: Direct database connection, flat file exports, REST API, or ODBC/JDBC.<br>3. <em>Transform and Model Data</em>: Replicate transformations in Power BI and build the data model.<br>4. <em>Build Reports</em>: Create Power BI dashboards and set up data refresh schedules.<br>5. <em>Validate and Test</em>: Verify accuracy and optimize performance.</p><p>By following these steps, you can ensure a smooth transition to Power BI, creating a more modern and interactive reporting environment. With Power BI’s advanced features, your organization can empower users to make data-driven decisions, collaborate effectively, and gain deeper insights into business operations.</p><p><strong><em>Follow me on LinkedIn</em></strong> — <a href="http://linkedin.com/in/sreemala-singha">linkedin.com/in/sreemala-singha</a></p><p><strong><em>Follow me on Medium</em></strong> — <a href="https://medium.com/@sreemala85">https://medium.com/@sreemala85</a></p><p><strong>If you found value in this article, I’d love to hear your thoughts! Please share your feedback by leaving a comment or giving it a ‘clap’ on Medium.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a017b7a3b3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to optimize SQL queries]]></title>
            <link>https://medium.com/@sreemala85/how-to-optimize-sql-queries-8db8e28fbbf7?source=rss-9f661986e2ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/8db8e28fbbf7</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[microsoft-sql-server]]></category>
            <dc:creator><![CDATA[Sreemala Singha]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 09:32:31 GMT</pubDate>
            <atom:updated>2024-11-13T09:50:54.126Z</atom:updated>
            <content:encoded><![CDATA[<p>Optimizing SQL queries is essential for improving performance, particularly when dealing with large datasets or complex joins. In an interview setting, you might focus on techniques, examples, and the reasoning behind each optimization strategy. Here are key SQL optimization techniques with examples:</p><h4>1. Indexing</h4><p><strong>Purpose</strong>: Indexes help the database locate rows faster, particularly in large tables. An index on frequently queried columns, such as those used in <strong>WHERE</strong>, <strong>JOIN</strong> or <strong>ORDER</strong> <strong>BY</strong> clauses, can significantly speed up query execution.</p><p><strong>Example</strong>: Suppose you have a <em>Customer</em> table with millions of records and often query by <em>customer_id</em>:</p><p><em>SELECT * FROM Customer WHERE customer_id = 12345;</em></p><p>This query can quickly locate customer_id = 12345 without scanning the entire table.</p><p>➡️ Without an index, the database performs a full table scan. By creating an index:</p><p><em>CREATE INDEX idx_customer_id ON Customer(customer_id);</em></p><h4>2. Use SELECT Fields Instead of SELECT*</h4><p><strong>Purpose</strong>: Selecting specific columns instead of SELECT * reduces the amount of data transferred and processed, especially if only a few columns are necessary.</p><p><strong>Example</strong>: Instead of: <em>SELECT * FROM Orders;</em></p><p>Use: <em>SELECT order_id, order_date FROM Orders;</em></p><p>➡️ This approach reduces the amount of memory and processing time needed if only order_id and order_date are required.</p><h4>3. Avoiding Nested Subqueries</h4><p><strong>Purpose</strong>: Subqueries within <strong>WHERE </strong>clauses can sometimes be slower than a <strong>JOIN</strong>, especially if they are correlated (executed for each row).</p><p><strong>Example</strong>: Instead of:</p><p><em>SELECT name FROM Customer WHERE customer_id IN (SELECT customer_id FROM Orders WHERE order_total &gt; 1000);</em></p><p>Try using a <strong>JOIN</strong>:</p><p><em>SELECT c.name<br>FROM Customer c<br>JOIN Orders o ON c.customer_id = o.customer_id<br>WHERE o.order_total &gt; 1000;</em></p><p><strong>➡️ JOIN </strong>typically performs better in this case as it avoids executing the subquery multiple times.</p><h4>4. Avoid Using Functions on Indexed Columns in WHERE Clauses</h4><p><strong>Purpose</strong>: Applying functions to indexed columns prevents the database from utilizing indexes effectively.</p><p><strong>Example</strong>: Instead of:</p><p><em>SELECT * FROM Sales WHERE YEAR(sale_date) = 2023;</em></p><p>Use:</p><p><em>SELECT * FROM Sales WHERE sale_date BETWEEN ‘2023–01–01’ AND ‘2023–12–31’;</em></p><p>➡️ Here, the <strong>BETWEEN</strong> clause allows the database to use an index on <em>sale_date</em>.</p><h4>5. Use Appropriate Data Types</h4><p><strong>Purpose</strong>: Choosing the correct data types ensures efficient storage and can speed up query execution. Larger data types consume more memory and processing time.</p><p><strong>Example</strong>: Use <strong>INT</strong> instead of <strong>BIGINT</strong> if you don’t expect values to exceed the range of an integer. Use CHAR (2) for state codes instead of VARCHAR (50) if you know it will always be 2 characters.</p><h4>6. Consider Partitioning for Large Tables</h4><p><strong>Purpose</strong>: Partitioning breaks large tables into smaller, more manageable segments, which can speed up queries that only need a subset of data.</p><p><strong>Example</strong>: If you often query data based on <em>order_date</em>, consider partitioning the Orders table by year or month of <em>order_date</em>. This allows the database to skip partitions that don’t match the query criteria, reducing the search space.</p><h4>7. Use EXISTS Instead of IN for Subquery Optimization</h4><p><strong>Purpose</strong>: For large datasets, <strong>EXISTS</strong> often performs better than <strong>IN</strong> as it stops evaluating once a match is found.</p><p><strong>Example</strong>: Instead of:</p><p><em>SELECT name FROM Customer WHERE customer_id IN (SELECT customer_id FROM Orders);</em></p><p>Use:</p><p><em>SELECT name FROM Customer c WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.customer_id = c.customer_id);</em></p><h4>8. Limit the Number of Rows with LIMIT or TOP</h4><p><strong>Purpose</strong>: If you only need a subset of data, using <strong>LIMIT</strong> or <strong>TOP</strong> reduces the data volume processed and returned.</p><p><strong>Example</strong>:</p><p><em>SELECT * FROM Sales ORDER BY sale_date DESC LIMIT 10;</em></p><p>➡️ This limits the result to 10 rows, reducing resource usage if only recent records are needed.</p><h4>9. Analyze Query Plans</h4><p><strong>Purpose</strong>: Tools like <strong>EXPLAIN</strong> (in MySQL/PostgreSQL) or <strong>EXPLAIN PLAN</strong> (in Oracle) display how the database executes a query, revealing bottlenecks and whether indexes are used.</p><p><strong>Example</strong>:</p><p><em>EXPLAIN SELECT * FROM Orders WHERE order_total &gt; 1000;</em></p><p>➡️ This helps to see if the database is performing a full table scan or using an index, which can inform further optimization steps.</p><p><strong><em>Follow me on LinkedIn</em></strong> — <a href="http://linkedin.com/in/sreemala-singha">linkedin.com/in/sreemala-singha</a></p><p><strong><em>Follow me on Medium</em></strong> — <a href="https://medium.com/@sreemala85">https://medium.com/@sreemala85</a></p><p><strong>If you found value in this article, I’d love to hear your thoughts! Please share your feedback by leaving a comment or giving it a ‘clap’ on Medium.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8db8e28fbbf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Difference Between FULL OUTER JOIN and CROSS JOIN in SQL]]></title>
            <link>https://medium.com/@sreemala85/understanding-the-difference-between-full-outer-join-and-cross-join-in-sql-70fe621f6c2f?source=rss-9f661986e2ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/70fe621f6c2f</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[microsoft-sql-server]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Sreemala Singha]]></dc:creator>
            <pubDate>Sat, 09 Nov 2024 12:56:57 GMT</pubDate>
            <atom:updated>2024-11-09T12:56:57.514Z</atom:updated>
            <content:encoded><![CDATA[<p>In SQL, joins are essential for combining data from multiple tables, enabling developers and analysts to generate insights by bringing together related data. Among the various types of joins, <strong>FULL OUTER JOIN</strong> and <strong>CROSS JOIN</strong> are two distinct types that serve unique purposes in SQL queries. Although they both involve combining tables, their methods and outcomes are very different.</p><h3>What is a FULL OUTER JOIN?</h3><p>A <strong>FULL OUTER JOIN</strong> returns all records from both tables, including the rows that do not have a matching row in the other table. If there is no match, SQL fills in NULL values for the missing side.</p><h4>Syntax for FULL OUTER JOIN:</h4><p><em>SELECT *<br>FROM table1<br>FULL OUTER JOIN table2<br>ON table1.column_name = table2.column_name;</em></p><h3>Example of FULL OUTER JOIN</h3><p>Suppose we have two tables — <strong>Employees</strong> and <strong>Departments</strong> as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*SxL49g_XAmf68G-T2K08PA.png" /><figcaption>Employees Table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*AK5UtlC_bTE-zCDqVm4JQQ.png" /><figcaption>Department table</figcaption></figure><p>Using a FULL OUTER JOIN between these tables, we can see employees with departments and also departments without employees:</p><p><em>SELECT e.employee_id, e.name, d.department_name<br>FROM employees e<br>FULL OUTER JOIN departments d<br>ON e.department_id = d.department_id;</em></p><p><strong>Result:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*qeci3cNFka3cIwTs1e5R9g.png" /><figcaption>Full Outer Join</figcaption></figure><h3>When to Use FULL OUTER JOIN</h3><p>A FULL OUTER JOIN is useful when you need all records from both tables, including unmatched rows on either side. It’s often used in reporting or when consolidating data where you need a complete dataset with all possible records.</p><h3>What is a CROSS JOIN?</h3><p>A <strong>CROSS JOIN</strong> is a join operation that produces the Cartesian product of two tables. In other words, it returns every possible combination of rows from both tables. CROSS JOINs do not require a condition to match rows; they combine every row from the first table with every row from the second.</p><h4>Syntax for CROSS JOIN:</h4><p><em>SELECT *<br>FROM table1<br>CROSS JOIN table2;</em></p><h3>Example of CROSS JOIN</h3><p>Using the same <strong>Employees</strong> and <strong>Departments </strong>tables, a CROSS JOIN will produce all combinations of employees and departments:</p><p><em>SELECT e.employee_id, e.name, d.department_name<br>FROM employees e<br>CROSS JOIN departments d;</em></p><p><strong>Result:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*YW_I2WAICtTVatvWc5iuLQ.png" /><figcaption>Cross Join</figcaption></figure><p>In this result, each employee is paired with every department, resulting in a table with <strong>all possible combinations</strong> of rows from <strong>Employees</strong> and <strong>Departments.</strong></p><h3>When to Use CROSS JOIN</h3><p>CROSS JOIN is typically used in scenarios where you need to generate all possible pairs or combinations of data from two tables. This is common in situations such as generating all potential matchups in a tournament, creating all possible pairings in a set, or producing combinations for testing purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCia_wa7KZwSxfx9EWsSYA.png" /><figcaption><strong>Key Differences Between FULL OUTER JOIN and CROSS JOIN</strong></figcaption></figure><h3>Practical Considerations</h3><ol><li><strong>Performance</strong>: CROSS JOINs can quickly grow in size, especially with large tables, as they return every possible combination. Be cautious with CROSS JOINs to avoid unmanageable result sets that may strain your database resources.</li><li><strong>NULL Handling</strong>: FULL OUTER JOIN is more relevant when NULL handling is required for unmatched records, often in reporting contexts.</li><li><strong>Data Suitability</strong>: FULL OUTER JOIN is suited for relational data where some rows may have incomplete matches. CROSS JOIN is often more suitable for scenarios requiring combinatorial data generation.</li></ol><p><strong><em>Follow me on LinkedIn</em></strong> — <a href="http://linkedin.com/in/sreemala-singha">linkedin.com/in/sreemala-singha</a></p><p><strong><em>Follow me on Medium</em></strong> — <a href="https://medium.com/@sreemala85">https://medium.com/@sreemala85</a></p><p><strong>If you found value in this article, I’d love to hear your thoughts! Please share your feedback by leaving a comment or giving it a ‘clap’ on Medium.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70fe621f6c2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SQL Query Execution with Examples]]></title>
            <link>https://medium.com/@sreemala85/understanding-sql-query-execution-with-examples-2cb79d5cca2d?source=rss-9f661986e2ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cb79d5cca2d</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[microsoft-sql-server]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Sreemala Singha]]></dc:creator>
            <pubDate>Fri, 08 Nov 2024 05:31:38 GMT</pubDate>
            <atom:updated>2024-11-08T05:31:38.999Z</atom:updated>
            <content:encoded><![CDATA[<p>SQL (Structured Query Language) is the backbone of data manipulation in databases, used to retrieve, insert, update, and delete data. To design efficient queries, it’s crucial to understand how SQL executes them. The order of operations or <em>SQL query execution order</em> is not the same as the order we typically write our queries.</p><h3>➡️SQL Query Execution Order</h3><p>The order in which SQL executes a query is as follows:</p><ol><li><strong>FROM</strong>: Specifies the tables involved in the query.</li><li><strong>JOIN</strong>: Joins tables based on conditions.</li><li><strong>WHERE</strong>: Filters rows based on specified conditions.</li><li><strong>GROUP BY</strong>: Groups rows with the same values into summary rows.</li><li><strong>HAVING</strong>: Filters groups based on aggregate conditions.</li><li><strong>SELECT</strong>: Selects the columns to display in the result set.</li><li><strong>DISTINCT</strong>: Removes duplicate rows from the results.</li><li><strong>ORDER BY</strong>: Sorts the result set.</li><li><strong>TOP</strong>: Limits the number of rows returned.</li></ol><p>Let’s take a deeper look at each step using practical examples.</p><h3>➡️Examples of Query Execution Steps</h3><h4>Example Scenario</h4><p>Consider the following table structure for a ‘Sales’ table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*04VLec-Y6av6pmy43lxDkA.png" /><figcaption><strong>Sales Table</strong></figcaption></figure><p>Using this data, let’s demonstrate how SQL’s query execution steps work.</p><h3>➡️Step-by-Step Execution</h3><h4>Step 1: FROM</h4><p>The <strong>FROM </strong>clause defines the table(s) from which data is retrieved. SQL begins by loading the data from the specified table.</p><p><em>SELECT *<br>FROM sales;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*04VLec-Y6av6pmy43lxDkA.png" /></figure><h4>Step 2: JOIN</h4><p>When combining data from multiple tables, the <strong>JOIN </strong>clause is applied immediately after loading the initial data in <strong>FROM</strong>. For instance, let’s say we have a ‘Products’ table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*SGmg8R0h2ryo24jSVSPQ7w.png" /><figcaption><strong>Product table</strong></figcaption></figure><p>We can join Sales and Products on product_id to show product names along with sales data:</p><p><em>SELECT s.id, s.customer_id, p.product_name, s.amount<br>FROM sales s<br>JOIN products p ON s.product_id = p.product_id;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*Ne2_9NbwgEgIELF8cSZr2Q.png" /></figure><h4>Step 3: WHERE</h4><p>The <strong>WHERE </strong>clause filters rows based on conditions.</p><p><em>SELECT *<br>FROM sales<br>WHERE amount &gt; 300;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*GSLeXIAS9XOcv9SO4KFLjg.png" /></figure><h4>Step 4: GROUP BY</h4><p>When using aggregation, SQL groups rows with similar values in specified columns. Suppose we want the total sales amount per customer:</p><p><em>SELECT customer_id, SUM(amount) AS total_sales<br>FROM sales<br>GROUP BY customer_id;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*_tdiSs9H3IVufcbn98Ll4Q.png" /></figure><h4>Step 5: HAVING</h4><p><strong>HAVING </strong>works like <strong>WHERE </strong>but applies to aggregations rather than individual rows.</p><p><em>SELECT customer_id, SUM(amount) AS total_sales<br>FROM sales<br>GROUP BY customer_id<br>HAVING SUM(amount) &gt; 500;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*pGxCehpNX-Dt7jUg4Yuvcg.png" /></figure><h4>Step 6: SELECT</h4><p>After filtering and grouping, SQL determines which columns to return with <strong>SELECT</strong>. For example, let’s display only customer IDs and total sales:</p><p><em>SELECT customer_id, SUM(amount) AS total_sales<br>FROM sales<br>GROUP BY customer_id;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*-T2F-Flb0txhDCBr_YoN2w.png" /></figure><h4>Step 7: DISTINCT</h4><p><strong>DISTINCT </strong>removes duplicates from the results. Suppose we want a unique list of customer_ids:</p><p><em>SELECT DISTINCT customer_id<br>FROM sales;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/103/1*u0Yj3nOtczuNkA_MiMuq2w.png" /></figure><h4>Step 8: ORDER BY</h4><p><strong>ORDER BY</strong> sorts the final result set by one or more columns. Here’s an example sorting by total_sales in descending order:</p><p><em>SELECT customer_id, SUM(amount) AS total_sales<br>FROM sales<br>GROUP BY customer_id<br>ORDER BY total_sales DESC;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*NzVOT2Lm6Ern3cFUZLYGJg.png" /></figure><h4>Step 9: LIMIT</h4><p>Finally, <strong>TOP </strong>restricts the number of rows returned. For example, to display the top 3 customers by sales:</p><p><em>SELECT TOP 3 customer_id, SUM(amount) AS total_sales<br>FROM sales<br>GROUP BY customer_id<br>ORDER BY total_sales DESC;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*lftRxoKirWliioXsgaKlVg.png" /></figure><p><strong><em>Note =&gt;</em></strong> The <strong>LIMIT </strong>clause is not supported in SQL Server. Instead, you can use the <strong>TOP </strong>clause to limit the number of rows in SQL Server.</p><h3>➡️Summary of Execution Order vs. Writing Order</h3><p>It’s essential to understand that SQL query execution order is different from the typical syntax order. Here’s a quick comparison:</p><ul><li><strong>Writing Order</strong>: SELECT -&gt; FROM -&gt; JOIN -&gt; WHERE -&gt; GROUP BY -&gt; HAVING -&gt; ORDER BY -&gt; TOP/LIMIT</li><li><strong>Execution Order</strong>: FROM -&gt; JOIN -&gt; WHERE -&gt; GROUP BY -&gt; HAVING -&gt; SELECT -&gt; DISTINCT -&gt; ORDER BY -&gt; TOP/LIMIT</li></ul><p>This difference is critical to writing optimized SQL queries.</p><h3>➡️Why Execution Order Matters</h3><p>Understanding the execution order allows developers to:</p><ol><li><strong>Optimize Queries</strong>: Filtering early (using WHERE) reduces data passed to later steps, improving performance.</li><li><strong>Avoid Common Pitfalls</strong>: Mixing up WHERE and HAVING or GROUP BY can lead to logical errors.</li><li><strong>Design Efficient Reports</strong>: Applying filters and joins correctly helps build efficient data aggregations for reporting.</li></ol><p><strong><em>Follow me on LinkedIn</em></strong> — <a href="http://linkedin.com/in/sreemala-singha">linkedin.com/in/sreemala-singha</a></p><p><strong><em>Follow me on Medium</em></strong> — <a href="https://medium.com/@sreemala85">https://medium.com/@sreemala85</a></p><p><strong>If you found value in this article, I’d love to hear your thoughts! Please share your feedback by leaving a comment or giving it a ‘clap’ on Medium.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cb79d5cca2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide to Recursive CTEs in SQL]]></title>
            <link>https://medium.com/@sreemala85/a-comprehensive-guide-to-recursive-ctes-in-sql-281801ce2f52?source=rss-9f661986e2ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/281801ce2f52</guid>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[microsoft-sql-server]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Sreemala Singha]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 10:10:08 GMT</pubDate>
            <atom:updated>2024-11-07T10:11:17.091Z</atom:updated>
            <content:encoded><![CDATA[<p>Common Table Expressions (CTEs) are a powerful feature in SQL that enable users to create temporary result sets, which can be referenced within a query. Among these, <strong>Recursive CTEs</strong> are particularly valuable for tackling complex hierarchical or sequential data problems.</p><h4><strong>➡️ ️What is a Recursive CTE?</strong></h4><p>A Recursive CTE is a CTE that references itself, allowing SQL to process repeating or hierarchical patterns. It typically consists of two main components:</p><ol><li><strong>Anchor Member</strong>: The initial query, which provides the base data for the recursion.</li><li><strong>Recursive Member</strong>: A query that references the CTE itself, enabling the query to continue building upon the results of the previous iteration.</li></ol><p>The recursive CTE continues to execute until it meets a termination condition, which prevents it from running indefinitely.</p><h4><strong>➡️ Basic Structure</strong></h4><p>Here’s the general structure of a Recursive CTE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*xiU6EsSJKMYKLP5fdHsmLw.png" /><figcaption><strong>Syntax for Recursive CTE</strong></figcaption></figure><h4><strong>➡️</strong>Example 1: Generating a Sequence</h4><p>Let’s start with a simple example where we generate a sequence of numbers from 1 to 10.</p><p><em>WITH Numbers AS (<br> SELECT 1 AS num <br> UNION ALL<br> SELECT num + 1 <br> FROM Numbers<br> WHERE num &lt; 10 <br>)<br>SELECT * FROM Numbers;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*UP-AYMZhMOlRHaMJhnbjaA.png" /></figure><p><strong>💡<em>Explanation —</em></strong></p><ul><li>The <strong>anchor member</strong> starts the sequence with the value 1.</li><li>The <strong>recursive member</strong> then increments num by 1 for each recursive call.</li><li>The recursion stops when num reaches 10, as defined by WHERE num &lt; 10.</li></ul><p><strong>💡<em>Output -</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*lh34aUBfhnbaBg-9wmFMZQ.png" /><figcaption><strong>Generates a sequence of numbers from 1–10</strong></figcaption></figure><h4><strong>➡️ Example 2 : Employee Hierarchy</strong></h4><p>Imagine you have an Employees table with a self-referencing column manager_id, which points to the employee_id of the employee’s manager. This is useful for organizational hierarchy traversal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*92DYutbVCwlLG6qgjd_erw.png" /><figcaption><strong>Employee Table</strong></figcaption></figure><p>To retrieve each employee and their chain of managers up to the top, we can use a recursive CTE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*VtDeaGxxIFGcmpzgSMqDXQ.png" /></figure><p>The error occurs because the hierarchy column in the anchor part of the recursive CTE is a VARCHAR (or TEXT) string (employee_name), but the recursive part is trying to append additional text, which requires hierarchy to be of a type that can hold larger strings, such as VARCHAR(MAX) or TEXT. Let’s resolve this by ensuring hierarchy has a consistent data type throughout the query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*tNgYj5C2T3_LXnpxQErlFg.png" /></figure><h4>➡️Key Considerations for Recursive CTEs</h4><ol><li><strong>Termination Condition</strong>: Recursive CTEs can run indefinitely if they lack a proper stopping condition. Always include a condition in the recursive member (such as a WHERE clause) to limit recursion.</li><li><strong>Performance</strong>: Recursive CTEs can be resource-intensive, especially on large datasets. Optimization strategies, such as indexing and filtering, can help improve performance.</li><li><strong>Recursive Depth</strong>: Some SQL systems allow configuring the maximum recursion depth (often defaulting to 100). This setting helps prevent accidental infinite loops in recursive CTEs.</li></ol><h4>➡️Conclusion</h4><p>Recursive CTEs are powerful tools for handling hierarchical and sequential data in SQL, making it possible to tackle problems that would otherwise be challenging in a single query. By understanding the anchor and recursive members, along with examples like hierarchy generation, sequence calculation, and factorial computation, you can leverage recursive CTEs effectively to simplify complex SQL tasks.</p><p>Recursive CTEs are indispensable for anyone working with hierarchical data or data that needs iterative calculations. Practice with these examples and tailor them to your datasets, and you’ll soon find recursive CTEs invaluable in your SQL toolkit.</p><p><strong><em>Follow me on LinkedIn</em></strong> — <a href="http://linkedin.com/in/sreemala-singha">linkedin.com/in/sreemala-singha</a></p><p><strong><em>Follow me on Medium</em></strong> — <a href="https://medium.com/@sreemala85">https://medium.com/@sreemala85</a></p><p><strong>If you found value in this article, I’d love to hear your thoughts! Please share your feedback by leaving a comment or giving it a ‘clap’ on Medium.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=281801ce2f52" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>