<?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 Lolithasherley on Medium]]></title>
        <description><![CDATA[Stories by Lolithasherley on Medium]]></description>
        <link>https://medium.com/@lolithasherley7?source=rss-56ba65ac9e86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*j4p_nn3rZ2QviAC-.jpg</url>
            <title>Stories by Lolithasherley on Medium</title>
            <link>https://medium.com/@lolithasherley7?source=rss-56ba65ac9e86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:38:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lolithasherley7/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[ Mastering Snowflake: A Complete Guide to Performance, Data Loading, and Best Practices]]></title>
            <link>https://lolithasherley7.medium.com/mastering-snowflake-a-complete-guide-to-performance-data-loading-and-best-practices-b68f448411c4?source=rss-56ba65ac9e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/b68f448411c4</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sql-performance]]></category>
            <category><![CDATA[snowflake-data-cloud]]></category>
            <category><![CDATA[cloud-data-warehouse]]></category>
            <category><![CDATA[etl-and-dataloading]]></category>
            <dc:creator><![CDATA[Lolithasherley]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 08:04:54 GMT</pubDate>
            <atom:updated>2025-04-25T08:04:54.389Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Lolithasherley</em></p><p>Snowflake is a powerful cloud data platform — but to use it efficiently and cost-effectively, you need to understand its architecture, performance tuning, data handling, and access controls. This blog is your all-in-one reference guide.</p><h3>📌 Table of Contents</h3><ol><li>Performance Optimization</li><li>Warehouse Scaling</li><li>Access Control &amp; Security</li><li>Table Types in Snowflake</li><li>Functions and Views</li><li>Data Loading Techniques</li><li>File Formats &amp; COPY Options</li><li>Validation and Error Logging</li><li>Best Practices</li><li>Knowledge Check (Q&amp;A)</li></ol><h3>🧠 1. Performance Optimization</h3><h3>🔸 Traditional vs. Snowflake Partitioning</h3><p>FeatureTraditional PartitioningSnowflake Micro-partitioningCreationManualAutomaticMaintenanceManualNo overheadPartition SizeBased on partition key50–500 MBFlexibilityLowVery high</p><blockquote><em>✅ Snowflake automatically divides tables into </em><strong><em>micro-partitions</em></strong><em> and uses </em><strong><em>pruning</em></strong><em> to optimize query performance.</em></blockquote><h3>🔸 Clustering</h3><p>Clustering helps organize data within micro-partitions. Use clustering when pruning isn’t effective due to complex filters.</p><p><strong>Syntax:</strong></p><pre>CREATE OR REPLACE TABLE test1 (<br>  c1 DATE,<br>  c2 STRING,<br>  c3 NUMBER<br>) CLUSTER BY (c1, c2);</pre><p><strong>Monitor clustering:</strong></p><pre>SELECT SYSTEM$CLUSTERING_INFORMATION(&#39;test1&#39;);</pre><p><strong>Best Practices:</strong></p><ul><li>Use clustering for large tables (&gt;500 GB).</li><li>Choose 3–4 commonly filtered columns.</li><li>Avoid clustering on expressions or function-based filters.</li></ul><h3>📦 2. Warehouse Scaling</h3><p>TypeActionExamplePurposeScale UpIncrease sizeXS ➝ MMore power per clusterScale DownDecrease sizeXL ➝ MReduce costScale OutAdd clusters1 ➝ 3 clustersHandle concurrency (multi-cluster)Scale InRemove clusters3 ➝ 1 clusterReduce compute when idle</p><blockquote><em>💡 All warehouses start with one cluster. Multi-cluster is used to handle high concurrency.</em></blockquote><h3>🔐 3. Access Control &amp; Security</h3><p>Snowflake supports two models:</p><ul><li><strong>DAC</strong> — Discretionary Access Control (owner manages access)</li><li><strong>RBAC</strong> — Role-Based Access Control (roles manage privileges)</li></ul><p><strong>Glossary:</strong></p><p>TermDescriptionUserPerson or service accessing SnowflakeRoleA set of privilegesPrivilegeSELECT, USAGE, OWNERSHIP, etc.Securable ObjectAny Snowflake object (table, DB, etc.)</p><h3>🧱 4. Table Types in Snowflake</h3><p>TypeSession ScopedFail-safeTime TravelUse CasePermanentNoYes0–90 daysCritical dataTransientNoNo0–1 dayShort-term data, cheaperTemporaryYesNoNoSession-specific processing</p><blockquote><em>⚠️ Same-named tables of different types can coexist. Temporary tables take precedence during the session.</em></blockquote><h3>🧠 5. Functions and Views</h3><h3>🔸 UDFs (User Defined Functions)</h3><p>TypeDescriptionScalarReturns a single valueTabularReturns multiple rowsSecureHides logic from users</p><blockquote><em>❌ You can’t convert a stored procedure to a secure one, but you </em><strong><em>can</em></strong><em> alter UDFs to be secure.</em></blockquote><h3>🔸 Views</h3><ul><li><strong>Standard View</strong>: Logical, no storage.</li><li><strong>Materialized View</strong>: Precomputed, improves query speed.</li></ul><blockquote><em>⚠️ Materialized views </em><strong><em>do not support</em></strong><em> joins, group by, UDFs, having, or order by.</em></blockquote><h3>📥 6. Data Loading Techniques</h3><h3>🔸 Bulk Load</h3><p>Use COPY INTO to load large files from internal or external stages.</p><h3>🔸 Snowpipe (Continuous Load)</h3><ul><li>Supports real-time ingestion</li><li>Best file size: 100–250 MB</li><li>Uses serverless compute</li></ul><h3>🔸 Stage Types</h3><p>Stage TypePurposeUser StageLoad from local to any tableTable StageLoad into one matching tableNamed StageReusable, user-managedExternal StageLoad from S3, Azure, GCP</p><blockquote><em>⚠️ Use the </em><strong><em>same region</em></strong><em> for your Snowflake account and cloud storage.</em></blockquote><h3>📂 7. File Formats &amp; COPY Options</h3><h3>🔸 Example: File Format Object</h3><pre>CREATE OR REPLACE FILE FORMAT contacts_format<br>TYPE = &#39;CSV&#39;<br>FIELD_DELIMITER = &#39;|&#39;<br>SKIP_HEADER = 1;</pre><h3>🔸 COPY Options</h3><p>OptionDescriptionON_ERROR=CONTINUESkip bad rowsENFORCE_LENGTH=FALSETruncate overflowing dataTRUNCATECOLUMNS=TRUETruncate fields exceeding column lengthFORCE=TRUEReload even if previously loadedVALIDATION_MODEValidate files without loading</p><h3>✅ 8. Validation &amp; Error Logging</h3><h3>✔️ Validate Files Before Loading</h3><pre>COPY INTO target_table<br>FROM @stage<br>VALIDATION_MODE = RETURN_ERRORS;</pre><pre>INSERT INTO CONTACTS_REJECTED<br>SELECT error, file, rejected_record<br>FROM TABLE(VALIDATE(target_table, JOB_ID =&gt; &#39;_last&#39;));</pre><h3>🌟 9. Best Practices</h3><ul><li>🧱 Use <strong>bulk loading</strong> instead of row-by-row inserts.</li><li>📁 Break files into <strong>100–250 MB</strong> chunks.</li><li>🔄 Load sorted data to minimize clustering costs.</li><li>🧹 Clean up unused temp tables/stages regularly.</li><li>🗑️ Use PURGE=TRUE to delete files after load.</li><li>🌍 Keep stages and Snowflake account in the <strong>same cloud region</strong>.</li></ul><h3>❓ 10. Knowledge Check (Q&amp;A)</h3><pre>Question Answer<br>Are micro-partitions immutable?✅ Yes<br>Does clustering cost extra?✅ Yes<br>Which UDF returns a single value?Scalar<br>Can you insert into materialized views?❌ No<br>Ideal file size for Snowpipe?100–250 MB<br>Does each insert/update create a new micro-partition?✅ Yes<br>Can you cluster using expression-based columns?❌ No<br>Is time travel available for temporary tables?❌ No<br>What model supports roles for access control?RBAC</pre><h3>🧠 11. Ultimate Q&amp;A Reference — Everything You Wanted to Know About Snowflake</h3><p>Below is a detailed, categorized list of real questions with answers — covering loading, validation, scaling, access control, functions, and more.</p><h3>📦 COPY Command &amp; File Format</h3><p><strong>Q:</strong> Will COPY INTO create duplicates if rerun with the same file?<br> <strong>A:</strong> ❌ No, unless FORCE = TRUE is used.</p><p><strong>Q:</strong> Can we transform data while copying?<br> <strong>A:</strong> ✅ Yes. You can use type casts and simple transformations (not complex functions like LOWER()).</p><p><strong>Q:</strong> How to skip header rows?<br> <strong>A:</strong> Set SKIP_HEADER=1 in your file format definition.</p><p><strong>Q:</strong> Can we change a file format type (e.g. from CSV to JSON)?<br> <strong>A:</strong> ❌ No, you’ll need to create a new file format.</p><p><strong>Q:</strong> What is the default ON_ERROR value in COPY INTO?<br> <strong>A:</strong> &#39;ABORT_STATEMENT&#39;</p><h3>⚙️ COPY Behavior &amp; Options</h3><p><strong>Q:</strong> What’s the difference between SKIP_FILE and SKIP_FILE_&lt;n&gt;?<br> <strong>A:</strong>SKIP_FILE: skips entire file if there&#39;s any error</p><ul><li>SKIP_FILE_&lt;n&gt;: skips only if error count ≤ <em>n</em></li></ul><p><strong>Q:</strong> Will Snowflake load one file even if the total size exceeds SIZE_LIMIT?<br> <strong>A:</strong> ✅ Yes, it guarantees loading at least one file.</p><p><strong>Q:</strong> What does RETURN_FAILED_ONLY do?<br> <strong>A:</strong> Shows stats for only files that failed to load.</p><h3>✅ Validation Mode</h3><p><strong>Q:</strong> Does validation mode load data?<br> <strong>A:</strong> ❌ No. It only checks and returns errors.</p><p><strong>Q:</strong> What does RETURN_ERRORS return?<br> <strong>A:</strong> All errors found across all files in the COPY INTO command.</p><p><strong>Q:</strong> What does RETURN_ALL_ERRORS do?<br> <strong>A:</strong> Returns errors even if ON_ERROR=&#39;CONTINUE&#39; was set.</p><p><strong>Q:</strong> How to get only the first <em>n</em> rows validated?<br> <strong>A:</strong> Use VALIDATION_MODE = RETURN_&lt;n&gt;_ROWS</p><p><strong>Q:</strong> How do you split rejected rows into columns?<br> <strong>A:</strong> Use SPLIT_PART() function.</p><h3>🗂️ Stage References</h3><p><strong>Q:</strong> How to refer to a user stage?<br> <strong>A:</strong> @~</p><p><strong>Q:</strong> How to refer to a table stage?<br> <strong>A:</strong> @%&lt;table_name&gt;</p><p><strong>Q:</strong> Can internal stages be altered or dropped?<br> <strong>A:</strong> ❌ No, only named/external stages can be modified or deleted.</p><p><strong>Q:</strong> What is the stage type shown in SHOW STAGES for internal stages?<br> <strong>A:</strong> INTERNAL</p><h3>🧱 Table Types &amp; Time Travel</h3><p><strong>Q:</strong> Which table type is session-scoped?<br> <strong>A:</strong> TEMPORARY</p><p><strong>Q:</strong> Time travel availability for permanent tables?<br> <strong>A:</strong> 0–90 days</p><p><strong>Q:</strong> Can same-named tables exist across different types?<br> <strong>A:</strong> ✅ Yes (e.g., permanent, transient, and temporary)</p><p><strong>Q:</strong> Which one takes precedence during a session?<br> <strong>A:</strong> TEMPORARY</p><p><strong>Q:</strong> Can we create a permanent schema in a transient DB?<br> <strong>A:</strong> ❌ No</p><h3>📐 Micro-partitions &amp; Scaling</h3><p><strong>Q:</strong> What’s the max compressed size of a micro-partition?<br> <strong>A:</strong> 16 MB</p><p><strong>Q:</strong> Are micro-partitions mutable?<br> <strong>A:</strong> ❌ No — they’re immutable</p><p><strong>Q:</strong> Is moving from Medium ➝ Small a scale down?<br> <strong>A:</strong> ✅ Yes</p><p><strong>Q:</strong> Does adding more clusters equal scale out?<br> <strong>A:</strong> ✅ Yes</p><p><strong>Q:</strong> Does reducing clusters equal scale in?<br> <strong>A:</strong> ✅ Yes</p><p><strong>Q:</strong> When does result cache expire?<br> <strong>A:</strong> 24 hours</p><p><strong>Q:</strong> What is the minimum overlap depth required for pruning?<br> <strong>A:</strong> 1</p><h3>🔐 Roles &amp; Access Control</h3><p><strong>Q:</strong> What is ACCOUNTADMIN?<br> <strong>A:</strong> A system-defined top-level role</p><p><strong>Q:</strong> What’s the container for a stage?<br> <strong>A:</strong> A schema</p><p><strong>Q:</strong> Best role for access control?<br> <strong>A:</strong> SYSADMIN</p><p><strong>Q:</strong> What happens if access is given to the PUBLIC role?<br> <strong>A:</strong> Everyone in the account can access it</p><h3>👁️ Views &amp; UDFs</h3><p><strong>Q:</strong> Are views in Snowflake read-only?<br> <strong>A:</strong> ✅ Yes</p><p><strong>Q:</strong> Can you alter a materialized view to add a clustering key?<br> <strong>A:</strong> ✅ Yes</p><p><strong>Q:</strong> Can you insert or update a materialized view?<br> <strong>A:</strong> ❌ No — it’s not allowed</p><p><strong>Q:</strong> Which features are NOT supported in MVs?<br> <strong>A:</strong>JOIN,HAVING,UDFs,ORDER BY and GROUP BY</p><p><strong>Q:</strong> Which UDF type returns a single value?<br> <strong>A:</strong> Scalar UDF</p><p><strong>Q:</strong> Which UDF type returns multiple rows (a table)?<br> <strong>A:</strong> Tabular UDF</p><p><strong>Q:</strong> Can stored procedures return values?<br> <strong>A:</strong> ✅ Yes (optional)</p><p><strong>Q:</strong> Can UDFs be altered to secure after creation?<br> <strong>A:</strong> ✅ Yes</p><p><strong>Q:</strong> Can stored procedures be made secure after creation?<br> <strong>A:</strong> ❌ No</p><p>✅ <strong>Tip:</strong> Bookmark this section or convert it to a cheat sheet — it’s one of the most practical references for anyone working with Snowflake!</p><h3>🧾 Final Thoughts</h3><p>Snowflake is more than a cloud data warehouse — it’s a platform built for scale, speed, and simplicity. But with great power comes the need for <strong>smart usage</strong>. By mastering clustering, warehouse scaling, data loading, and access control, you’ll harness Snowflake’s full potential while keeping costs under control.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b68f448411c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced MCQs on Data Modeling, Power BI, Python, SQL & ML]]></title>
            <link>https://lolithasherley7.medium.com/advanced-mcqs-on-data-modeling-power-bi-python-sql-ml-628470e03419?source=rss-56ba65ac9e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/628470e03419</guid>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[basics-machine-learning]]></category>
            <category><![CDATA[sql-interview-questions]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[dataframes-python]]></category>
            <dc:creator><![CDATA[Lolithasherley]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 10:49:08 GMT</pubDate>
            <atom:updated>2025-04-04T10:49:08.269Z</atom:updated>
            <content:encoded><![CDATA[<h3>Doselect Qualifying Interview Questions &amp; Answer Insight Analyst</h3><p><strong>1. ML: Classification — F1 Score</strong><br><strong>Question:</strong> In the context of model evaluation, what does a high F1 score indicate?<br><strong>Options:</strong><br>a) Model prioritizes false positives only<br>b) Model prioritizes false negatives only<br>c) Model considers both false positives and false negatives<br>d) Model ignores both false positives and false negatives<br><strong>Answer:</strong> c) Model considers both false positives and false negatives<br><strong>Explanation:</strong> F1 Score is the harmonic mean of precision and recall. It balances both false positives and false negatives, which is especially useful in imbalanced datasets.</p><p><strong>2. Deciles of Predictions — KS Curve Dip</strong><br><strong>Question:</strong> What does a dip in the KS curve across deciles indicate?<br><strong>Options:</strong><br>a) The model is highly stable across all deciles<br>b) The model has overfit the training data<br>c) The model has inconsistent discriminatory power<br>d) There is no impact<br><strong>Answer:</strong> c) The model has inconsistent discriminatory power<br><strong>Explanation:</strong> A dip in the KS curve typically signals a region where the model struggles to differentiate between classes, often due to data inconsistencies or model limitations.</p><p><strong>3. Decile Analysis to Assess Model Performance</strong><br><strong>Question:</strong> Which method best helps evaluate model performance across prediction deciles?<br><strong>Options:</strong><br>a) Calculating accuracy for each decile<br>b) Using random predictions as baseline<br>c) Cumulative gains chart and lift comparison<br>d) Confusion matrix only<br><strong>Answer:</strong> c) Cumulative gains chart and lift comparison<br><strong>Explanation:</strong> This method allows evaluation of model performance by comparing it with random chance, and identifying how well it distinguishes classes across prediction ranges.</p><p><strong>4. Confusion Matrix — Error Rate</strong><br><strong>Question:</strong> Given the confusion matrix below, what is the error rate?</p><pre>+----------------------+------------------+------------------+<br>|                      | Predicted: 1     | Predicted: 0     |<br>+----------------------+------------------+------------------+<br>| Actual: 1            | 140 (True Pos.)  | 30 (False Neg.)  |<br>| Actual: 0            | 70 (False Pos.)  | 60 (True Neg.)   |<br>+----------------------+------------------+------------------+</pre><p><strong>Options:</strong><br>a) 20%<br>b) 25%<br>c) 33.33%<br>d) 10%<br><strong>Answer:</strong> c) 33.33%<br><strong>Explanation:</strong> Error Rate = (FP + FN) / Total = (70 + 30) / 300 = 0.3333.</p><p><strong>5. Classification Report — Precision</strong><br><strong>Question:</strong> In the context of the classification report, if the precision of the model is 0.85, what does this value indicate?<br><strong>Options:</strong><br>a) 85% of positive predictions are correct.<br>b) 85% of negative predictions are correct.<br>c) 85% of all predictions are correct.<br>d) 85% of the actual positive cases are identified.<br><strong>Answer:</strong> a) 85% of positive predictions are correct.<br><strong>Explanation:</strong> Precision measures how many of the predicted positives are actually positive. A precision of 0.85 means 85% were correct.</p><p><strong>6. Visualization — Extracting Last Names</strong><br><strong>Question:</strong> Assuming you have a column named Employee Name that contains the full names of employees in the format “FirstName LastName”, which query correctly extracts only the last names?<br><strong>Options:</strong><br>a) SPLIT([Employee Name], ‘ ‘, 1)<br>b) SPLIT([Employee Name], ‘ ‘, 0)<br>c) SPLIT([Employee Name], ‘ ‘, 2)<br>d) SPLIT([Employee Name], ‘ ‘, )<br><strong>Answer:</strong> a) SPLIT([Employee Name], ‘ ‘, 1)<br><strong>Explanation:</strong> This extracts the second part (last name) assuming the format is “First Last”. Indexing is zero-based, so 1 returns the last name.</p><p><strong>7. Power BI — Alternate Name with Cortana</strong><br><strong>Question:</strong> After creating a Cortana Answer Page with an Alternate Name as Sales and a Page Level Filter for City, which of the following queries should be functional?<br><strong>Options:</strong><br>a) All Sales for US<br>b) Show sales for Chicago<br>c) Show Sales By City<br>d) Sales for Chicago and New York<br><strong>Answer:</strong> d) Sales for Chicago and New York<br><strong>Explanation:</strong> This query uses the alternate page name and specifies city filters aligned with page-level filter settings.</p><p><strong>8. Utilizing Inaccessible Layers in Maps</strong><br><strong>Question:</strong> If you encounter map layers that are displayed in gray and are inaccessible, how would you utilize these layers in your mapping process?<br><strong>Options:</strong><br>a) Go to a specific zoom level to enable choosing the map layers<br>b) The options in gray are unavailable and cannot be enabled for that map<br>c) Import the map layer to enable them<br>d) Load a custom dataset to enable those specific map layers<br><strong>Answer:</strong> a) Go to a specific zoom level to enable choosing the map layers<br><strong>Explanation:</strong> Some map layers become interactive only at certain zoom levels in Power BI and mapping tools like ArcGIS or Tableau.</p><p><strong>9. Power BI Performance — Large Datasets</strong><br><strong>Question:</strong> To ensure optimal performance and responsiveness with large sales datasets, which modeling approach is most suitable?<br><strong>Options:</strong><br>a) Tabular Model<br>b) Composite Model<br>c) Multidimensional Model<br>d) Dataflow Model<br><strong>Answer:</strong> b) Composite Model<br><strong>Explanation:</strong> Composite models allow you to combine DirectQuery and Import, balancing performance and data freshness in large datasets.</p><p><strong>10. Time Series — Many Categories</strong><br><strong>Question:</strong> If you have a lot of categories in time series data, what is the best approach for visualization?<br><strong>Options:</strong><br>a) Stream graph<br>b) Line chart<br>c) Bar chart<br>d) Pie chart<br><strong>Answer:</strong> a) Stream graph<br><strong>Explanation:</strong> A stream graph is well-suited for visualizing multiple categories over time, showing fluctuations clearly in a layered format.</p><p><strong>11. Power BI — Pre-filtering Large Data in Power Query</strong><br><strong>Question:</strong> Which Power Query function helps to improve performance by pre-filtering large data before loading it into Power BI?<br><strong>Options:</strong><br>a) Filter Table<br>b) Rename Column<br>c) Filter Rows<br>d) Merge Queries<br><strong>Answer:</strong> c) Filter Rows<br><strong>Explanation:</strong> Applying row filters at the query stage reduces the data volume imported into Power BI, improving performance during modeling and visualization.</p><p><strong>12. Power BI — Premium Capacity Performance Fix</strong><br><strong>Question:</strong> In Power BI Premium, if large datasets and complex DAX calculations cause slowdowns while smaller reports perform well, what’s the best way to address it?<br><strong>Options:</strong><br>a) Upgrade to a Higher v-Core Tier<br>b) Enable Parallel Loading<br>c) Optimize DAX Calculations<br>d) Increase Report Cache Size<br><strong>Answer:</strong> a) Upgrade to a Higher v-Core Tier<br><strong>Explanation:</strong> Scaling up v-cores improves overall memory and processing capacity, helping large datasets and intensive reports perform better.</p><p><strong>13. Power BI — Regional Dataset Advantages</strong><br><strong>Question:</strong> A company wants to create a smaller, region-specific dataset from a large global logistics dataset. What is the biggest advantage?<br><strong>Options:</strong><br>a) Simplified Data Model<br>b) Data Granularity<br>c) Resource Consumption<br>d) Historical Data<br><strong>Answer:</strong> a) Simplified Data Model<br><strong>Explanation:</strong> Focusing on a regional subset reduces data complexity, making models simpler and reports more responsive.</p><p><strong>14. Tableau — Hiding Filters During Presentation</strong><br><strong>Question:</strong> Mr. John wants to hide the filters and pages section in Tableau during a client presentation. What’s the most efficient way?<br><strong>Options:</strong><br>a) Show/Hide Cards button<br>b) Present button<br>c) Format option<br>d) Dashboard option<br><strong>Answer:</strong> a) Show/Hide Cards button<br><strong>Explanation:</strong> This button toggles the visibility of filter and pages shelves, making it ideal for quick clean-up during presentations.</p><p><strong>15. Tableau — Using Older (.tde) Extract File</strong><br><strong>Question:</strong> Mr. John has a 2015 Tableau Data Extract (.tde) file and wants to use it in the latest Tableau version. What’s the solution?<br><strong>Options:</strong><br>a) The (.tde) file format gets corrupted by changing its format<br>b) The (.tde) format files can be converted into hyper format<br>c) The conversion is cost expensive and not effective<br>d) The (.tde) file format cannot be converted into other format<br><strong>Answer:</strong> b) The (.tde) format files can be converted into hyper format<br><strong>Explanation:</strong> Tableau supports conversion of .tde files to the newer .hyper format, ensuring compatibility with newer Tableau features.</p><h4>16.What is the key difference between the CHARINDEX and SUBSTRING functions in SQL?</h4><p>The key difference between CHARINDEX and SUBSTRING in SQL is their purpose and functionality:</p><p>✅ <strong>“</strong><strong>CHARINDEX is used to determine the position of a specific character or substring within a string, while </strong><strong>SUBSTRING is used to extract a portion of a string based on its position and length.&quot;</strong></p><ol><li><strong>CHARINDEX</strong></li></ol><ul><li>Used to find the position (index) of a substring within a string.</li><li>Returns an integer indicating the starting position of the substring.</li><li>If the substring is not found, it returns 0.</li><li>Syntax:CHARINDEX(substring, string, start_position)</li><li>Example:SELECT CHARINDEX(&#39;o&#39;, &#39;Hello World&#39;); -- Returns 5 (1-based index)</li></ul><h3>Key Difference</h3><ul><li>CHARINDEX <strong>finds</strong> the position of a substring within a string.</li><li>SUBSTRING <strong>extracts</strong> a portion of a string based on position and length.</li></ul><p>They are often used together, for example, extracting text after a specific character:</p><pre>SELECT SUBSTRING(&#39;Hello World&#39;, CHARINDEX(&#39; &#39;, &#39;Hello World&#39;) + 1, LEN(&#39;Hello World&#39;));<br>-- Returns &#39;World&#39;</pre><p>This extracts everything after the first space.</p><h4>17. The SQL query retrieves a result set from the employees table based on the following criteria and transformations:</h4><h3>Columns Selected:</h3><ol><li><strong>employee_id</strong> - The unique identifier of the employee.</li><li><strong>last_name</strong> - The employee&#39;s last name.</li><li><strong>hire_date_formatted</strong> - The hire date formatted as &quot;Month DD, YYYY&quot; (e.g., <em>January 15, 2005</em>).</li><li><strong>days_since_1980</strong> - The number of days between the employee&#39;s hire date and <strong>January 1, 1980</strong>.</li></ol><h3>Filters Applied:</h3><ul><li>Only employees whose last_name <strong>starts with &#39;A&#39;</strong> (LIKE &#39;A%&#39;) will be included.</li></ul><pre>SELECT <br>  employee_id, <br>  last_name, <br>  TO_CHAR(hire_date, &#39;Month DD, YYYY&#39;) as hire_date_formatted,<br>  hire_date - TO_DATE(&#39;1980-01-01&#39;, &#39;YYYY-MM-DD&#39;) as days_since_1980<br>FROM <br>  employees<br>WHERE <br>  last_name LIKE &#39;A%&#39;; what is SQL REULT set</pre><pre>Expected Result Set (Example Output)<br>employee_id         last_name       hire_date_formatted     days_since_1980<br>101                    Adams       March 12, 1995               5567<br>204                 Anderson       July 23, 2002                 8250<br>305               Alvarez         December 05, 2010              11638</pre><h3>Explanation of Results:</h3><ol><li><strong>TO_CHAR(hire_date, &#39;Month DD, YYYY&#39;)</strong>Converts hire_date into a formatted string, ensuring a human-readable date.</li><li><strong>hire_date - TO_DATE(&#39;1980-01-01&#39;, &#39;YYYY-MM-DD&#39;)</strong></li></ol><ul><li>Calculates the number of days an employee has been hired <strong>since January 1, 1980</strong>.</li></ul><p>To get the <strong>same result set</strong> in an <strong>Oracle Database</strong>, let’s analyze which SQL query would be equivalent to the one provided. The original query:</p><pre>SELECT <br>  employee_id, <br>  last_name, <br>  TO_CHAR(hire_date, &#39;Month DD, YYYY&#39;) as hire_date_formatted,<br>  hire_date - TO_DATE(&#39;1980-01-01&#39;, &#39;YYYY-MM-DD&#39;) as days_since_1980<br>FROM <br>  employees<br>WHERE <br>  last_name LIKE &#39;A%&#39;;</pre><h3>Key Components in Oracle SQL:</h3><ol><li><strong>TO_CHAR(hire_date, &#39;Month DD, YYYY&#39;)</strong> → Converts hire_date into a formatted string.</li><li><strong>hire_date - TO_DATE(&#39;1980-01-01&#39;, &#39;YYYY-MM-DD&#39;)</strong> → Calculates the difference in days.</li><li><strong>LIKE &#39;A%&#39;</strong> → Filters employees whose last_name starts with &#39;A&#39;.</li></ol><h3>Equivalent Queries:</h3><p>Now, let’s check potential equivalent queries:</p><pre>SELECT <br>  employee_id, <br>  last_name, <br>  TO_CHAR(hire_date, &#39;Month DD, YYYY&#39;) AS hire_date_formatted,<br>  hire_date - DATE &#39;1980-01-01&#39; AS days_since_1980<br>FROM <br>  employees<br>WHERE <br>  last_name LIKE &#39;A%&#39;;</pre><h4>Why is this correct?</h4><ul><li><strong>DATE &#39;1980-01-01&#39;</strong> is a shorthand for TO_DATE(&#39;1980-01-01&#39;, &#39;YYYY-MM-DD&#39;) in Oracle.</li><li>The rest of the query remains the same, ensuring the same result set.</li></ul><h4>❌ Incorrect Queries:</h4><ol><li><strong>Using </strong><strong>SYSDATE instead of </strong><strong>TO_DATE(&#39;1980-01-01&#39;, &#39;YYYY-MM-DD&#39;):</strong></li></ol><pre>SELECT <br>  employee_id, <br>  last_name, <br>  TO_CHAR(hire_date, &#39;Month DD, YYYY&#39;) AS hire_date_formatted,<br>  hire_date - SYSDATE AS days_since_1980<br>FROM <br>  employees<br>WHERE <br>  last_name LIKE &#39;A%&#39;;</pre><ul><li><strong>Issue:</strong></li><li>SYSDATE gives the <strong>current date</strong>, so hire_date - SYSDATE does not match the original query&#39;s logic.</li></ul><p><strong>2. Formatting </strong><strong>hire_date incorrectly:</strong></p><pre>SELECT <br>  employee_id, <br>  last_name, <br>  TO_CHAR(hire_date, &#39;DD-Mon-YYYY&#39;) AS hire_date_formatted, -- Wrong format<br>  hire_date - TO_DATE(&#39;1980-01-01&#39;, &#39;YYYY-MM-DD&#39;) AS days_since_1980<br>FROM <br>  employees<br>WHERE <br>  last_name LIKE &#39;A%&#39;;</pre><ol><li><strong>Issue:</strong></li></ol><ul><li>TO_CHAR(hire_date, &#39;DD-Mon-YYYY&#39;) formats differently than &#39;Month DD, YYYY&#39;.</li></ul><h3>Final Answer:</h3><p>✅ The correct equivalent query in Oracle:</p><pre>SELECT <br>  employee_id, <br>  last_name, <br>  TO_CHAR(hire_date, &#39;Month DD, YYYY&#39;) as hire_date_formatted,<br>  hire_date - DATE &#39;1980-01-01&#39; as days_since_1980<br>FROM <br>  employees<br>WHERE <br>  last_name LIKE &#39;A%&#39;;</pre><h4>18. DBMS : Length Function MCQ Unsolved You have a table named products with the following columns: product_id, product_name, and description.</h4><p>You need to retrieve a list of product names that have a description containing the word “premium” and are at least 10 characters long. Additionally, you want the product names to be displayed in reverse order (reversed strings) in the result.</p><p>Write an SQL query to achieve this.</p><pre>a. SELECT REVERSE(CONCAT(product_name)) AS reversed_name FROM products WHERE LENGTH(description) &gt;= 10 AND POSITION(&#39;premium&#39; IN description) &gt; 0;<br>b. SELECT REVERSE(LEFT(product_name, LENGTH(product_name))) AS reversed_name FROM products WHERE LENGTH(description) &gt;= 10 AND INSTR(description, &#39;premium&#39;) &gt; 0;<br>c. SELECT REVERSE(SUBSTRING(product_name, 1, LENGTH(product_name))) AS reversed_name FROM products WHERE LENGTH(description) &gt;= 10 AND LOCATE(&#39;premium&#39;, description) &gt; 0;<br>d. SELECT REVERSE(product_name) AS reversed_name FROM products WHERE CHAR_LENGTH(description) &gt;= 10 AND description LIKE &#39;%premium%&#39;;</pre><p>✅ <strong>For MySQL and most other databases, the correct query is:</strong></p><pre>SELECT REVERSE(product_name) AS reversed_name <br>FROM products <br>WHERE CHAR_LENGTH(description) &gt;= 10 <br>AND description LIKE &#39;%premium%&#39;;</pre><h3>Why is this correct?</h3><ol><li><strong>REVERSE(product_name)</strong>Reverses the string correctly.</li><li><strong>CHAR_LENGTH(description) &gt;= 10</strong>Ensures that the description has <strong>at least 10 characters</strong>.</li></ol><p>3.CHAR_LENGTH() is preferred over LENGTH() because LENGTH() might return <strong>byte count</strong> instead of character count.</p><p><strong>4. description LIKE &#39;%premium%&#39;</strong>Checks if &quot;premium&quot; is present anywhere in the description.</p><p>5.<strong>Issues:</strong>CONCAT(product_name) is unnecessary since product_name is already a string.</p><ul><li>POSITION(&#39;premium&#39; IN description) is <strong>valid in PostgreSQL</strong>, but not in MySQL or Oracle.</li></ul><p>19. SQL: Vowel MCQ Unsolved Given the SQL query below, what will be the result?</p><pre>SELECT PATINDEX(&#39;%[aeiou]%&#39;, &#39;rhyme with why&#39;);<br>Answer ( Please choose a correct answer )<br>1<br>4<br>5<br>7</pre><p>The <strong>correct answer is </strong><strong>4</strong>.</p><h3>Explanation:</h3><ul><li>PATINDEX(&#39;%[aeiou]%&#39;, &#39;rhyme with why&#39;) is a <strong>SQL Server function</strong> that returns the <strong>position</strong> of the first occurrence of any vowel (a, e, i, o, u) in the given string.</li><li>The given string is <strong>‘rhyme with why’</strong>.</li><li>Checking each character:<br> <strong>r (1), h (2), y (3), m (4), e (5)</strong> → The first vowel is <strong>‘e’</strong>, which is in the <strong>4th</strong> position.</li></ul><p>Thus, the query returns <strong>4</strong>. ✅</p><h4>20. DBMS : String World MCQ Unsolved Given the string &quot;Hello World&quot;, what would be the result of the following SQL query:</h4><p>SELECT SUBSTRING(&#39;Hello World&#39;, 7, 5);</p><ul><li>Extracts a portion of a string based on a starting position and length.</li></ul><p>Returns the extracted substring.SUBSTRING(string, start_position, length)</p><p>Example:SELECT SUBSTRING(&#39;Hello World&#39;, 7, 5); -- Returns &#39;World&#39;</p><h3>Explanation:</h3><p>The <strong>SUBSTRING</strong> function in SQL extracts a portion of a string based on:</p><pre>SUBSTRING(string, start_position, length)</pre><ul><li><strong>String:</strong> &#39;Hello World&#39;</li><li><strong>Start position:</strong> 7 (1-based index)</li><li><strong>Length:</strong> 5 (number of characters to extract)</li></ul><p>The string <strong>“Hello World”</strong> is indexed as:</p><pre>H  e  l  l  o     W  o  r  l  d<br>1  2  3  4  5  6  7  8  9 10 11</pre><ul><li><strong>Start at position </strong><strong>7</strong> → &#39;W&#39;</li><li><strong>Extract </strong><strong>5 characters</strong> → &quot;World&quot;</li></ul><h4>21.DBMS : Uppercase Employee MCQ Unsolved Let&#39;s consider a table named &#39;Employee&#39; with column name emp_id, first_name, last_name, email. Find the last name of the employee where the first letter of the last name matches the first letter of the email address and both are in uppercase.</h4><pre>SELECT last_name <br>FROM Employee <br>WHERE UPPER(LEFT(last_name, 1)) = UPPER(LEFT(email, 1));</pre><h3>Explanation:</h3><ol><li><strong>UPPER(LEFT(last_name, 1))</strong></li></ol><ul><li>Extracts the <strong>first letter</strong> of last_name and converts it to <strong>uppercase</strong>.</li></ul><p>2.<strong>UPPER(LEFT(email, 1))</strong></p><ul><li>Extracts the <strong>first letter</strong> of email and converts it to <strong>uppercase</strong>.</li></ul><p>3. <strong>WHERE condition:</strong></p><ul><li>Compares whether the first letter of last_name <strong>matches</strong> the first letter of email, both in uppercase.</li></ul><h3>Alternative Syntax (for different SQL dialects):</h3><p><strong>For MySQL &amp; PostgreSQL:</strong></p><ul><li>SELECT last_name FROM Employee WHERE LEFT(UPPER(last_name), 1) = LEFT(UPPER(email), 1);</li></ul><p><strong>For Oracle:</strong></p><ul><li>SELECT last_name FROM Employee WHERE SUBSTR(UPPER(last_name), 1, 1) = SUBSTR(UPPER(email), 1, 1);</li></ul><pre>Example Data:<br>emp_id     first_name       last_name       email<br>1         John               Smith         Smith@xyz.com ✅<br>2          Jane             Brown          Brown@abc.com ✅<br>3           Alice           Davis         alice@xyz.com ❌ (Lowercase mismatch)</pre><p>✅ <strong>Rows 1 &amp; 2 match the condition</strong> because the first letter of last_name matches the first letter of email when both are converted to uppercase.</p><h3>21. Pickthe right one</h3><pre>SELECT last_name FROM Employees WHERE UPPER(LEFT(last_name, 1)) = UPPER(RIGHT(email, 1));<br>Select last_name from Employee where UPPER (SUBSTRING(last_name, 1, 1)) = LEFT (UPPER(email),1);<br>SELECT last_name FROM Employees WHERE SUBSTRING(last_name, 1, 1) = LEFT(email, 1);<br>SELECT last_name FROM Employees WHERE UPPER(last_name) = UPPER(email); </pre><p>The <strong>correct answer</strong> is:<br> ✅ <strong>Select last_name from Employee where UPPER (SUBSTRING(last_name, 1, 1)) = LEFT (UPPER(email),1);</strong></p><h3>Explanation:</h3><ol><li><strong>SUBSTRING(last_name, 1, 1)</strong>Extracts the <strong>first letter</strong> of last_name.</li><li><strong>UPPER(SUBSTRING(last_name, 1, 1))</strong>Converts the first letter of last_name to <strong>uppercase</strong>.</li><li><strong>LEFT(UPPER(email), 1)</strong>Extracts the first letter of email <strong>in uppercase</strong>.</li><li><strong>WHERE condition: </strong>Compares the <strong>first letter</strong> of last_name with the <strong>first letter</strong> of email, both in uppercase.</li></ol><h4>22. SQL: Employees You are given a table Employees with the following columns: EmployeeID, FirstName, and LastName. You want to find all employees whose last names sound similar to “Smith”. Which of the following queries correctly retrieves this information using the SOUNDEX function?</h4><pre><br><br>SELECT EmployeeID, FirstName, LastName<br>FROM Employees<br>WHERE SOUNDEX(LastName) = &#39;Smith&#39;;<br><br><br><br>SELECT EmployeeID, FirstName, LastName<br>FROM Employees <br>WHERE SOUNDEX(LastName) = SOUNDEX(&#39;Smith&#39;);<br><br><br><br>SELECT EmployeeID, FirstName, LastName<br>FROM Employees <br>WHERE LastName LIKE SOUNDEX(&#39;Smith&#39;);<br><br><br><br>SELECT EmployeeID, FirstName, LastName<br>FROM Employees <br>WHERE SOUNDEX(LastName) LIKE &#39;Smith&#39;;</pre><p>✅ <strong>Correct Answer:</strong></p><pre>SELECT EmployeeID, FirstName, LastName<br>FROM Employees <br>WHERE SOUNDEX(LastName) = SOUNDEX(&#39;Smith&#39;);</pre><h3>Explanation:</h3><p>The <strong>SOUNDEX</strong> function is used in SQL to compare words that <strong>sound similar</strong>. It generates a four-character code based on phonetic pronunciation.</p><p>To check if the LastName sounds like &quot;Smith&quot;, we <strong>compare the SOUNDEX values</strong> of both:</p><pre>SOUNDEX(LastName) = SOUNDEX(&#39;Smith&#39;)</pre><h4>23. SQL : Create to Replace MCQ Unsolved Identify the incorrect description of the SQL statement provided below, which is used to define a function.</h4><pre>CREATE OR REPLACE FUNCTION get_file_list (text, Boolean) <br>RETURNS SETOF TEXT LANGUAGE C STRICT SECURITY DEFINER AS &#39;myfuncs.so&#39;;</pre><p>The function returns a set of text values.</p><p>This function can be defined in &#39;myfuncs.so&#39;.</p><p>The function allows NULL values as input parameters.</p><p>The function executes with the privileges of the user who defined it.</p><pre>CREATE OR REPLACE FUNCTION get_file_list (text, Boolean) <br>RETURNS SETOF TEXT <br>LANGUAGE C <br>STRICT <br>SECURITY DEFINER <br>AS &#39;myfuncs.so&#39;;</pre><p>defines a function in <strong>PostgreSQL</strong> that:</p><ol><li><strong>Returns a set of text values</strong> (SETOF TEXT ✅ <strong>Correct</strong>).</li><li><strong>Is implemented in a shared object file (</strong><strong>myfuncs.so)</strong>, written in C (LANGUAGE C ✅ <strong>Correct</strong>).</li><li><strong>Runs with the privileges of the function’s creator</strong> (SECURITY DEFINER ✅ <strong>Correct</strong>).</li><li><strong>Does NOT allow NULL values as input parameters</strong> (STRICT ❌ <strong>Incorrect Statement</strong>).</li></ol><h3>Why is the incorrect answer correct?</h3><ul><li><strong>The </strong><strong>STRICT keyword in PostgreSQL means the function automatically returns NULL if any input parameter is NULL.</strong></li><li><strong>This prevents the function from executing when NULL inputs are given.</strong></li><li>So, <strong>the statement “The function allows NULL values as input parameters.” is incorrect.</strong></li></ul><h3>Why are the other options correct?</h3><p>✅ <strong>“The function returns a set of text values.”</strong> → Correct, because SETOF TEXT means the function returns multiple text values.</p><p>✅ <strong>“This function can be defined in ‘myfuncs.so’.”</strong> → Correct, because the function is written in C and loaded from myfuncs.so.</p><p>✅ <strong>“The function executes with the privileges of the user who defined it.”</strong> → Correct, because SECURITY DEFINER means it runs with the <strong>privileges of the function&#39;s creator</strong>.</p><h4>24.SQL: Database Admin MCQ Unsolved You are an SQL developer for a multinational company that sells various kinds of products across different countries.</h4><p>You have two tables in your database:</p><p>a. Orders table which has columns: OrderID, CustomerID, ProductID, OrderDate, and Country.</p><p>b. Customers table which has columns: CustomerID, CustomerName, ContactNumber, Email, and Country.</p><p>c. You’ve been asked to generate a list of all customers, along with their order details(ProductID and OrderDate) if any, residing in the ‘United States’. Which of the following SQL queries would you use to perform this task?</p><pre>SELECT Customers.CustomerName, Orders.ProductID, Orders.OrderDate FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Customers.Country = &#39;United States&#39;;<br>SELECT Customers.CustomerName, Orders.ProductID, Orders.OrderDate FROM Customers RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Customers.Country = &#39;United States&#39;;<br>SELECT Customers.CustomerName, Orders.ProductID, Orders.OrderDate FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Orders.Country = &#39;United States&#39;;<br>SELECT Customers.CustomerName, Orders.ProductID, Orders.OrderDate FROM Customers RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Orders.Country = &#39;United States&#39;;</pre><pre>✅ Correct Answer:<br>**```sql SELECT Customers.CustomerName, Orders.ProductID, Orders.OrderDate<br> FROM Customers <br>LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID <br>WHERE Customers.Country = &#39;United States&#39;;</pre><h4>25. SQL: Free Text MCQ Unsolved Consider the following SQL query using Full-Text Search:</h4><pre>SELECT DocumentID, Title FROM Documents WHERE CONTAINS(Title, &#39;FREETEXT(&#39;&#39;technology&#39;&#39;)&#39;);</pre><h4>What will this query return?</h4><h3>Correct Query Explanation</h3><h4>Option 1: Using CONTAINS</h4><p>If the query was written correctly as:</p><pre>SELECT DocumentID, Title<br>FROM Documents<br>WHERE CONTAINS(Title, &#39;technology&#39;);</pre><p>✅ It would <strong>return all documents where the </strong><strong>Title contains the exact word &#39;technology&#39;</strong> or matches variations based on the Full-Text Search Index.</p><h4>Option 2: Using FREETEXT</h4><p>If the intention was to use <strong>FREETEXT()</strong>, the correct query should be:</p><pre>SELECT DocumentID, Title<br>FROM Documents<br>WHERE FREETEXT(Title, &#39;technology&#39;);</pre><p>✅ This would <strong>return documents where the </strong><strong>Title is related to &#39;technology&#39;, considering synonyms and linguistic variations</strong> (e.g., &quot;technological&quot;, &quot;tech industry&quot;, etc.).</p><h3>Final Answer:</h3><p>🔴 The provided query is incorrect due to <strong>syntax errors</strong>.<br> ✅ If you meant an exact match, use CONTAINS(Title, &#39;technology&#39;).<br> ✅ If you meant a broader match (synonyms, variations), use FREETEXT(Title, &#39;technology&#39;).</p><p>The correct answer depends on <strong>how Full-Text Search is used</strong> in SQL Server:</p><p>1️⃣ <strong>CONTAINS(Title, &#39;technology&#39;) →</strong> Returns documents where the <strong>title contains the exact word</strong> ‘technology’. ✅ <strong>(Correct choice for first option)</strong></p><p>2️⃣ <strong>FREETEXT(Title, &#39;technology&#39;) →</strong> Returns documents where the <strong>title contains variations and synonyms</strong> of ‘technology’. ✅ <strong>(Correct choice for second option)</strong></p><p>3️⃣ <strong>CONTAINS(Title, &#39;&quot;technology&quot;&#39;) →</strong> Ensures the <strong>exact phrase</strong> ‘technology’ appears in the title. ✅ <strong>(Correct choice for third option)</strong></p><p>4️⃣ <strong>CONTAINS(Title, &#39;technology AND other_specific_word&#39;)</strong> → Finds documents where ‘technology’ <strong>and</strong> another specific word appear. ✅ <strong>(Correct choice for fourth option)</strong></p><p>🔹 <strong>Final Answer:</strong><br> Since your given query is incorrect, the intended meaning is closest to <strong>option 1 (exact word ‘technology’)</strong>.</p><h4>26.Understanding P-Values in Model Evaluation MCQ Unsolved In the context of evaluating the accuracy of a machine learning model, what role does the p-value play?</h4><p>It measures the model&#39;s prediction accuracy on the test dataset, with lower values indicating higher accuracy.</p><p>It indicates the importance of features used in the model, with higher values suggesting greater importance.</p><p>It assesses the strength of the relationship between the model&#39;s predictions and the actual outcomes, with lower values indicating a statistically significant relationship.</p><p>It calculates the percentage of data points correctly classified by the model out of the total number of points.</p><p>The correct answer is:</p><p>✅ <strong>“It assesses the strength of the relationship between the model’s predictions and the actual outcomes, with lower values indicating a statistically significant relationship.”</strong></p><h3>Explanation:</h3><ul><li><strong>P-value</strong> is a statistical measure used in hypothesis testing, often in regression models.</li><li>It helps determine whether an independent variable has a <strong>statistically significant</strong> impact on the dependent variable.</li><li><strong>Lower p-values (&lt; 0.05)</strong> suggest that the feature has a meaningful relationship with the target variable.</li><li><strong>Higher p-values (&gt; 0.05)</strong> indicate that the feature may not significantly contribute to the model.</li></ul><h4>27. ML: Precision-Recall Tradeoff MCQ Unsolved Alex, an experienced data scientist with three years in the field, is developing a healthcare classification model. The objective is to predict whether a patient has a specific medical condition based on features like age, blood pressure, and cholesterol levels. After thorough data preprocessing and feature engineering, Alex uses a popular machine learning algorithm to train the model. Encouraging results are obtained during the training phase, prompting Alex to assess its performance on a test dataset. In the evaluation process, Alex focuses on the classification report to gain insights into the model’s performance. The dataset is imbalanced, with more negative cases than positive ones, mirroring the real-world distribution of the medical condition in the population.</h4><h4>If Alex’s classification model has a high precision but a low recall, what can be inferred about the model’s performance?</h4><p>a. The model is good at identifying positive cases but might miss some.</p><p>b. The model is conservative and rarely predicts positive cases.</p><p>c. The model is accurate in predicting both positive and negative cases.</p><p>d. The model is not performing well on any aspect.</p><p>The correct answer is:</p><p>✅ <strong>“The model is conservative and rarely predicts positive cases.”</strong></p><h3>Explanation:</h3><ul><li><strong>Precision</strong> measures how many of the predicted <strong>positive cases</strong> are <strong>actually positive</strong> (i.e., how correct the model is when it predicts a positive).</li><li><strong>Recall</strong> measures how many of the <strong>actual positive cases</strong> the model correctly identifies (i.e., how well the model captures all positives).</li><li>A <strong>high precision but low recall</strong> means the model <strong>only predicts positive cases when it’s very confident</strong>, leading to <strong>fewer false positives but more false negatives</strong> (it misses actual positive cases).</li><li>In <strong>healthcare</strong>, this can be risky, as missing positive cases (patients with the condition) could have serious consequences.</li></ul><h4>28.AUC-ROC MCQ Unsolved The given figure shows three Area-under-ROC curves for three different regression models. Different hyper parameter value curves are shown in three different colours: Green (outer curve), Blue (middle curve), Yellow (inner curve/straight line).</h4><p>Which curve gives the best result?</p><p>Answer</p><p>Yellow</p><p>Blue</p><p>Green</p><p>All the three have the same results</p><p>The correct answer is:</p><p>✅ <strong>Green (outer curve)</strong></p><h3>Explanation:</h3><ul><li><strong>AUC-ROC (Area Under the Receiver Operating Characteristic Curve)</strong> is used to evaluate the performance of a <strong>classification model</strong> (not regression).</li><li>A <strong>higher AUC value</strong> indicates a better-performing model.</li><li>The <strong>Green curve (outer curve)</strong> is the farthest from the diagonal (random guessing) and <strong>closest to the top left corner</strong>, meaning it has the <strong>highest AUC value</strong> and the best performance.</li><li>The <strong>Yellow curve (inner curve/straight line)</strong> represents <strong>random guessing (AUC ≈ 0.5)</strong>, meaning the model is not making useful predictions.</li><li>The <strong>Blue curve (middle curve)</strong> performs better than Yellow but worse than Green.</li></ul><h4>29. Binary Classification MCQ Unsolved In the context of model evaluation, what does a log loss value closer to 0 indicate about a model&#39;s performance on a binary classification task?</h4><p>Answer s</p><p>The model consistently predicts the less frequent class more accurately than the more frequent class.</p><p>The model has a high bias towards one of the classes, leading to a skewed distribution of predicted probabilities.</p><p>The model&#39;s predicted probabilities are close to the actual class labels, indicating high accuracy.</p><p>The model performs equally poorly on both classes, indicating a need for retraining with a different algorithm.</p><p>he correct answer is:</p><p>✅ <strong>The model’s predicted probabilities are close to the actual class labels, indicating high accuracy.</strong></p><h3>Explanation:</h3><ul><li><strong>Log loss (Logarithmic Loss or Cross-Entropy Loss)</strong> is a key metric for evaluating probabilistic predictions in <strong>binary classification</strong> tasks.</li><li>A <strong>lower log loss (closer to 0)</strong> means that the predicted probabilities are <strong>very close</strong> to the actual labels (either 0 or 1). This indicates that the model is well-calibrated and making highly accurate predictions.</li><li>Conversely, a <strong>higher log loss</strong> suggests that the model is making poor probability estimates.</li></ul><h4>30. <strong>AI/ML — Overfitting</strong><br> <strong>Question:</strong> Which of the following best describes overfitting in a machine learning model?</h4><p><strong>Options:</strong><br> a) The model performs well on both training and unseen data<br> b) The model performs poorly on both training and test data<br> c) The model performs well on training data but poorly on test data<br> d) The model performs well on test data only<br> <strong>Answer:</strong> c) The model performs well on training data but poorly on test data<br> <strong>Explanation:</strong> Overfitting occurs when a model learns the training data too well, including noise, which reduces its ability to generalize to new, unseen data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=628470e03419" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering SQL Window Functions: A Comprehensive Guide with Examples]]></title>
            <link>https://lolithasherley7.medium.com/mastering-sql-window-functions-a-comprehensive-guide-with-examples-ce1960ba8d41?source=rss-56ba65ac9e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce1960ba8d41</guid>
            <category><![CDATA[sql-ranking-functions]]></category>
            <category><![CDATA[sql-queries]]></category>
            <category><![CDATA[sql-window-functions]]></category>
            <category><![CDATA[advanced-sql]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Lolithasherley]]></dc:creator>
            <pubDate>Thu, 20 Mar 2025 15:07:07 GMT</pubDate>
            <atom:updated>2025-03-20T15:07:07.984Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>SQL <strong>window functions</strong> allow you to perform calculations across a specific range of rows <strong>without collapsing data</strong> into a single result. They are commonly used in <strong>ranking, running totals, moving averages, and percentile calculations</strong>.</p><p>In this guide, we will cover <strong>all essential SQL window functions</strong>, including:</p><ul><li>FIRST_VALUE()</li><li>NTH_VALUE()</li><li>LEAD()</li><li>LAG()</li><li>AVG()</li><li>PERCENT_RANK()</li><li>CUME_DIST()</li><li>NTILE()</li><li>PERCENTILE_CONT()</li><li>PERCENTILE_DISC()</li><li>RANK()</li><li>DENSE_RANK()</li><li>ROW_NUMBER()</li></ul><h3>Understanding Window Functions</h3><p>A window function requires an <strong>OVER()</strong> clause, which defines the &quot;window&quot; of rows the function operates over. It can include:</p><ul><li><strong>PARTITION BY</strong>: Divides rows into separate groups.</li><li><strong>ORDER BY</strong>: Specifies the row order within each partition.</li></ul><h3>SQL Window Functions with Examples</h3><h3>1. FIRST_VALUE() – First value in a partition</h3><p>Returns the <strong>first value</strong> within each partition.<br>SQL Query</p><pre>SELECT department, employee, salary,<br>       FIRST_VALUE(employee) OVER (PARTITION BY department ORDER BY salary DESC) AS first_emp<br>FROM employees;</pre><h4>Breakdown</h4><ul><li><strong>FIRST_VALUE(employee)</strong>: Gets the first employee&#39;s name based on salary.</li><li><strong>PARTITION BY department</strong>: Groups by department.</li><li><strong>ORDER BY salary DESC</strong>: Orders salaries in descending order.</li></ul><h4>Output</h4><pre>+------------+------------+--------+------------+<br>| Department | Employee   | Salary | First_Emp  |<br>+------------+------------+--------+------------+<br>| HR         | Alice      | 60000  | Alice      |<br>| HR         | Bob        | 50000  | Alice      |<br>| IT         | David      | 90000  | David      |<br>| IT         | Charlie    | 80000  | David      |<br>+------------+------------+--------+------------+</pre><h3>2. NTH_VALUE() – Nth value in an ordered set</h3><p>Returns the <strong>Nth value</strong> from a partition.<br>The NTH_VALUE() function retrieves the Nth value from a partitioned dataset based on the specified order.</p><h4>SQL Query</h4><pre>SELECT department, employee, salary,<br>       NTH_VALUE(employee, 2)<br> OVER (PARTITION BY department ORDER BY salary DESC) AS nth_emp<br>FROM employees;</pre><h4>Explanation</h4><ul><li>PARTITION BY department divides the dataset into separate groups based on department.</li><li>ORDER BY salary DESC orders the employees in each department by their salary in descending order.</li><li>NTH_VALUE(employee, 2) returns the second highest employee name within each department.</li><li>If there aren’t enough employees in a department, it returns NULL.</li></ul><h4>Output</h4><pre>+------------+------------+--------+---------+<br>| Department | Employee   | Salary | Nth_Emp |<br>+------------+------------+--------+---------+<br>| HR         | Alice      | 60000  | Bob     |<br>| HR         | Bob        | 50000  | NULL    |<br>| IT         | David      | 90000  | Charlie |<br>| IT         | Charlie    | 80000  | NULL    |<br>+------------+------------+--------+---------+</pre><h3>3. LEAD() – Next row’s value</h3><p>Returns the <strong>next row’s value</strong> within the partition.<br>The LEAD() function retrieves the next row’s value within a partitioned dataset.</p><h4>SQL Query</h4><pre>SELECT department, employee, salary,<br>       LEAD(salary) OVER (PARTITION BY department ORDER BY salary DESC) AS next_salary<br>FROM employees;</pre><h4>Explanation</h4><ul><li>PARTITION BY department ensures the function works separately for each department.</li><li>ORDER BY salary DESC sorts employees within each department in descending order of salary.</li><li>LEAD(salary) fetches the salary of the next row (next employee) in the ordered list.</li></ul><h4>Output</h4><pre>+------------+------------+--------+-------------+<br>| Department | Employee   | Salary | Next_Salary |<br>+------------+------------+--------+-------------+<br>| HR         | Alice      | 60000  | 50000       |<br>| HR         | Bob        | 50000  | NULL        |<br>| IT         | David      | 90000  | 80000       |<br>| IT         | Charlie    | 80000  | NULL        |<br>+------------+------------+--------+-------------+</pre><h3>4. LAG() – Previous row’s value</h3><p>Returns the <strong>previous row’s value</strong> within the partition.<br>The LAG() function retrieves the previous row’s value within a partition.</p><h4>SQL Query</h4><pre>SELECT department, employee, salary,<br>       LAG(salary) OVER (PARTITION BY department ORDER BY salary DESC) AS prev_salary<br>FROM employees;</pre><h4>Explanation</h4><ul><li>PARTITION BY department ensures it operates independently within each department.</li><li>ORDER BY salary DESC sorts the employees in each department from highest to lowest salary.</li><li>LAG(salary) retrieves the salary of the previous employee in the ordered list.</li></ul><h4>Output</h4><pre>+------------+------------+--------+-------------+<br>| Department | Employee   | Salary | Prev_Salary |<br>+------------+------------+--------+-------------+<br>| HR         | Alice      | 60000  | NULL        |<br>| HR         | Bob        | 50000  | 60000       |<br>| IT         | David      | 90000  | NULL        |<br>| IT         | Charlie    | 80000  | 90000       |<br>+------------+------------+--------+-------------+</pre><h3>5. AVG() – Moving average</h3><p>Returns the <strong>average salary</strong> within the partition.<br>The AVG() function calculates the average salary for each partition.</p><h4>SQL Query</h4><pre>SELECT department, employee, salary,<br>       AVG(salary) OVER (PARTITION BY department) AS avg_salary<br>FROM employees;</pre><h4>Explanation</h4><ul><li>PARTITION BY department ensures the average salary is computed separately for each department.</li><li>AVG(salary) OVER (...) calculates the average of all salaries within the same department.</li></ul><h4>Output</h4><pre>+------------+------------+--------+-----------+<br>| Department | Employee   | Salary | Avg_Salary |<br>+------------+------------+--------+-----------+<br>| HR         | Alice      | 60000  | 55000     |<br>| HR         | Bob        | 50000  | 55000     |<br>| IT         | David      | 90000  | 85000     |<br>| IT         | Charlie    | 80000  | 85000     |<br>+------------+------------+--------+-----------+</pre><h3>6. PERCENT_RANK() – Relative rank</h3><p>Calculates <strong>percentile rank</strong> of each row.<br>The PERCENT_RANK() function calculates the relative ranking of an employee’s salary within each department.</p><h4>SQL Query</h4><pre>SELECT department, employee, salary,<br>       PERCENT_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS perc_rank<br>FROM employees;</pre><h4>Explanation</h4><ul><li>PARTITION BY department ensures ranking is calculated within each department separately.</li><li>ORDER BY salary DESC sorts salaries in descending order.</li><li>PERCENT_RANK() calculates the percentile rank based on the position of each salary in the sorted list.</li><li>The highest salary in each department has a rank of 0.0, and the lowest has 1.0.</li></ul><h4>Output</h4><pre>+------------+------------+--------+-----------+<br>| Department | Employee   | Salary | Perc_Rank |<br>+------------+------------+--------+-----------+<br>| HR         | Alice      | 60000  | 0.0       |<br>| HR         | Bob        | 50000  | 1.0       |<br>| IT         | David      | 90000  | 0.0       |<br>| IT         | Charlie    | 80000  | 1.0       |<br>+------------+------------+--------+-----------+</pre><h3>7. PERCENTILE_CONT() – Continuous percentile</h3><p>Calculates <strong>continuous percentile value</strong>.</p><p>The PERCENTILE_CONT() function calculates the continuous percentile value within a partition.</p><h4>SQL Query</h4><pre>SELECT department, employee, salary,<br>       PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) OVER (PARTITION BY department) AS median_salary<br>FROM employees;</pre><h4>Explanation</h4><ul><li>PARTITION BY department ensures the calculation is done separately for each department.</li><li>PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) calculates the median salary (50th percentile) within each department.</li><li>If there is an even number of employees, the function interpolates between the two middle values.</li></ul><h4>Output</h4><pre>+------------+------------+--------+--------------+<br>| Department | Employee   | Salary | Median_Salary |<br>+------------+------------+--------+--------------+<br>| HR         | Alice      | 60000  | 55000        |<br>| HR         | Bob        | 50000  | 55000        |<br>| IT         | David      | 90000  | 85000        |<br>| IT         | Charlie    | 80000  | 85000        |<br>+------------+------------+--------+--------------+</pre><h3>Conclusion</h3><p>SQL <strong>window functions</strong> are powerful tools that allow advanced analytics without modifying the structure of query results. By mastering these functions, you can efficiently rank, filter, and analyze data in <strong>real-world SQL queries</strong>.</p><h3>Key Takeaways</h3><p>✅ LEAD() &amp; LAG() are useful for comparing rows.<br> ✅ RANK(), DENSE_RANK(), and ROW_NUMBER() help in ranking.<br> ✅ AVG(), PERCENTILE_CONT(), and PERCENTILE_DISC() help in statistical analysis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce1960ba8d41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dissecting SQL Query]]></title>
            <link>https://lolithasherley7.medium.com/dissecting-sql-query-9bf8fffa3aed?source=rss-56ba65ac9e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bf8fffa3aed</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[count]]></category>
            <category><![CDATA[extract]]></category>
            <category><![CDATA[histograms]]></category>
            <category><![CDATA[tweet]]></category>
            <dc:creator><![CDATA[Lolithasherley]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 18:21:05 GMT</pubDate>
            <atom:updated>2025-03-16T18:21:05.052Z</atom:updated>
            <content:encoded><![CDATA[<p>You are given a table tweets containing Twitter tweet data. Write a SQL query to obtain a histogram of tweets posted per user in 2022. The output should include the number of tweets as a <strong>bucket</strong> and the count of users who fall into that bucket.</p><pre>Step 1: Filter tweets from 2022<br>+---------+--------+------------------------------------------------+------------+<br>| tweet_id| user_id| msg                                            | tweet_date |<br>+---------+--------+------------------------------------------------+------------+<br>|  739252 |    111 | Despite the constant negative press covfefe   | 01/01/2022 |<br>|  846402 |    111 | Following @NickSinghTech on Twitter changed my life! | 02/14/2022 |<br>|  241425 |    254 | If the salary is so competitive why won’t you tell me what it is? | 03/01/2022 |<br>|  231574 |    148 | I no longer have a manager. I can&#39;t be managed | 03/23/2022 |<br>+---------+--------+------------------------------------------------+------------+<br><br>Step 2: Count tweets per user<br>+--------+-------------+<br>| user_id| tweet_count |<br>+--------+-------------+<br>|    111 |          2  |<br>|    254 |          1  |<br>|    148 |          1  |<br>+--------+-------------+<br><br>Step 3: Create histogram (group by tweet count)<br>+-------------+-----------+<br>| tweet_bucket| users_num |<br>+-------------+-----------+<br>|           1 |        2  |<br>|           2 |        1  |<br>+-------------+-----------+<br><br>Step 1: Filter tweets from 2022<br>+---------+--------+------------------------------------------------+------------+<br>| tweet_id| user_id| msg                                            | tweet_date |<br>+---------+--------+------------------------------------------------+------------+<br>|  739252 |    111 | Despite the constant negative press covfefe   | 01/01/2022 |<br>|  846402 |    111 | Following @NickSinghTech on Twitter changed my life! | 02/14/2022 |<br>|  241425 |    254 | If the salary is so competitive why won’t you tell me what it is? | 03/01/2022 |<br>|  231574 |    148 | I no longer have a manager. I can&#39;t be managed | 03/23/2022 |<br>+---------+--------+------------------------------------------------+------------+<br><br>Step 2: Count tweets per user<br>+--------+-------------+<br>| user_id| tweet_count |<br>+--------+-------------+<br>|    111 |          2  |<br>|    254 |          1  |<br>|    148 |          1  |<br>+--------+-------------+<br><br>This means:<br><br>User 111 posted 2 tweets<br>User 254 posted 1 tweet<br>User 148 posted 1 tweet<br><br><br>Step 3: Create histogram (group by tweet count)<br>+-------------+-----------+<br>| tweet_bucket| users_num |<br>+-------------+-----------+<br>|           1 |        2  |<br>|           2 |        1  |<br>+-------------+-----------+</pre><h3>SQL Answer</h3><pre>SELECT tweet_count AS tweet_bucket, COUNT(user_id) AS users_num<br>FROM (<br>    -- Step 1: Count the number of tweets per user in 2022<br>    SELECT user_id, COUNT(*) AS tweet_count<br>    FROM tweets<br>    WHERE EXTRACT(YEAR FROM tweet_date) = 2022<br>    GROUP BY user_id<br>) user_tweet_counts<br>GROUP BY tweet_count<br>ORDER BY tweet_bucket;</pre><h3>Explanation</h3><p>We need to:</p><ol><li><strong>Filter tweets from 2022</strong></li></ol><ul><li>Use EXTRACT(YEAR FROM tweet_date) = 2022 to get tweets posted in 2022.</li></ul><p><strong>2. Count tweets per user</strong></p><ul><li>GROUP BY user_id ensures we count the number of tweets each user posted.</li><li>COUNT(*) AS tweet_count calculates the number of tweets per user.</li></ul><p><strong>3. Create a histogram of tweet counts</strong></p><ul><li>GROUP BY tweet_count groups users based on how many tweets they posted.</li><li>COUNT(user_id) AS users_num counts how many users fall into each tweet count bucket.</li></ul><p><strong>4. Order results by tweet_bucket</strong></p><ul><li>This makes the output easier to read.</li></ul><p>5. First, we need to <strong>count tweets per user</strong>.</p><p>Then, we need to <strong>count how many users fall into each tweet bucket</strong>.</p><p>Since SQL doesn’t allow <strong>two different GROUP BY operations at the same time</strong>, we need a <strong>subquery (inner query)</strong> first and then the <strong>outer query</strong>.</p><h3>Real-World Analogy</h3><p>Imagine a classroom where students take a test and get different scores.</p><ol><li><strong>First step:</strong> Count how many tests each student took.</li></ol><ul><li>“Shinjini took 2 tests, Vineeth took 1 test, Karan took 1 test.”</li></ul><p><strong>2. Second step:</strong> Count how many students fall into each test count.</p><ul><li>“2 students took 1 test, 1 student took 2 tests.”</li></ul><h3>Step-by-Step Execution</h3><pre>Step 1: Filter tweets from 2022<br>+---------+--------+------------------------------------------------+------------+<br>| tweet_id| user_id| msg                                            | tweet_date |<br>+---------+--------+------------------------------------------------+------------+<br>|  739252 |    111 | Despite the constant negative press covfefe   | 01/01/2022 |<br>|  846402 |    111 | Following @NickSinghTech on Twitter changed my life! | 02/14/2022 |<br>|  241425 |    254 | If the salary is so competitive why won’t you tell me what it is? | 03/01/2022 |<br>|  231574 |    148 | I no longer have a manager. I can&#39;t be managed | 03/23/2022 |<br>+---------+--------+------------------------------------------------+------------+<br><br>Step 2: Count tweets per user<br>+--------+-------------+<br>| user_id| tweet_count |<br>+--------+-------------+<br>|    111 |          2  |<br>|    254 |          1  |<br>|    148 |          1  |<br>+--------+-------------+<br><br>Step 3: Create histogram (group by tweet count)<br>+-------------+-----------+<br>| tweet_bucket| users_num |<br>+-------------+-----------+<br>|           1 |        2  |<br>|           2 |        1  |<br>+-------------+-----------+</pre><h3>Key Takeaways</h3><p>✅ <strong>COUNT(*) counts tweets for each user</strong><br> ✅ <strong>GROUP BY user_id groups by each user</strong><br> ✅ <strong>GROUP BY tweet_count forms the histogram</strong><br> ✅ <strong>Output shows how many users tweeted X times in 2022</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bf8fffa3aed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the WITH Clause (Common Table Expression — CTE) in SQL]]></title>
            <link>https://lolithasherley7.medium.com/understanding-the-with-clause-common-table-expression-cte-in-sql-e3ccdd15278c?source=rss-56ba65ac9e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3ccdd15278c</guid>
            <category><![CDATA[sql-queries]]></category>
            <category><![CDATA[with-clause]]></category>
            <category><![CDATA[common-table-expressions]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-optimization]]></category>
            <dc:creator><![CDATA[Lolithasherley]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 17:04:49 GMT</pubDate>
            <atom:updated>2025-03-16T17:04:49.638Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding the WITH Clause (Common Table Expression — CTE) in SQL</h3><h3>Introduction</h3><p>Before diving into writing SQL queries, if you enjoy this content, please consider subscribing to the channel and giving it a thumbs up. Thank you, and let’s begin.</p><p>The <strong>WITH clause</strong>, also known as <strong>Common Table Expression (CTE)</strong> or <strong>Subquery Factoring</strong>, serves as a temporary result set that can be referenced within a query. Throughout this explanation, these terms will be used interchangeably.</p><p>We will explore the <strong>WITH clause</strong> using two queries:</p><ol><li>A simple example using an employee table.</li><li>A more complex example using a sales table.</li></ol><h3>Example 1: Using WITH Clause to Find Employees with Above-Average Salary</h3><h4>Given Employee Table:</h4><pre>+------------+--------------+---------+<br>| EmployeeID | EmployeeName | Salary  |<br>+------------+--------------+---------+<br>| 101        | Alice        | 50,000  |<br>| 102        | Bob          | 60,000  |<br>| 103        | Charlie      | 70,000  |<br>| 104        | David        | 80,000  |<br>| 105        | Emma         | 90,000  |<br>| 106        | Frank        | 40,000  |<br>+------------+--------------+---------+</pre><h4>Requirement:</h4><p>Retrieve employees whose <strong>salary is greater than the average salary</strong> of all employees.</p><h4>Query using WITH Clause:</h4><pre>WITH AverageSalary AS (<br>    SELECT AVG(salary) AS avg_salary FROM employee<br>)<br>SELECT e.*<br>FROM employee e<br>JOIN AverageSalary a ON e.salary &gt; a.avg_salary;</pre><h4>Explanation:</h4><ol><li>The <strong>WITH clause</strong> computes the average salary and stores it in AverageSalary.</li><li>The main query selects employees whose salary is greater than this computed avg_salary.</li><li>The result set filters employees earning above the average salary (65,000 in this case).</li></ol><p><strong>Key Notes:</strong></p><ul><li>The WITH clause acts like a temporary table but is not stored permanently.</li><li>It improves query readability and allows breaking down complex logic into simpler steps.</li></ul><h3>Example 2: Using WITH Clause for Sales Data Analysis</h3><h4>Given Sales Table:</h4><pre>+---------+------------+----------+----------+--------+<br>| StoreID | StoreName  | Product  | Quantity | Cost   |<br>+---------+------------+----------+----------+--------+<br>| 1       | Store A    | iPhone   | 10       | 10,000 |<br>| 1       | Store A    | iPad     | 5        | 5,000  |<br>| 2       | Store B    | MacBook  | 3        | 12,000 |<br>| 2       | Store B    | iPhone   | 8        | 8,000  |<br>| 3       | Store C    | Watch    | 6        | 3,000  |<br>| 3       | Store C    | iPhone   | 7        | 7,000  |<br>| 4       | Store D    | AirPods  | 15       | 4,500  |<br>| 4       | Store D    | iPad     | 10       | 6,000  |<br>+---------+------------+----------+----------+--------+</pre><h4>Requirement:</h4><p>Find stores whose <strong>total sales exceed the average sales across all stores</strong>.</p><h4>Query using WITH Clause:</h4><pre>WITH TotalSales AS (<br>    SELECT store_id, SUM(cost) AS total_sales<br>    FROM sales<br>    GROUP BY store_id<br>),<br>AverageSales AS (<br>    SELECT AVG(total_sales) AS avg_sales FROM TotalSales<br>)<br>SELECT t.store_id, t.total_sales<br>FROM TotalSales t<br>JOIN AverageSales a ON t.total_sales &gt; a.avg_sales;</pre><h4>Explanation:</h4><ol><li>TotalSales: Computes total sales per store.</li><li>AverageSales: Computes the average of these total sales.</li><li>The final query filters and selects stores where total sales exceed the computed average.</li></ol><h3>Why Use the WITH Clause?</h3><ol><li><strong>Enhances Readability</strong>: Queries are structured into logical blocks.</li><li><strong>Avoids Repetition</strong>: Eliminates the need for redundant subqueries.</li><li><strong>Improves Maintainability</strong>: Breaking down complex logic simplifies debugging.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3ccdd15278c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Interview Questions and Answers]]></title>
            <link>https://lolithasherley7.medium.com/sql-interview-questions-and-answers-0a51debd30e7?source=rss-56ba65ac9e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a51debd30e7</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[joins-in-sql]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Lolithasherley]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 09:14:28 GMT</pubDate>
            <atom:updated>2025-03-13T09:14:28.847Z</atom:updated>
            <content:encoded><![CDATA[<h3>📌 Basic SQL Questions</h3><h4>What is SQL, and how does it differ from NoSQL databases?</h4><p>SQL (Structured Query Language) is a standardized language used to manage and manipulate relational databases. It allows users to perform operations like querying, updating, inserting, and deleting data using structured queries.</p><p>NoSQL (Not Only SQL) databases, on the other hand, are designed for flexible, schema-less data storage, often optimized for horizontal scaling. Unlike SQL databases, NoSQL databases use different data models, such as key-value, document, column-family, or graph-based structures.</p><h4>Explain the difference between DDL, DML, DCL, and TCL commands.</h4><ul><li><strong>DDL (Data Definition Language)</strong>: Commands like CREATE, ALTER, DROP, and TRUNCATE are used to define and modify the structure of database objects.</li><li><strong>DML (Data Manipulation Language)</strong>: Commands like INSERT, UPDATE, DELETE, and SELECT are used to manipulate data within tables.</li><li><strong>DCL (Data Control Language)</strong>: Commands like GRANT and REVOKE are used to control access permissions.</li><li><strong>TCL (Transaction Control Language)</strong>: Commands like COMMIT, ROLLBACK, and SAVEPOINT are used to manage transactions within the database.</li></ul><h4>What is the difference between WHERE and HAVING?</h4><ul><li>WHERE is used to filter records <strong>before</strong> any grouping operations.</li><li>HAVING is used to filter grouped data <strong>after</strong> the GROUP BY clause.</li></ul><p>Example:</p><pre>SELECT department, COUNT(*) <br>FROM employees <br>WHERE salary &gt; 50000  -- Applied before grouping<br>GROUP BY department <br>HAVING COUNT(*) &gt; 10;  -- Applied after grouping</pre><h4>How does ORDER BY work, and what is its default sorting order?</h4><p>The ORDER BY clause sorts the query result based on one or more columns. By default, it sorts in <strong>ascending order</strong> (ASC). To sort in descending order, use DESC.</p><p>Example:</p><pre>SELECT name, age FROM users ORDER BY age DESC;</pre><h4>What is the purpose of DISTINCT in SQL queries?</h4><p>The DISTINCT keyword removes duplicate values from the result set.</p><p>Example:</p><pre>SELECT DISTINCT city FROM customers;</pre><h3>🔗 Multi-Table Queries &amp; JOINs</h3><h4>What are the different types of JOINs in SQL?</h4><ol><li><strong>INNER JOIN</strong> — Returns matching rows from both tables.</li><li><strong>LEFT JOIN (LEFT OUTER JOIN)</strong> — Returns all rows from the left table and matching rows from the right.</li><li><strong>RIGHT JOIN (RIGHT OUTER JOIN)</strong> — Returns all rows from the right table and matching rows from the left.</li><li><strong>FULL OUTER JOIN</strong> — Returns all rows when there is a match in either table.</li><li><strong>CROSS JOIN</strong> — Returns the Cartesian product of both tables.</li><li><strong>SELF JOIN</strong> — A table joins with itself.</li></ol><h4>Explain the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN.</h4><ul><li>INNER JOIN: Returns only matching rows.</li><li>LEFT JOIN: Returns all records from the left table and matches from the right table. Missing values are NULL.</li><li>RIGHT JOIN: Returns all records from the right table and matches from the left table. Missing values are NULL.</li><li>FULL OUTER JOIN: Returns all records from both tables, with NULL where there is no match.</li></ul><h4>What is a SELF JOIN, and when would you use it?</h4><p>A <strong>SELF JOIN</strong> is a join where a table is joined with itself. It’s useful for hierarchical data, like employees and managers.</p><p>Example:</p><pre>SELECT e1.name AS Employee, e2.name AS Manager <br>FROM employees e1<br>JOIN employees e2 ON e1.manager_id = e2.id;</pre><h4>How do you use CROSS JOIN? Give an example.</h4><p>A CROSS JOIN returns the Cartesian product of two tables.</p><p>Example:</p><pre>SELECT customers.name, products.product_name <br>FROM customers <br>CROSS JOIN products;</pre><h4>What is the role of ON vs. USING in JOIN conditions?</h4><ul><li><strong>ON</strong>: Used when column names differ between tables.</li><li><strong>USING</strong>: Used when column names are the same in both tables.</li></ul><p>Example:</p><pre>SELECT * FROM employees INNER JOIN departments ON employees.dept_id = departments.dept_id;</pre><p>Using USING:</p><pre>SELECT * FROM employees INNER JOIN departments USING (dept_id);</pre><h3>📊 Aggregation &amp; Grouping</h3><h4>How do GROUP BY and ORDER BY differ?</h4><ul><li>GROUP BY is used for grouping rows and aggregating data.</li><li>ORDER BY sorts the final query output.</li></ul><h4>What is the difference between COUNT(*) and COUNT(column_name)?</h4><ul><li>COUNT(*) counts all rows including NULLs.</li><li>COUNT(column_name) counts only non-NULL values.</li></ul><h4>Can you use WHERE and HAVING in the same query? Explain with an example.</h4><p>Yes, WHERE filters before grouping, HAVING filters after grouping.</p><p>Example:</p><pre>SELECT department, COUNT(*) <br>FROM employees <br>WHERE salary &gt; 50000 <br>GROUP BY department <br>HAVING COUNT(*) &gt; 10;</pre><h4>Explain the concept of ROLLUP and CUBE in SQL.</h4><ul><li>ROLLUP provides hierarchical subtotals.</li><li>CUBE provides all possible aggregations.</li></ul><p>Example:</p><pre>SELECT department, job_role, SUM(salary) <br>FROM employees <br>GROUP BY ROLLUP(department, job_role);</pre><h4>What are GROUPING SETS, and when would you use them?</h4><p>They allow specific groupings instead of full CUBE/ROLLUP.</p><p>Example:</p><pre>SELECT department, job_role, SUM(salary) <br>FROM employees <br>GROUP BY GROUPING SETS ((department), (job_role), (department, job_role));</pre><h3>⚡ Advanced Window Functions (Moving Averages, Ranks, Trends, etc.)</h3><ol><li>What are <strong>window functions</strong> in SQL, and how do they differ from aggregate functions?</li></ol><p>Window functions perform calculations <strong>across a set of rows related to the current row</strong> but do not collapse rows like aggregate functions.</p><p>2. How do you calculate a <strong>moving average</strong> in SQL using <strong>window functions</strong>?</p><pre>SELECT date, sales,<br>       AVG(sales) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS moving_avg<br>FROM sales_data;</pre><p>3. Explain the difference between <strong>RANK(), DENSE_RANK(), and ROW_NUMBER()</strong>.</p><ul><li>RANK(): Skips ranks if there are ties.</li><li>DENSE_RANK(): No gaps in ranking.</li><li>ROW_NUMBER(): Assigns unique row numbers.</li></ul><p>4. What do <strong>LAG()</strong> and <strong>LEAD()</strong> functions do? Provide a practical use case.</p><ul><li>LAG(): Fetches previous row value.</li><li>LEAD(): Fetches next row value.</li></ul><p>Example:</p><pre>SELECT product, sales, LAG(sales) OVER (PARTITION BY product ORDER BY date) AS prev_sales <br>FROM sales_data;</pre><p>5. How do you calculate <strong>cumulative sums (running totals)</strong> using SQL?</p><pre>SELECT date, sales, SUM(sales) OVER (ORDER BY date) AS running_total <br>FROM sales_data;</pre><h3>🛠 Recursive Queries, CTEs &amp; Query Optimization</h3><h4>Q1: What are Common Table Expressions (CTEs), and how do they differ from subqueries?</h4><p>A <strong>Common Table Expression (CTE)</strong> is a temporary result set defined using the WITH clause, which can be referenced within a SQL query. It improves readability, simplifies complex queries, and allows recursion.</p><p>👉 <strong>Example:</strong></p><pre>WITH sales_summary AS (<br>    SELECT product, SUM(sales) AS total_sales<br>    FROM sales_data<br>    GROUP BY product<br>)<br>SELECT * FROM sales_summary WHERE total_sales &gt; 1000;</pre><p>🔹 <strong>Difference from subqueries:</strong></p><ul><li>CTEs can be referenced <strong>multiple times</strong> within a query, while subqueries cannot.</li><li>CTEs improve <strong>query organization and readability</strong>, especially in complex queries.</li><li>Recursive CTEs allow <strong>hierarchical data processing</strong>, unlike subqueries.</li></ul><h4>Q2: How can you create a recursive CTE, and what are its use cases?</h4><p>A <strong>recursive CTE</strong> is a special type of CTE that calls itself until a condition is met. It is commonly used for <strong>hierarchical data</strong>, such as employee hierarchies or organizational structures.</p><p>👉 <strong>Example: Finding an Employee Hierarchy</strong></p><pre>WITH RECURSIVE employee_hierarchy AS (<br>    SELECT id, name, manager_id, 1 AS level<br>    FROM employees<br>    WHERE manager_id IS NULL  -- Start with top-level managers<br>    UNION ALL<br>    SELECT e.id, e.name, e.manager_id, h.level + 1<br>    FROM employees e<br>    INNER JOIN employee_hierarchy h ON e.manager_id = h.id<br>)<br>SELECT * FROM employee_hierarchy;</pre><p>🔹 <strong>Use cases:</strong><br> ✅ Organizational hierarchies<br> ✅ File system directories<br> ✅ Bill of materials (BOM) in manufacturing<br> ✅ Graph-based relationships</p><h4>Q3: What is query optimization, and why is it important?</h4><p>Query optimization is the process of improving SQL query performance by reducing execution time and resource consumption. It is crucial for <strong>scalability, efficiency, and cost reduction</strong> in database operations.</p><p>🔹 <strong>Why is it important?</strong><br> ✅ Improves response time for queries<br> ✅ Reduces CPU and memory usage<br> ✅ Enhances database performance for large datasets</p><h4>Q4: How do indexes work, and what are the different types of indexes in SQL?</h4><p>Indexes speed up database searches by organizing data in a structured manner. They work like the index of a book, allowing for quick lookups.</p><p>🔹 <strong>Types of Indexes:</strong></p><ul><li><strong>B-Tree Index (Default Index)</strong> — Efficient for equality and range queries</li><li><strong>Hash Index</strong> — Fast lookup for exact matches</li><li><strong>Full-Text Index</strong> — Used for searching text documents</li><li><strong>Composite Index</strong> — Index on multiple columns for optimized searches</li><li><strong>Clustered vs. Non-Clustered Index</strong></li><li><strong>Clustered Index</strong>: Sorts and stores the data rows (Only one per table)</li><li><strong>Non-Clustered Index</strong>: Stores pointers to actual data (Multiple allowed)</li></ul><p>👉 <strong>Example:</strong></p><pre>CREATE INDEX idx_product_sales ON sales_data(product, sales);</pre><h4>Q5: How does EXPLAIN ANALYZE help optimize queries?</h4><p>The EXPLAIN ANALYZE statement helps in query debugging by showing the execution plan and performance metrics.</p><p>👉 <strong>Example:</strong></p><pre>EXPLAIN ANALYZE SELECT * FROM sales_data WHERE product = &#39;A&#39;;</pre><p>🔹 <strong>It helps by:</strong><br> ✅ Showing index usage<br> ✅ Identifying slow operations (like full table scans)<br> ✅ Highlighting costly joins</p><h3>Final Takeaways</h3><p>✅ <strong>Indexes speed up SELECT queries</strong> (especially with WHERE conditions).<br> ✅ <strong>EXPLAIN ANALYZE shows if an index is used</strong> for optimization.<br> ✅ <strong>Composite Indexes help with multi-condition queries</strong> (e.g., department + salary).<br> 🚨 <strong>Too many indexes slow down INSERT/UPDATE/DELETE</strong> (since MySQL must update indexes too).</p><h3>🔍 JSON Handling &amp; NoSQL Integration</h3><h4>Q6: How does SQL handle JSON data types, and what functions are available for querying JSON?</h4><p>Modern SQL databases (e.g., PostgreSQL, MySQL) support <strong>JSON data types</strong> for semi-structured data.</p><p>👉 <strong>Querying JSON in PostgreSQL:</strong></p><pre>SELECT data-&gt;&gt;&#39;name&#39; AS name, data-&gt;&#39;address&#39;-&gt;&gt;&#39;city&#39; AS city <br>FROM customers;</pre><p>🔹 <strong>Common JSON functions:</strong></p><ul><li>-&gt; Extracts JSON object</li><li>-&gt;&gt; Extracts JSON text</li><li>jsonb_each() Expands JSON into key-value pairs</li></ul><h4>Q7: What is JSONB in PostgreSQL, and how is it different from JSON?</h4><p><strong>JSONB</strong> is a <strong>binary</strong> format for JSON that allows indexing and faster querying.</p><ul><li>JSON is stored <strong>as text</strong> (slower for searching).</li><li>JSONB is <strong>indexed and optimized</strong> for querying.</li></ul><p>👉 <strong>Example:</strong></p><pre>CREATE TABLE orders (<br>    id SERIAL PRIMARY KEY,<br>    details JSONB<br>);</pre><h4>Q8: How do you extract a specific key-value pair from a JSON column in SQL?</h4><pre>SELECT details-&gt;&gt;&#39;product_name&#39; AS product, details-&gt;&#39;price&#39; AS price<br>FROM orders;</pre><p>This extracts product_name and price from the details JSON column.</p><h3>🌍 Geospatial Queries (EV Charging Stations &amp; GPS Data)</h3><h4>Q9: How do you find the nearest EV charging station using SQL geospatial functions?</h4><p>Using <strong>PostGIS</strong>, you can query for the <strong>nearest charging station</strong>.</p><p>👉 <strong>Example:</strong></p><pre>SELECT name, location<br>FROM ev_stations<br>ORDER BY ST_Distance(location, ST_GeomFromText(&#39;POINT(12.9716 77.5946)&#39;, 4326))<br>LIMIT 1;</pre><p>Here, ST_Distance() calculates the nearest charging station to a given point.</p><h4>Q10: What are PostGIS and its key spatial functions for location-based queries?</h4><p><strong>PostGIS</strong> is a PostgreSQL extension that enables geospatial queries.</p><p>🔹 <strong>Key Functions:</strong></p><ul><li>ST_Distance() – Computes distance between points</li><li>ST_Within() – Checks if a point is inside a boundary</li><li>ST_Contains() – Checks if one geometry contains another</li></ul><h4>Q11: How can you calculate the distance between two latitude-longitude points in SQL?</h4><p>Using the <strong>Haversine formula</strong> in SQL:</p><pre>SELECT ST_DistanceSphere(<br>    ST_MakePoint(-122.4194, 37.7749), <br>    ST_MakePoint(-73.9857, 40.7488)<br>) AS distance_meters;</pre><p>This calculates the <strong>distance between San Francisco and New York</strong>.</p><h3>🚗 EV Fleet Management &amp; Analytics</h3><h4>Q12: How can SQL be used to analyze battery degradation trends over time?</h4><p>By tracking battery health over time using <strong>window functions</strong>:</p><pre>SELECT vehicle_id, date, battery_health, <br>       LAG(battery_health) OVER (PARTITION BY vehicle_id ORDER BY date) AS prev_health,<br>       battery_health - LAG(battery_health) OVER (PARTITION BY vehicle_id ORDER BY date) AS health_drop<br>FROM fleet_data;</pre><p>This calculates <strong>battery degradation per day</strong>.</p><h4>Q13: What SQL queries would help analyze EV charging station utilization?</h4><pre>SELECT station_id, COUNT(*) AS total_sessions, AVG(duration) AS avg_duration<br>FROM charging_sessions<br>GROUP BY station_id;</pre><p>This query gives the <strong>total charging sessions and average charging time</strong> per station.</p><h4>Q14: How do you track vehicle movement using GPS data in an SQL database?</h4><pre>SELECT vehicle_id, ST_AsText(location) AS last_known_location<br>FROM vehicle_tracking<br>WHERE timestamp = (SELECT MAX(timestamp) FROM vehicle_tracking);</pre><p>This fetches the <strong>latest location of each vehicle</strong>.</p><h4>Q15: What is an anomaly detection query for spotting irregular charging behaviors?</h4><pre>SELECT user_id, COUNT(*) AS charge_count<br>FROM charging_sessions<br>WHERE duration &gt; (SELECT AVG(duration) * 1.5 FROM charging_sessions)<br>GROUP BY user_id;</pre><p>This detects <strong>users who charge for significantly longer durations</strong> than average.</p><p>✅ Conclusion</p><p>These SQL queries and concepts help with <strong>data analysis, optimization, JSON handling, and geospatial queries</strong> for real-world use cases like <strong>EV management</strong> and <strong>fleet tracking</strong>. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a51debd30e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Query Order of Execution]]></title>
            <link>https://lolithasherley7.medium.com/sql-query-order-of-execution-a99cb774c080?source=rss-56ba65ac9e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/a99cb774c080</guid>
            <category><![CDATA[sql-queries]]></category>
            <category><![CDATA[database-management]]></category>
            <category><![CDATA[sql-optimization]]></category>
            <category><![CDATA[sql-execution-order]]></category>
            <category><![CDATA[learn-sql]]></category>
            <dc:creator><![CDATA[Lolithasherley]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 12:47:13 GMT</pubDate>
            <atom:updated>2025-03-07T12:47:13.250Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding the order in which SQL executes different parts of a SELECT query is crucial for writing efficient and correct queries. Below is the execution order:</p><ol><li><strong>FROM &amp; JOIN</strong></li></ol><ul><li>The process begins by identifying the dataset to be used.</li><li>If there are multiple tables, joins are executed to form a combined dataset.</li><li>Subqueries in the FROM clause are executed at this stage.</li></ul><p><strong>2. WHERE</strong></p><ul><li>Filters are applied to remove rows that do not meet the given conditions.</li><li>Only columns from the tables in the FROM clause can be used (aliases from SELECT are not available).</li></ul><p><strong>3. GROUP BY</strong></p><ul><li>Remaining rows are grouped based on the specified column(s).</li><li>Aggregations (e.g., SUM, COUNT, AVG) work on these grouped rows.</li></ul><p><strong>4. HAVING</strong></p><ul><li>Works like WHERE, but applies filters to grouped data.</li><li>Only used when GROUP BY is present.</li></ul><p><strong>5. SELECT</strong></p><ul><li>Determines which columns or calculated expressions appear in the final result.</li><li>Aliases assigned in this clause become available for reference.</li></ul><p><strong>6. DISTINCT</strong></p><ul><li>Eliminates duplicate rows, ensuring only unique records remain.</li></ul><p><strong>7. ORDER BY</strong></p><ul><li>Sorts the result based on the specified columns, either in ascending (ASC) or descending (DESC) order.</li></ul><p><strong>8. LIMIT / OFFSET</strong></p><ul><li>Limits the number of rows returned (LIMIT).</li><li>Skips a certain number of rows before returning results (OFFSET).</li></ul><h3>1️⃣How to Easily Remember the Order of Execution?</h3><p>You can use this <strong>mnemonic</strong>:<br><strong>“From Where Groups Have Selected Distinct Ordered Limits”</strong></p><h3>2️⃣ Acronym-Based Memory Trick</h3><p>Use this phrase to remember the order:<br>🔹 <strong>“Fine Wine Gets High Sales, Delivering Outstanding Liquor”</strong></p><h3>1️⃣ Story-Based Memory Trick (Visual &amp; Fun!)</h3><p>Think of it as <strong>a chef preparing a dish in a restaurant</strong>🍽️:</p><ol><li><strong>FROM &amp; JOIN</strong> → 🛒 <strong>Start by gathering ingredients</strong> (Get tables and join them)</li><li><strong>WHERE</strong> → 🚮 <strong>Remove bad ingredients</strong> (Filter out unnecessary rows)</li><li><strong>GROUP BY</strong> → 🍱 <strong>Sort ingredients into groups</strong> (Group data together)</li><li><strong>HAVING</strong> → 🔍 <strong>Check if groups are valid</strong> (Apply additional filters to groups)</li><li><strong>SELECT</strong> → 🍽️ <strong>Choose what to serve on the plate</strong> (Pick the required columns)</li><li><strong>DISTINCT</strong> → 🚫 <strong>Make sure no duplicate dishes</strong> (Remove duplicates)</li><li><strong>ORDER BY</strong> → 📏 <strong>Arrange dishes neatly</strong> (Sort the output)</li><li><strong>LIMIT/OFFSET</strong> → 🚪 <strong>Serve only a limited number of customers</strong> (Restrict results)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a99cb774c080" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Technical Questions and Answers- Vol 1]]></title>
            <link>https://lolithasherley7.medium.com/technical-questions-and-answers-vol-1-b368e70f85ab?source=rss-56ba65ac9e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/b368e70f85ab</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-lake]]></category>
            <dc:creator><![CDATA[Lolithasherley]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 18:11:18 GMT</pubDate>
            <atom:updated>2025-03-04T18:11:18.906Z</atom:updated>
            <content:encoded><![CDATA[<h4>1. What is the difference between a Delta Lake and a Data Lake?</h4><ul><li><strong>Data Lake:</strong> A central storage repository that holds raw data in its original format.</li><li><strong>Delta Lake:</strong> An enhanced version of a Data Lake with added capabilities like:</li><li>ACID transactions</li><li>Schema enforcement</li><li>Time travel (versioning of data)</li><li>Better performance due to indexing and caching</li><li>Support for incremental data processing</li></ul><h4>2. How do you process data from an Excel sheet in your ETL pipeline?</h4><ul><li>Extract data from the Excel sheet (CSV format).</li><li>Store raw data in the <strong>Bronze Layer</strong>.</li><li>Clean the data and apply transformations to create the <strong>Silver Layer</strong>.</li><li>Further processing and aggregation take place before moving to the <strong>Gold Layer</strong>, which is used for business intelligence and reporting.</li><li>Different access permissions are applied at each layer using <strong>Azure Key Vault</strong>.</li></ul><h4>3. What are some key features of Unity Catalog in Databricks?</h4><ul><li><strong>Data Governance</strong>: Centralized control over permissions, policies, and access control.</li><li><strong>Storage Management</strong>: Supports <strong>cold storage</strong> for historical data and enables cost optimization.</li><li><strong>Data Lineage</strong>: Tracks data movement from source to destination, aiding in debugging pipeline failures.</li></ul><h4>4. What are the advantages of Parquet over CSV and other file formats?</h4><ul><li><strong>Columnar Storage:</strong> Allows efficient querying by scanning only the required columns.</li><li><strong>Compression:</strong> Parquet uses efficient compression, reducing storage costs.</li><li><strong>Predicate Pushdown:</strong> Enables filtering early in the data pipeline, improving query performance.</li></ul><h4>5. What is Predicate Pushdown?</h4><ul><li>A technique where filters (WHERE clauses) are applied at the <strong>storage level</strong> before loading data into memory.</li><li>Reduces I/O operations and speeds up query execution.</li></ul><h4>6. Which is better: DataFrame or Dataset?</h4><p><strong>DataFrames:</strong></p><ul><li>Optimized for performance.</li><li>Uses Spark’s Catalyst optimizer for query execution.</li><li>No compile-time type safety (errors detected at runtime).</li></ul><p><strong>Datasets:</strong></p><ul><li>Provides compile-time type safety.</li><li>Best suited for Scala and Java.</li><li><strong>Preferred Choice:</strong> DataFrames in <strong>Python</strong>, as Python does not support typed Datasets.</li></ul><h4>7. What is Compile-time Safety vs. Runtime Type Safety?</h4><ul><li><strong>Compile-time Safety:</strong> Errors are detected <strong>before</strong> execution. Example: Scala.</li><li><strong>Runtime Type Safety:</strong> Errors appear <strong>after</strong> running the code. Example: Python.</li></ul><h4>8. What is Lazy Evaluation in Spark?</h4><p><strong>Lazy Evaluation:<br></strong>Transformations are <strong>not executed immediately</strong>.<br>They are stored as a <strong>logical plan</strong> and executed only when an action (e.g., .show(), .collect()) is triggered.</p><p><strong>Benefits:</strong></p><ul><li>Optimizes execution using <strong>Catalyst Optimizer</strong>.</li><li>Reduces redundant computations.</li><li><strong>Partitioning in SQL:</strong></li></ul><p><strong>9. How are partitions created?</strong></p><ul><li>Partitions can be created based on user-defined criteria.</li><li>If no criteria are provided, SQL uses <strong>hash partitioning</strong>, distributing data based on hash values.</li><li>DevOps teams usually configure partitioning parameters in enterprise settings.</li></ul><p><strong>10. Reducing the number of partitions:</strong></p><ul><li><strong>coalesce()</strong>: Reduces the number of partitions without shuffling data. Efficient for reducing partitions.</li><li><strong>repartition()</strong>: Increases or decreases partitions but involves a full shuffle of data. More resource-intensive than coalesce().</li></ul><p><strong>11. What is the diference between Deep Copy vs. Shallow Copy in Python:</strong></p><ul><li><strong>Shallow Copy:</strong> Creates a new object but inserts references to the original objects instead of copying them.</li><li><strong>Deep Copy:</strong> Creates a completely independent copy of an object and all nested objects.</li></ul><p>Example:</p><ul><li>import copy original = [[1, 2], [3, 4]] shallow = copy.copy(original) deep = copy.deepcopy(original) shallow[0][0] = 99 # Affects original list deep[0][0] = 42 # Does not affect original list</li></ul><p><strong>12. What is the difference between Pandas Series vs. DataFrame:</strong></p><ul><li><strong>Series</strong>: A one-dimensional labeled array (like a single column in a table).</li><li><strong>DataFrame</strong>: A two-dimensional labeled data structure (like a table with rows and columns).</li></ul><p><strong>13. Python Coding Question:</strong> <em>Write a function that checks if both words in a two-word string start with the same letter.</em></p><pre>def same_starting_letter(s):<br>    words = s.split()<br>    return words[0][0].lower() == words[1][0].lower() if len(words) == 2 else False</pre><pre># Test cases<br>print(same_starting_letter(&quot;Crazy Chocolate&quot;))  # True<br>print(same_starting_letter(&quot;Lazy Dog&quot;))  # False</pre><p><strong>13. Handling NULL values in SQL:</strong></p><ul><li><strong>NULL cannot be compared using </strong><strong>= or </strong><strong>!=.</strong></li></ul><p>Use IS NULL or IS NOT NULL instead.</p><p>Example:SELECT * FROM employees WHERE salary IS NULL;</p><p><strong>14. Difference between RANK, DENSE_RANK, and ROW_NUMBER:</strong></p><pre>+----+-------+--------+--------+--------------+-------------+<br>| ID | Name  | Salary | RANK() | DENSE_RANK() | ROW_NUMBER() |<br>+----+-------+--------+--------+--------------+-------------+<br>|  1 | Alice |  6000  |   1    |      1       |      1      |<br>|  2 | Bob   |  5000  |   2    |      2       |      2      |<br>|  3 | Carol |  5000  |   2    |      2       |      3      |<br>|  4 | Dave  |  4000  |   4    |      3       |      4      |<br>+----+-------+--------+--------+--------------+-------------+</pre><ul><li><strong>RANK()</strong>: Assigns the same rank to duplicate values but skips the next rank.</li><li><strong>DENSE_RANK()</strong>: Assigns the same rank to duplicate values but does not skip ranks.</li><li><strong>ROW_NUMBER()</strong>: Assigns a unique row number regardless of duplicates.</li></ul><p>SQL Query Example:</p><ul><li>SELECT Name, Salary, RANK() OVER (ORDER BY Salary DESC) AS Rank, DENSE_RANK() OVER (ORDER BY Salary DESC) AS DenseRank, ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNum FROM employees;</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b368e70f85ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Analyst Interview Questions]]></title>
            <link>https://lolithasherley7.medium.com/data-analyst-interview-questions-9155def8c343?source=rss-56ba65ac9e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/9155def8c343</guid>
            <category><![CDATA[ｐｙｔｈｏｎ]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Lolithasherley]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 10:17:30 GMT</pubDate>
            <atom:updated>2025-02-28T10:17:30.639Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Explain *args and **kwargs</h3><h3>*args (Non-keyword arguments):</h3><ul><li>*args allows you to pass a <strong>variable number of non-keyword arguments</strong> to a function.</li><li>Inside the function, args is treated as a <strong>tuple</strong>.</li></ul><h4>Example:</h4><pre>def example_function(*args):<br>    for arg in args:<br>        print(arg)</pre><pre>example_function(1, 2, 3, 4)</pre><h4>Output:</h4><pre>1<br>2<br>3<br>4</pre><p>Explanation:</p><ul><li>You can pass any number of arguments to the function.</li><li>Inside the function, args becomes a tuple containing all the passed arguments: (1, 2, 3, 4).</li></ul><h3>2. **kwargs (Keyword arguments):</h3><ul><li>**kwargs allows you to pass a <strong>variable number of keyword arguments</strong> to a function.</li><li>Inside the function, kwargs is treated as a <strong>dictionary</strong>.</li></ul><h4>Example:</h4><pre>def example_function(**kwargs):<br>    for key, value in kwargs.items():<br>        print(f&quot;{key}: {value}&quot;)</pre><pre>example_function(name=&quot;John&quot;, age=30, city=&quot;New York&quot;)</pre><h4>Output:</h4><pre>name: John<br>age: 30<br>city: New York</pre><p>Explanation:</p><ul><li>You can pass any number of keyword arguments (in the form of key-value pairs).</li><li>Inside the function, kwargs becomes a dictionary: {&#39;name&#39;: &#39;John&#39;, &#39;age&#39;: 30, &#39;city&#39;: &#39;New York&#39;}.</li></ul><h3>2. OLAP and OLTP which is normalised and denormalised?</h3><h3>OLTP (Online Transaction Processing):</h3><ul><li><strong>Normalization</strong>: OLTP systems are typically <strong>normalized</strong>.</li><li><strong>Purpose</strong>: OLTP systems are used for day-to-day transaction processing (e.g., banking transactions, retail sales).</li><li><strong>Normalization</strong> is applied to reduce redundancy and avoid data anomalies, ensuring efficient, fast updates and inserts.</li><li><strong>Example of Normalization</strong>:<br>In an OLTP system, instead of storing the full customer information with each order, you might store a CustomerID in the order table and store customer details in a separate Customers table. This ensures that customer information is not duplicated with every order.</li><li><strong>Typical Use Cases</strong>: Retail systems, banking systems, e-commerce platforms, etc.</li></ul><p><strong>Characteristics</strong>:</p><ul><li>Handles high volume of small, individual transactions.</li><li>Requires fast query processing (especially for inserts, updates, and deletes).</li><li>Data is frequently updated.</li></ul><h3>OLAP (Online Analytical Processing):</h3><ul><li><strong>Denormalization</strong>: OLAP systems are typically <strong>denormalized</strong>.</li><li><strong>Purpose</strong>: OLAP systems are used for reporting, analysis, and decision-making (e.g., data warehousing, business intelligence).</li><li><strong>Denormalization</strong> is used to improve the speed of read operations (queries), making it easier to aggregate large datasets quickly without the need to join multiple tables.</li><li><strong>Example of Denormalization</strong>:<br>In an OLAP system, the Orders table might include customer details, product details, and sales information all in one large table, making it easier to run complex queries for reports.</li><li><strong>Typical Use Cases</strong>: Data warehouses, reporting systems, business intelligence tools.</li></ul><p><strong>Characteristics</strong>:</p><ul><li>Handles large volumes of data.</li><li>Optimized for complex, multi-dimensional queries.</li><li>Focuses on fast query performance for analytical tasks.</li><li>Data is often aggregated and historical.</li></ul><h3>3. What is the difference between CTE and Subquery?</h3><pre>+---------------------+---------------------------------------------+--------------------------------------------------+<br>|       Aspect        |                 Subquery                    |             CTE (Common Table Expression)         |<br>+---------------------+---------------------------------------------+--------------------------------------------------+<br>| Definition          | Inline query within another query.          | Named temporary result set, declared with WITH.   |<br>+---------------------+---------------------------------------------+--------------------------------------------------+<br>| Reusability         | Non-reusable; defined once and used inline. | Reusable within the same query multiple times.    |<br>+---------------------+---------------------------------------------+--------------------------------------------------+<br>| Readability         | Can become hard to read in complex queries. | Improves readability by breaking down queries.    |<br>+---------------------+---------------------------------------------+--------------------------------------------------+<br>| Performance         | May lead to performance issues if nested    | Typically more efficient in terms of readability  |<br>|                     | too deeply or if correlated.                | and debugging, but performance depends on         |<br>|                     |                                             | query optimization.                               |<br>+---------------------+---------------------------------------------+--------------------------------------------------+<br>| Recursion           | Cannot perform recursive operations.        | Supports recursion, useful for hierarchical data. |<br>+---------------------+---------------------------------------------+--------------------------------------------------+<br>| Usage Scope         | Can be used in SELECT, FROM, WHERE, etc.    | Primarily used in SELECT, INSERT, UPDATE, and     |<br>|                     |                                             | DELETE statements.                                |<br>+---------------------+---------------------------------------------+--------------------------------------------------+<br>| Lifetime            | Exists only for the duration of the         | Exists for the duration of the query and can be   |<br>|                     | specific part of the query.                 | referenced multiple times.                        |<br>+---------------------+---------------------------------------------+--------------------------------------------------+</pre><h3><strong>4. Fetch employee names and their manager names</strong></h3><pre>+-------------+------------+---------------+<br>| employee_id | manager_id | employee_name |<br>+-------------+------------+---------------+<br>|      1      |    NULL    |   John Doe    |<br>|      2      |      1     |  Jane Smith   |<br>|      3      |      1     | Robert Brown  |<br>|      4      |      2     |  Emily Davis  |<br>+-------------+------------+---------------+</pre><pre>SELECT e.employee_name AS Employee, m.employee_name AS Manager<br>FROM employees e<br>LEFT JOIN employees m ON e.manager_id = m.employee_id;</pre><h3>5. What’s the difference between pandas ans spark?</h3><pre>+-----------------+---------------------------------------------------------------+--------------------------------------------------------------------------+<br>| Feature         | Pandas                                                        | Apache Spark                                                             |<br>+-----------------+---------------------------------------------------------------+--------------------------------------------------------------------------+<br>| Definition      | A Python library for data manipulation and analysis.          | A distributed computing system for big data processing.                  |<br>| Data Processing | In-memory processing; suitable for small to medium datasets   | Out-of-core processing; designed for large datasets that do not fit      |<br>|                 | that fit in memory.                                           | in memory.                                                               |<br>| Speed           | Fast for small datasets due to in-memory operations.          | Optimized for speed on large datasets using distributed processing.      |<br>| Scalability     | Limited scalability; not suitable for distributed computing.  | Highly scalable; can handle petabytes of data across clusters.           |<br>| Data Structures | Uses DataFrames for data manipulation.                        | Uses Resilient Distributed Datasets (RDDs) and DataFrames for            |<br>|                 |                                                               | data processing.                                                         |<br>| API Language    | Python; primarily designed for Python users.                  | Supports multiple languages, including Scala, Java, Python, and R.       |<br>| Use Cases       | Data cleaning, manipulation, and exploratory data analysis.   | ETL processes, real-time data processing, machine learning at scale.     |<br>| Performance     | Performance may degrade with larger datasets due to           | Performs well with large datasets and can leverage cluster resources     |<br>|                 | memory constraints.                                           | for better performance.                                                  |<br>| Ecosystem       | Part of the broader Python data science ecosystem,            | Part of the larger Apache Hadoop ecosystem; integrates with Hive, HDFS,  |<br>|                 | including libraries like NumPy and Matplotlib.                | and various data storage solutions.                                      |<br>| Ease of Use     | Intuitive API; simpler to use for Python users.               | More complex due to distributed computing concepts; requires             |<br>|                 |                                                               | understanding of cluster management.                                     |<br>| Installation    | Easy to install via pip or conda.                             | Requires more setup; can run on local machines or clusters               |<br>|                 |                                                               | (YARN, Mesos, Kubernetes).                                               |<br>| Concurrency     | Limited to single-threaded processing; can use multiprocessing| Supports parallel processing across nodes in a cluster.                  |<br>+-----------------+---------------------------------------------------------------+--------------------------------------------------------------------------+<br>| Summary         | Pandas is excellent for data manipulation, analysis, and      | Apache Spark is suited for large-scale data processing and analytics in  |<br>|                 | visualization for datasets that fit into memory and is easier | a distributed environment, making it ideal for big data applications.    |<br>|                 | to use for quick data tasks.                                  |                                                                          |<br>+-----------------+---------------------------------------------------------------+--------------------------------------------------------------------------+</pre><h3>6. Using Python for input “a4b3c2” get the output aaaabbbcc</h3><pre>input_str = &#39;a4b3c2&#39;<br><br># Step 1: Create an output string based on the input<br>output = &quot;&quot;<br><br>for i in range(0, len(input_str), 2):<br>    char = input_str[i]          # Get the character<br>    num = int(input_str[i + 1])  # Get the corresponding number<br>    output += char * num         # Repeat the character according to the number<br><br>print(&quot;Output:&quot;, output)  # Output should be: aaaabbbcc</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9155def8c343" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Quality and Data Governance]]></title>
            <link>https://lolithasherley7.medium.com/data-quality-and-data-governance-1ff10197dd81?source=rss-56ba65ac9e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ff10197dd81</guid>
            <category><![CDATA[data-quality-metrics]]></category>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[data-validation]]></category>
            <category><![CDATA[data-quality-intergrity]]></category>
            <category><![CDATA[data-quality-dimensions]]></category>
            <dc:creator><![CDATA[Lolithasherley]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 10:14:10 GMT</pubDate>
            <atom:updated>2025-02-28T10:14:10.902Z</atom:updated>
            <content:encoded><![CDATA[<h4>1. Introduction to Data Quality</h4><ul><li><strong>Definition</strong>: Data Quality refers to the accuracy, completeness, validity, consistency, and reliability of data.</li><li><strong>Importance</strong>:</li><li>Ensures data is usable for decision-making.</li><li>Critical for business operations, reporting, and analytics.</li><li>Poor data quality can lead to business problems and incorrect decisions.</li></ul><h4>2. Key Concepts of Data Quality</h4><ul><li><strong>Accuracy</strong>: Ensures data correctly represents the real-world scenario it models.</li><li><strong>Completeness</strong>: All required data is present (e.g., no missing fields).</li><li><strong>Validity</strong>: Data conforms to defined formats (e.g., Aadhaar number as digits, PAN card as alphanumeric).</li><li><strong>Consistency</strong>: Data should be consistent across different data sources.</li><li><strong>Uniqueness</strong>: Each data record should be unique (no duplicates).</li><li><strong>Timeliness</strong>: Data should be up-to-date and available when needed.</li><li><strong>Fitness for Purpose</strong>: Data should be relevant and useful for specific business needs.</li></ul><h4>3. Data Quality Lifecycle</h4><ul><li>Data Quality follows a lifecycle, including data collection, validation, processing, and reporting.</li><li>Emphasizes the continuous improvement of data through regular checks and updates.</li></ul><h4>4. Data Quality Dimensions</h4><ul><li>Different dimensions ensure data quality beyond just accuracy and completeness:</li><li><strong>Validity</strong>: Checking if data follows the defined format (e.g., Aadhaar as numeric).</li><li><strong>Consistency</strong>: Ensuring data consistency across multiple systems.</li><li><strong>Timeliness</strong>: Verifying data is available within a required timeframe.</li><li><strong>Uniqueness</strong>: Ensuring no duplicate records exist in the dataset.</li></ul><h4>5. Data Quality Metrics &amp; KPIs</h4><ul><li>Metrics are essential for measuring data quality and ensuring standards are met.</li><li><strong>Examples</strong>: Data Accuracy Rate, Completeness Percentage, Validation Error Rate.</li></ul><h4>6. Data Validation</h4><ul><li>Closely tied to data quality, it ensures data integrity by validating data against predefined rules.</li><li><strong>Types of Data Validation</strong>:</li><li>Format validation (e.g., Aadhaar number as digits, PAN card as alphanumeric).</li><li>Completeness checks (e.g., all users should have both Aadhaar and PAN card).</li><li>Uniqueness checks (e.g., each user has a unique Aadhaar and PAN number).</li></ul><h4>7. Best Practices for Ensuring Data Quality</h4><ul><li>Use custom scripts (e.g., Python scripts) to automate data quality checks.</li><li>Implement data quality checks throughout the data pipeline, from extraction to processing.</li><li>Leverage Python libraries or tools like AWS Glue DataBrew for automated data validation and cleaning.</li></ul><h4>8. Real-World Example: Aadhaar and PAN Card Validation</h4><ul><li><strong>Data Completeness</strong>: Ensure every user record has Aadhaar and PAN card details.</li><li><strong>Data Validity</strong>:</li><li>Aadhaar should be a numeric value.</li><li>PAN card should follow a 10-character alphanumeric pattern.</li><li><strong>Data Uniqueness</strong>: Each user must have a unique Aadhaar and PAN number.</li></ul><h4>9. Overview of Data Governance</h4><ul><li><strong>Definition</strong>: A set of predefined rules and policies for data management within an organization.</li><li><strong>Key Areas</strong>:</li><li><strong>Access Control</strong>: Defining who can access data.</li><li><strong>Data Sensitivity Tagging</strong>: Marking sensitive data like personal identification details.</li><li><strong>Data Classification</strong>: Organizing data based on its type, sensitivity, and use.</li></ul><p>These structured notes can help provide a comprehensive overview of data quality and its importance in data management and governance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*D4xkY3fUuTzAX4NiUu8VjA.png" /></figure><h3>Data Quality Lifecycle Overview</h3><p>The <strong>Data Quality Lifecycle</strong> is a structured approach to managing the quality of data across its entire lifespan. This process helps organizations ensure their data is accurate, complete, and reliable for decision-making and reporting. Below are the key stages of the data quality lifecycle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*G44qX9OepD2E3HIf5ScUcg.png" /></figure><ol><li><strong>Identification</strong>:</li></ol><ul><li>Identify where data quality issues may occur.</li><li>Pinpoint specific problem areas that need attention.</li></ul><p><strong>2. Prioritization</strong>:</p><ul><li>Prioritize data quality issues based on their impact on business processes.</li><li>Focus on the most critical areas to address first.</li></ul><p><strong>3. Analysis</strong>:</p><ul><li>Perform data profiling to understand the current state of data.</li><li>Examine patterns, outliers, and anomalies.</li><li>Create rules to detect and resolve quality issues.</li></ul><p><strong>4. Improvement</strong>:</p><ul><li>Enhance existing algorithms and validation rules.</li><li>Implement corrections based on analysis to improve data quality.</li></ul><p><strong>5. Control</strong>:</p><ul><li>Monitor data quality continuously.</li><li>Ensure adherence to established standards and controls.</li><li>Use scorecards and dashboards to report data quality metrics.</li></ul><p><strong>Summary</strong>:</p><ul><li>The data quality lifecycle involves <strong>Discovery</strong>, <strong>Profiling</strong>, <strong>Rule Creation</strong>, <strong>Improvement</strong>, and <strong>Control</strong>.</li><li>Data quality processes need to be planned, executed, monitored, and refined.</li></ul><h3>Data Quality Dimensions</h3><p>Data quality is evaluated based on several dimensions, each targeting a specific aspect of data reliability. These dimensions may vary depending on the data source and its use case. The six core dimensions are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*etHdiRPBM3gWfjg3mKrYpA.png" /></figure><ol><li><strong>Accuracy</strong>:</li></ol><ul><li>Measures how close data is to the true or accepted value.</li><li>Ensures that data represents the correct source of truth.</li><li>Example: Ensuring that country codes (e.g., “IND” for India) are consistently mapped and not mixed with full names like “India.”</li></ul><p><strong>2. Completeness</strong>:</p><ul><li>Indicates whether all required data is available.</li><li>High levels of missing or null data can skew analyses and lead to incorrect conclusions.</li><li>Example: Ensuring that no mandatory fields are left empty in customer records.</li></ul><p><strong>3. Uniqueness</strong>:</p><ul><li>Ensures that data records are not duplicated.</li><li>Particularly important for identifiers like IDs or key attributes that should be unique.</li><li>Example: Ensuring no duplicate customer IDs exist in the database.</li></ul><p><strong>4. Validity</strong>:</p><ul><li>Checks if data conforms to predefined formats and standards.</li><li>Validates data types, ranges, and patterns to ensure consistency.</li><li>Example: Ensuring dates follow a standard format like “YYYY-MM-DD.”</li></ul><p><strong>5. Timeliness</strong>:</p><ul><li>Measures whether data is available within the required timeframe.</li><li>Ensures data is up-to-date and ready for use when needed.</li><li>Example: Order confirmation emails should be sent immediately after purchase, not days later.</li></ul><p><strong>6. Consistency</strong>:</p><ul><li>Ensures uniformity of data across different sources and systems.</li><li>Checks that data attributes are harmonized and follow the same format.</li><li>Example: Date fields should have a consistent format across all data sources (e.g., “2022–01–10” vs. “10/01/2022”).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*BMBnvyMaahUAq0O0pGj3vQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*0OzbkMXd2ZwwPDYPvyr-Hw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*mEzv0JMJAwFc1zJO6Azofw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*BLFtX1Xykl4JgPtpAqx82w.png" /></figure><p>#dataquality#dataQualityDimension#dataqualityIntergrity</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ff10197dd81" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>