<?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 Kuldeep Trivedi on Medium]]></title>
        <description><![CDATA[Stories by Kuldeep Trivedi on Medium]]></description>
        <link>https://medium.com/@kuldeepkr16?source=rss-ddfef8ceeb54------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bcfeNV_S3uiZFTt0</url>
            <title>Stories by Kuldeep Trivedi on Medium</title>
            <link>https://medium.com/@kuldeepkr16?source=rss-ddfef8ceeb54------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:53:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kuldeepkr16/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[Building a Config-Driven Real-Time CDP on AWS]]></title>
            <link>https://kuldeepkr16.medium.com/building-a-config-driven-customer-data-platform-sync-pipeline-on-aws-f030593d4c0d?source=rss-ddfef8ceeb54------2</link>
            <guid isPermaLink="false">https://medium.com/p/f030593d4c0d</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <dc:creator><![CDATA[Kuldeep Trivedi]]></dc:creator>
            <pubDate>Thu, 11 Jun 2026 17:35:10 GMT</pubDate>
            <atom:updated>2026-06-14T07:26:34.584Z</atom:updated>
            <content:encoded><![CDATA[<p>When building data pipelines for analytics or dashboarding, batch processing is usually sufficient. A few minutes or even a few hours of data delay is often acceptable, as long as users can see and understand the expected lag. However, not every use case has that luxury. When downstream systems require data to be updated immediately and stale data can impact user experience or business operations, traditional batch processing starts to fall short. In those scenarios, an event-driven, near real-time architecture becomes a necessity rather than an optimisation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnapU0HiU9wV5udE39fa0Q.png" /></figure><p>If you’ve been following my posts, you know that most of my work revolves around batch processing, materialized views, and large analytical datasets powering dashboards and reports.</p><p>For analytics, some delay is usually acceptable. A dashboard refreshing every 30 minutes or even a few hours later is rarely a problem.</p><h4>The Problem:</h4><p>Recently, however, I was asked to build a dataset for a customer-facing chatbot. In this case, data freshness was critical. If a customer made a payment and immediately asked the chatbot about their payment status, showing outdated information was not an option.</p><p>That’s when I realised that the batch-processing patterns I normally rely on were the wrong fit. We needed a system that could react to changes and update customer data within seconds.</p><h4>The Solution:</h4><p>Most of our operational data already lived in DynamoDB, and changes were being captured through DynamoDB Streams. My initial thought was to simply add another consumer for this new use case.</p><p>However, DynamoDB Streams has a limitation, only a small number of direct consumers can be attached to a stream. I didn’t want every new requirement to compete for one of those slots. Instead, I introduced a Kinesis stream as a central event bus. DynamoDB Streams would push all relevant change events into Kinesis, and any downstream system could consume from there independently.</p><p>The architecture became simple: DynamoDB Streams → Kinesis → Multiple Consumers. Now, whenever a new pipeline, Lambda, or processor needs access to real-time events, it can simply subscribe to the Kinesis stream without impacting existing consumers.</p><p>We then introduced a dedicated Lambda for the CDP (Customer Data Platform) sync. The Lambda consumed events from Kinesis and processed them according to the business logic we had defined. As soon as a change occurred in any configured DynamoDB table, the event flowed through Kinesis and was picked up by the CDP sync Lambda. The processed data was then written to a new DynamoDB table, giving the chatbot a single source of truth containing the latest customer information along with all the required business logic and enrichments applied.</p><p>However, this approach introduced a new challenge. Every time we wanted to onboard a new source table, add a column, change a transformation rule, or introduce a new calculated field, we had to modify the Lambda code and redeploy it. While this worked initially, it quickly became a bottleneck. Simple data mapping changes required engineering effort, and product managers or operations teams had no way to make these updates themselves.</p><p>To solve this, we introduced a <strong>CDP Configuration Table</strong>. Instead of hardcoding logic in the Lambda, we moved the behaviour into metadata. The Lambda would read the configuration and decide how to process each table dynamically.</p><p>A typical configuration contained information such as:</p><ul><li><strong>source_table</strong> — Which DynamoDB table to listen to.</li><li><strong>enabled</strong> — Whether processing is active for this table.</li><li><strong>fields_required_from_this_table</strong> — Source-to-target field mappings.</li><li><strong>watch_fields</strong> — Process events only when specific fields change.</li><li><strong>secondary_lookups</strong> — Additional tables to query for enrichment.</li><li><strong>broadcast_field</strong> — Fan-out updates to multiple customer records.</li><li><strong>resolve_sk_from</strong> — Logic to determine the target record when keys are missing.</li><li><strong>archive_on_remove</strong> — Track historical values when fields are removed.</li><li><strong>lookback_days</strong> — Time window for fetching historical data.</li><li><strong>calculated_fields</strong> — Derived metrics and business logic definitions.</li></ul><p>With this change, the Lambda became a generic processing engine. Adding a new table, introducing a new field, or changing business logic often required nothing more than updating a configuration row — no code changes, no deployments, and significantly faster iteration cycles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttGTZEVzoG2V3O5hivockQ.png" /></figure><p>Looking back, the most valuable part of this project wasn’t the Lambda, Kinesis stream, or even the CDP table itself. It was moving business logic out of code and into configuration.</p><p>What started as a simple real-time sync requirement evolved into a generic framework capable of onboarding new source tables, adding enrichments, and changing business rules without requiring deployments. Today, adding a new data source is often as simple as inserting a new configuration row. The result is a system that is easier to maintain, easier to scale, and significantly faster to adapt as business requirements evolve.</p><p>I’ll keep updating this as the approach evolves and new improvements are introduced. Until then —<br>Happy Coding!! Happy Learning!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f030593d4c0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Optimised PostgreSQL Materialized Views Serving 31 Million Rows]]></title>
            <link>https://kuldeepkr16.medium.com/how-i-optimised-postgresql-materialized-views-serving-31-million-rows-81e23b5d1af8?source=rss-ddfef8ceeb54------2</link>
            <guid isPermaLink="false">https://medium.com/p/81e23b5d1af8</guid>
            <category><![CDATA[optimisation]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Kuldeep Trivedi]]></dc:creator>
            <pubDate>Tue, 26 May 2026 17:47:50 GMT</pubDate>
            <atom:updated>2026-05-26T17:49:18.107Z</atom:updated>
            <content:encoded><![CDATA[<p>I shared a blog one year ago about materialized views — <a href="https://medium.com/@kuldeepkr16/automate-materialized-view-refresh-eed94c1973b1">LINK</a>. That approach worked well for about a year, but as the data grew, several challenges started to appear. In this blog, I’ll walk through those problems and the solution I eventually implemented.</p><p>Here’s a summary of what I solved — Across multiple QuickSight datasets, I noticed several CTEs (Common Table Expressions) performing nearly identical transformations, differing only in a few selected columns. To optimize this, I consolidated these repeated CTE patterns into reusable tables and materialized views. These were scheduled to refresh nightly and were then consumed by downstream datasets later in the day.</p><p>This setup worked fine when the data volume was small. But as the data kept growing, the refresh time for materialized views started increasing as well. Over time, this became a bottleneck.</p><p>Another pain point was schema changes. Even a simple data type change in a source table turned into a lengthy process. I had to drop all dependent materialized views, apply the ALTER TABLE, recreate those dependencies, and then trigger refreshes again.</p><p>This created a chain reaction — dependent queries had to wait for materialized views to become available, and in some cases, schema changes introduced locking and operational delays that temporarily impacted upstream data ingestion. What should have been a quick change gradually became an operational overhead.</p><p>Because of this, even the auto schema discovery and auto-update mechanisms I had built into the data pipelines(<a href="https://medium.com/@kuldeepkr16/dynamodb-tables-to-postgres-data-pipeline-4820b4af149b">LINK</a>) became far less effective. Any schema change still required manual handling because of the dependency chain around materialized views.</p><p>There had to be a better solution — one where I could maintain and refresh reusable views independently, without introducing tight coupling to source table changes. The goal was to keep the business logic centralized in views that were consumed across multiple datasets while making the overall system easier to operate and scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7dfP_ZiOyMnYAjO7DoWlw.png" /></figure><p>The answer turned out to be much simpler — <strong>Tables</strong>. I replaced those materialized views with simple views and moved the refresh logic to tables instead. Every night, I generated a staging table from the views without impacting existing consumers. Once the staging table was fully prepared, I used a transaction to atomically swap it with the main table by renaming the tables. This approach eliminated dependency issues, reduced downtime during refreshes, and allowed consumers to continue reading from the existing table until the new version was ready.</p><p>Without any locks —</p><pre>DROP TABLE IF EXISTS sales_summary_staging;<br><br>CREATE TABLE sales_summary_staging AS<br>SELECT *<br>FROM vw_sales_summary;</pre><p>Once the staging table is ready, the final step is a <strong>lock and replace</strong> operation. Since ALTER TABLE ... RENAME is a metadata operation in PostgreSQL, the lock duration is typically very short compared to rebuilding or refreshing materialized views.</p><pre>BEGIN;<br><br>TRUNCATE TABLE sales_summary;<br><br>INSERT INTO sales_summary<br>SELECT *<br>FROM sales_summary_staging;<br><br>ANALYZE sales_summary;<br><br>COMMIT;<br><br>DROP TABLE sales_summary_staging;</pre><p>This approach acquires a brief lock only during the table rename operation and instantly switches consumers to the new dataset. Until that point, all reads continue hitting the existing table while the staging table is built in the background. The result is significantly lower downtime and easier schema evolution compared to managing materialized view dependencies.</p><p>Now, the source tables are completely independent of downstream dependencies. Schema changes and ALTER TABLE operations can happen independently without requiring views or refresh pipelines to be rebuilt. We already built handling for common schema evolution scenarios across integer, boolean, and timestamp columns. Even if a refresh starts failing because of an unexpected change, the recovery process is straightforward — update the view definition, update the target table schema if required, and trigger the refresh again. Since the nightly refresh process was orchestrated through bash scripts, I also built a schema drift detector and auto-updater into the pipeline.</p><p>Before every refresh, it validates schema changes and applies the required updates automatically. The operational model became much simpler — create the table and indexes once, and from that point onward, refreshes, schema updates, and data loading are handled automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PpCk_Ys5DLJRcHL1DQFKyQ.png" /></figure><p>I’ll keep updating this as the approach evolves and new improvements are introduced. Until then — happy coding and happy learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81e23b5d1af8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Data Engineers Can Use AI Effectively]]></title>
            <link>https://kuldeepkr16.medium.com/how-data-engineers-can-use-ai-effectively-a1e81734488e?source=rss-ddfef8ceeb54------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1e81734488e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Kuldeep Trivedi]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 14:57:51 GMT</pubDate>
            <atom:updated>2026-03-16T11:22:36.799Z</atom:updated>
            <content:encoded><![CDATA[<p>I often see posts from data engineers asking how they can practically use AI. It’s a fair question.</p><p>In reality, our data lives in many places — databases, Excel files, CRMs, APIs, and internal systems. Much of this data is private and sits behind servers or bastion hosts. Often, we can’t directly connect AI tools to these systems.</p><p>For example, imagine doing a simple analysis like checking data quality or completeness. Suppose the data exists in two sources — DynamoDB and PostgreSQL. You might run a script locally to fetch data from DynamoDB, but to get PostgreSQL data, you first connect to a server, download the file there, then SCP it to your local machine before you can even ask AI to help analyze it. It quickly becomes a very manual workflow.</p><p>That too, when you are using some tools like cursor, antigravity or a similar tool, this will be too painful if you are chatting directly with ChatGPT, Gemini, or Perplexity. Uploading files and screenshots, and asking questions.</p><p>I recently found a much better way to handle this.</p><h3>The Challenge</h3><p>When working with databases hosted on private networks (e.g., within AWS VPC), teams often face:<br>• No direct connectivity from local development machines<br>• Multi-step access through bastion/jump servers<br>• Manual SQL query writing and execution<br>• Exporting data to CSV and uploading to external AI tools for analysis<br>• Repeatedly explaining schema and relationships to AI assistants</p><h3>The Solution</h3><p>Integrate AI capabilities directly into the development environment using:<br>• SSH Tunnel — Secure, encrypted connection through bastion server<br>• MCP Server — Model Context Protocol for database connectivity<br>• IDE Integration — Query and analyse data without leaving the editor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2C0ZqC8gHa3GONAuKEvhw.png" /></figure><h3>Architecture</h3><p>Local Machine (IDE + AI Chat + MCP Server) → <em>Encrypted SSH Tunnel</em> → Private Network: Bastion Server → PostgreSQL Database</p><h3>Setup Steps</h3><h4>Step 1: Configure SSH Tunnel</h4><p>Create a script to establish an SSH tunnel through your bastion server to the database. The tunnel forwards a local port<br>to the database port.</p><p><strong>Key considerations</strong>:<br>• Use SSH keepalive settings to maintain persistent connections<br>• Handle MFA/2FA prompts if required (can use expect scripting)<br>• Forward to a read replica for safety when possible</p><h4>Step 2: Install MCP Server</h4><p>Add a PostgreSQL MCP server to your IDE configuration. This enables the AI assistant to execute read-only SQL queries directly.<br>Configuration requirements:<br>• Connection string pointing to localhost through the tunnel<br>• Read-only database user credentials<br>• Appropriate timeout settings</p><h4>Step 3: Database Viewer (Optional)</h4><p>Install a database viewer extension for visual schema browsing and query execution with a results grid.</p><h3>Capabilities</h3><h4>Natural Language Queries</h4><p>Ask questions in plain English and get SQL-generated results:<br>• “How many active users do we have?”<br>• “Show me the top 10 customers by revenue”<br>• “What is the average order value by region?”</p><h4>Database Monitoring</h4><p>Monitor database health in real-time:<br>• Check replication lag between primary and replica<br>• View active queries and their duration<br>• Identify blocking queries and lock chains<br>• Analyze connection pools and resource usage</p><h4>Data Operations</h4><p>Generate and verify data operations:<br>• Lookup records by ID with full context<br>• Generate INSERT/UPDATE queries with proper column mapping<br>• Verify changes across primary and replica</p><h3>Usage Workflow</h3><p>• Start the SSH tunnel (approve MFA if required)<br>• Open the IDE with MCP server configured<br>• Ask natural language questions in the AI chat<br>• AI generates SQL, executes it, and returns formatted results<br>• Request follow-up analysis or data modifications as needed</p><h3>Security Considerations</h3><p>• Connect to read replica instead of primary when possible<br>• Use read-only database credentials for the MCP server<br>• SSH tunnel provides end-to-end encryption<br>• Tunnel terminates when session ends — no persistent exposure<br>• Store credentials securely (secrets manager, environment variables)</p><h3>Benefits</h3><p>• Single unified environment for code and data analysis<br>• AI has full schema context without manual explanation<br>• Faster iteration — no CSV exports or tool switching<br>• Real-time database health monitoring<br>• Schema-aware query generation reduces errors<br>• Keep adding more MCP and add more data sources.</p><p>Happy coding!!! Happy Learning!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1e81734488e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Schema Discovery and Evolution In the Data Pipeline]]></title>
            <link>https://kuldeepkr16.medium.com/schema-discovery-and-evolution-in-the-data-pipeline-a33709635930?source=rss-ddfef8ceeb54------2</link>
            <guid isPermaLink="false">https://medium.com/p/a33709635930</guid>
            <category><![CDATA[schema-detection]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[schema-evolution]]></category>
            <category><![CDATA[nosql-to-sql]]></category>
            <dc:creator><![CDATA[Kuldeep Trivedi]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 16:36:33 GMT</pubDate>
            <atom:updated>2025-12-08T16:36:33.804Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0Lk2ZvD3xx3TFYItIMyzg.png" /></figure><p>One of the most important steps in creating a data pipeline is schema discovery and evolution. If the source is NoSQL, it becomes especially critical to automate this step.</p><p>I recently built a data pipeline and wrote a Medium post about it: <a href="https://medium.com/@kuldeepkr16/dynamodb-tables-to-postgres-data-pipeline-4820b4af149b"><strong>LINK</strong></a></p><p>In that write-up, I mentioned one open question:<br>What happens when the schema changes? At that point, the pipeline only raised an alert.</p><p>I handled schema changes manually for a while, and it quickly became obvious that this wasn’t sustainable. It was time to automate the entire process.</p><h4>Step 1 — Catch the Exception</h4><p>The first step is straightforward: wrap the write operation in a try–except block so failures can be intercepted gracefully.</p><h4>Step 2 — Understand What Went Wrong</h4><p>The next challenge is identifying <em>what kind</em> of schema issue occurred. Errors may not explicitly mention the missing table or column, so we need to detect them smartly.</p><h4>Handling Different Scenarios</h4><p><strong>1. Missing Table<br></strong>Since the Glue job already knows the expected table name, simply check whether the target (main or staging) table exists.</p><p><strong>2. Missing Column<br></strong>Look for “relation not found”–type errors and compare the Spark DataFrame schema with the existing table columns.</p><p><strong>3. Data Type Mismatch / Column Size Too Small<br></strong>Compare Spark column types with the table’s column definitions.<br>If a column length is insufficient, compute the max length in the DataFrame to determine the required size.</p><h4>Applying the Fix</h4><p>Once the root cause is identified, the simplest solution is to run an ALTER TABLE command.</p><p>But large or locked tables can make this expensive — your Glue job keeps running (and costing) while waiting for the alter operation.</p><p>The fix:<br>Set a timeout (around 4–5 minutes, adjusted based on load).</p><ul><li>If the alter succeeds within the timeout → retry the data load</li><li>If it times out → alert and stop the job</li></ul><p>At this point, manual intervention is required, preventing the Glue job from burning unnecessary runtime.</p><h4>Alternate option —</h4><p>Another option is to rely on <strong>AWS Glue Crawlers</strong> to infer schemas from the files stored in S3 and automatically update corresponding Glue tables.</p><p>However, this approach comes with several limitations:</p><h4>1. You still need a separate service to sync schemas</h4><p>Glue crawlers can detect schema changes, but your ETL pipelines still need some mechanism to ensure that:</p><ul><li>The newly inferred schema is compatible with your downstream processes, and</li><li>any Glue Table updates are propagated to your application logic or warehouse.</li></ul><p>This essentially means writing <strong>another monitoring or reconciliation service</strong>, which defeats the simplicity you were aiming for.</p><h4>2. Crawlers run on their own schedule</h4><p>Glue crawlers are not event-driven, they run on:</p><ul><li>schedules (cron-like), or</li><li>on-demand triggers that you must manage.</li></ul><p>This creates uncertainty.</p><p>If your Glue ETL job starts before the crawler finishes updating the schema, your job will still fail.<br>For example:<br>Crawler runs every 30 minutes<br>A schema change happens at minute 10<br>Your Glue job starts at minute 12</p><p>→ The crawler hasn’t run yet<br>→ Schema isn’t updated<br>→ Job fails</p><p>This timing dependency makes the whole system unreliable.</p><h4>3. Many tables don’t write data to S3</h4><p>Glue crawlers only work when the source data is stored in S3.<br>They cannot:<br>- Infer schema for JDBC sources<br>- Detect updates in transactional tables<br>- Pull schema from APIs<br>- Generate table metadata for sources not connected to S3</p><p>So for any pipeline where data is not being written to S3 (e.g., direct ingestion into RDS, Postgres, Redshift, DynamoDB), crawlers simply won’t help. This leaves a big portion of tables unmanaged.</p><h3>Code Redundancy Issue</h3><p>Once schema-change handling logic was added to every Glue job, a new problem surfaced:<br>The same code was being duplicated across multiple pipelines.<br>This meant each Glue job contained two responsibilities:</p><ol><li><strong>Data preprocessing logic</strong> (job-specific)</li><li><strong>Schema change detection &amp; correction logic</strong> (common across all jobs)</li></ol><p>Not only did this make the code harder to maintain, but any update in the schema-handling logic required editing every Glue job script — an unnecessary operational burden and a clear violation of modular design principles.</p><h4>Decoupling Schema Handling From ETL Logic</h4><p>Ideally, each Glue job should contain only the logic specific to its preprocessing or transformation tasks.</p><p>Schema-related routines — such as detecting missing columns, mismatched data types, increasing column sizes, or creating missing tables — should be centralized and reused across jobs.</p><p>To solve this, I created a separate Glue job that has all the reusable code.<br>All schema management functions were moved into a single Python module and then shared across jobs.</p><h4>Making It Reusable with a Common Library</h4><p>AWS Glue allows importing external Python code by supplying it via the Python library path argument.</p><p>So I packaged all the common functions into a single reusable module:</p><pre>s3://&lt;bucket-name&gt;/glue_scripts/common/etl_common_glue.py</pre><p>Then, every Glue job imports it by simply configuring:</p><pre>--extra-py-files s3://bucket-name/glue_scripts/common/etl_common_glue.py</pre><p>Now all jobs use:</p><pre>from etl_common_glue import handle_schema_changes</pre><h4>Benefits</h4><ul><li>No code duplication</li><li>One place to update schema logic</li><li>Cleaner, smaller Glue job scripts</li><li>Better maintainability and consistency across all ETL pipelines</li></ul><p>Automating schema handling and centralizing common Glue logic has made our pipelines cleaner, faster to maintain, and far more resilient. It’s a small shift with a big long-term impact — and one that I’d recommend to any team working with evolving data structures.</p><p>Happy coding!!! Happy Learning!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a33709635930" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing AWS Quicksight Resources]]></title>
            <link>https://kuldeepkr16.medium.com/managing-aws-quicksight-resources-6aafa54668ec?source=rss-ddfef8ceeb54------2</link>
            <guid isPermaLink="false">https://medium.com/p/6aafa54668ec</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[finops]]></category>
            <category><![CDATA[quicksight]]></category>
            <dc:creator><![CDATA[Kuldeep Trivedi]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 18:14:27 GMT</pubDate>
            <atom:updated>2025-12-05T15:41:37.347Z</atom:updated>
            <content:encoded><![CDATA[<p>How I was able to save thousands of dollars by setting alerts and cleaning up resources in Quicksight</p><p>As an Admin and Maintainer of AWS Quicksight, I usually visit the Quicksight admin portal to see how many users, datasets, analyses, and dashboards we have. How much spice capacity are we using, and what other charges are we incurring for our account?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQYlU2bCiCJjPfLY5R3xzg.png" /></figure><p>For the last few months, I have been busy developing data pipelines (details of which you can find in my other blogs <a href="https://medium.com/@kuldeepkr16/dynamodb-tables-to-postgres-data-pipeline-4820b4af149b">here</a>). After 3 months, when I visited the Quicksight admin portal, something seemed off. Spice capacity reached 3TBs, many data analysts had author accounts who left the system, and many switched teams, but we were still paying for these author accounts. When I looked closer, I found that there were many datasets not used in any analysis or dashboard. Some were only used in test analyses, but they were still taking up tens of gigabytes of Spice storage.</p><p>I removed all such users and cleaned up datasets with the help of data analysts. But I needed some process so that I don&#39;t have to check this manually every time, so I set some alerts for this.</p><p>Quicksight offers APIs to get information about its resources. I used Python’s boto3 library to connect and retrieve details about the datasets and other resources.</p><ol><li><a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/quicksight/client/list_data_sets.html">list_data_sets</a>()</li><li><a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/quicksight/client/describe_data_set.html">describe_data_set</a>()</li></ol><pre>quicksight = boto3.client(&#39;quicksight&#39;, region_name=region)<br><br>dataset_response = quicksight.list_data_sets(<br>                        AwsAccountId=account_id,<br>                        MaxResults=100<br>                        )<br><br># from dataset_response get the dataset_id<br><br>dataset_detailed_response = quicksight.describe_data_set(<br>                        AwsAccountId=account_id,<br>                        DataSetId=dataset_id<br>                        )<br><br># from dataset_detailed_response get the size and other details about dataset</pre><p>Now that you have all the details about the datasets, you can sort them by size and filter out the top 10 largest ones. Sending this information regularly to data analysts helps them understand which datasets consume the most SPICE capacity. With these insights, analysts can review if any large datasets are unused or redundant and take steps to optimize or remove them. I have set this process to run weekly to keep the team updated and help manage storage efficiently.</p><p>Similarly — We have list_users(), list_analyses() and list_dashboards().<br>This opens up many possibilities. We can get all the datasets, check the size and refine them. We can get a list of all the authors and readers&#39; accounts monthly and clean it if required. We can get all the unused datasets and clean them.</p><p>Using describe_dashboard_permissions(), describe_analysis_permissions() and describe_data_set_permissions() and update_dashboard_permissions(), update_analysis_permissions() and update_data_set_permissions() we can manage access to these resources.</p><p>You can check out more here — <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/quicksight.html/">https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/quicksight.html</a></p><p>I will update this blog as and when I find more interesting use cases.</p><p>Till then, Happy Coding! Happy Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6aafa54668ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Optimised a 13 Million Row PostgreSQL Migration]]></title>
            <link>https://kuldeepkr16.medium.com/how-i-optimised-a-13-million-row-postgresql-migration-29ba91cedc8d?source=rss-ddfef8ceeb54------2</link>
            <guid isPermaLink="false">https://medium.com/p/29ba91cedc8d</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <dc:creator><![CDATA[Kuldeep Trivedi]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 14:43:24 GMT</pubDate>
            <atom:updated>2025-08-16T14:43:24.690Z</atom:updated>
            <content:encoded><![CDATA[<p>After implementing the pipeline,<a href="https://kuldeepkr16.medium.com/dynamodb-tables-to-postgres-data-pipeline-4820b4af149b#8c6e-b8b3e5da3ae9"> I explained in this blog — LINK</a>. In the new schema tables, I had to have all the historical data as well, so that data analysts can now start using the new table itself.</p><h3>The Problem That Kept Me Up All Night</h3><p>Migrate 13 million records from our production database to a new schema with two additional ETL tracking columns. I thought it should take an hour or two.</p><p>20 hours later, I was still watching my terminal, desperately trying different approaches as our maintenance window was closing. The migration that was supposed to be done by morning was nowhere near complete.</p><p>If you’ve ever dealt with large-scale data migrations in PostgreSQL, you know the pain. Each approach I tried seemed reasonable at first, but failed spectacularly at scale:</p><ul><li><strong>Direct INSERT with ON CONFLICT</strong>: Checking 13 million rows for duplicates turned a simple insert into a crawling nightmare</li><li><strong>COPY TO/FROM with files</strong>: “No space left on device” — our host didn’t have free space for the intermediate CSV</li><li><strong>Piping between databases</strong>: Read to Write dbs — Network overhead between RDS instances made this unbearably slow</li><li><strong>Parallel processing by event types</strong>: Still took hours due to conflict checking</li></ul><h3>The Revelation: CTAS (CREATE TABLE AS SELECT)</h3><p>After exhausting conventional approaches, I remembered an often-overlooked PostgreSQL feature: CREATE TABLE AS SELECT (CTAS). What if instead of inserting into an existing table, I created a new one?</p><p>The approach was simple:</p><h4>Step 1: Create a New Table with All Data</h4><pre>CREATE TABLE etl_schema.sample_table AS <br>SELECT * FROM schema.sample_table;</pre><p>This single command did what took hours before — in just 3 minutes! PostgreSQL’s CTAS is optimised for bulk operations because:</p><ul><li>No constraint checking during creation</li><li>Minimal logging (compared to individual INSERTs)</li><li>Sequential disk writes</li><li>No index maintenance during load</li></ul><h4>Step 2: Modify the Structure</h4><pre>-- Drop columns we don&#39;t need<br>ALTER TABLE etl_schema.sample_table <br>    DROP COLUMN IF EXISTS col1,<br>    DROP COLUMN IF EXISTS col2;</pre><pre>-- Add new ETL tracking columns<br>ALTER TABLE etl_schema.sample_table <br>    ADD COLUMN etl_ingested_at timestamp DEFAULT CURRENT_TIMESTAMP,<br>    ADD COLUMN etl_is_deleted_at_source boolean DEFAULT false;</pre><h4>Step 3: Add Constraints and Indexes</h4><pre>-- Add primary key<br>ALTER TABLE etl_schema.sample_table <br>ADD CONSTRAINT sample_table_pkey PRIMARY KEY (id);</pre><pre>-- Create indexes<br>CREATE INDEX CONCURRENTLY sample_table_idx <br>ON etl_schema.sample_table (index_col);<br>-- ... other indexes</pre><h4>Why This Approach Is Superior</h4><h4>1. Speed:</h4><ul><li>Traditional INSERT: 20+ hours</li><li>CTAS approach: 20 minutes total</li></ul><h4>2. Simplicity:</h4><p>No complex scripts, no parallel processing logic, no intermediate files</p><h4>3. Atomicity:</h4><p>The final swap is atomic — either it all works or nothing changes</p><h4>4. Resource Efficiency:</h4><ul><li>Minimal CPU usage (no conflict checking)</li><li>No network overhead</li><li>No intermediate storage needed</li></ul><h4>5. Predictability:</h4><p>CTAS performance is linear with data size, making it easy to estimate completion time</p><h4>Lessons Learned</h4><ol><li><strong>Don’t Overthink It</strong>: Sometimes the simplest solution is the best. I spent hours on complex parallel processing when a basic CTAS would have solved it in minutes.</li><li><strong>Understand Your Tools</strong>: PostgreSQL has powerful features like CTAS that are often overlooked in favour of more “sophisticated” approaches.</li><li><strong>Test at Scale</strong>: What works for 1,000 rows might fail miserably at 13 million. Always test with production-scale data.</li><li><strong>Constraints Are Expensive</strong>: Adding constraints after bulk loading is much faster than checking them during insert.</li></ol><h4>When to Use This Approach</h4><p>CTAS is perfect when:</p><ul><li>Migrating entire tables</li><li>Adding/removing columns during migration</li><li>No need to preserve during migration (can handle updates separately)</li><li>Have enough disk space for the temporary table</li></ul><h4>Conclusion</h4><p>Next time you’re facing a large PostgreSQL migration, before reaching for complex ETL tools or writing elaborate parallel processing scripts, ask yourself: “Can I just CREATE TABLE AS SELECT?”</p><p>Happy Coding. Happy Learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29ba91cedc8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DynamoDB tables to Postgres Data Pipeline]]></title>
            <link>https://kuldeepkr16.medium.com/dynamodb-tables-to-postgres-data-pipeline-4820b4af149b?source=rss-ddfef8ceeb54------2</link>
            <guid isPermaLink="false">https://medium.com/p/4820b4af149b</guid>
            <category><![CDATA[data-migration]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[aws-data-pipeline]]></category>
            <dc:creator><![CDATA[Kuldeep Trivedi]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 10:00:27 GMT</pubDate>
            <atom:updated>2025-08-14T13:48:34.922Z</atom:updated>
            <content:encoded><![CDATA[<h3>DynamoDB tables to Postgres – Data Pipeline</h3><p>This is another story of how we reduced our data sync cost by 80%</p><p><strong>The Setup.</strong> We’ve got data sitting in DynamoDB tables. Our data analysts and ML engineers? They need this data in AWS RDS Postgres for SQL queries and pre-processed data.</p><p>I’m breaking this down into 2 clean parts:<br>1. DynamoDB tables → S3<br>2. S3 → Postgres</p><p><strong>Why this approach?<br></strong>Because trying to do direct DynamoDB to Postgres sync is expensive and messy. S3 acts as our middle ground — cheap storage, reliable, and plays nice with everything. And, we can reload the full table data without scanning the table again.</p><p>Let’s dive into each part…</p><h4>Part 1: <strong>DynamoDB tables to S3</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Chj6ligxy-HnucPCCo3ghw.png" /></figure><p>a. <strong>DynamoDB Source Tables</strong> — Enable streams for the tables which you want to pull. <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html">Link to AWS Doc</a><br>If you want to handle all the deleted events along with new updates from the DynamoDB table, enable <strong>New and old images </strong>option in the stream.</p><p>b. <strong>AWS Lambda </strong>— Every time something changes in our DynamoDB table, Lambda gets triggered. Pretty straightforward.<br>We could preprocess the data or add extra info. But we’re keeping it simple. Just adding two fields:<br><strong>row_updated_on_timestamp</strong> — The exact moment we pulled this record from DynamoDB. No guessing games.<br><strong>is_deleted_as_source</strong> — Here’s the clever part. We’ve enabled <strong>New and old images</strong> in our stream. So every event gives us two things:<br> - OldImage key<br> - NewImage key<br>If OldImage exists and NewImage is empty? That means the record got deleted from the table. Mark is_deleted_as_source = true.</p><p>c. <strong>Config Table In DynamoDB</strong>: In this config table, we store source table-level parameters. Parameters like S3 schedule, primary keys, pre-processing glue, Postgres schedule, current glue job status, etc.</p><p>d. <strong>AWS Firehose</strong>: Automatically writes data to S3 dynamic partitions with a custom buffer size and time limits. We created 2 firehoses. If the updates in the table are frequent, then put data into a 5-minute firehose; otherwise, 15 15-minute firehose. And where is this config defined? Yes, you guessed it. Its <strong>Config Table In DynamoDB.</strong></p><p>e. <strong>S3 Bucket: </strong>Where all our data lands. Simple hourly partitioning.<br>Structure — <br>&lt;dynamodb_table_name&gt;/year/month/day/hour/</p><p>Now, let&#39;s talk about scalability and ease of adding new tables — <br>1. As the data increases, new files will be added to S3. At scale? Large and frequent files.<br>2. Adding a new table, just add a trigger to the lambda and config in the <strong>Config Table.</strong></p><h4><strong>Part 2: S3 to Postgres</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FLbbmxf51CJyRdU4cIgMpg.png" /></figure><p>a. <strong>Eventbridge Rule: </strong>triggers Lambda every 15 Mins.</p><p>b. <strong>AWS Lambda: </strong>It checks the config table, picks the table name, the last file timestamp, the schedule and the last glue run timestamp. Collects all the new files from S3. Triggers the glue job with all the required parameters.</p><p>c. <strong>AWS Glue Job: </strong>2 types of glue jobs here. <br>1. Generic Glue job: reads data from S3 paths provided and loads into Postgres.<br>2. <strong>Pre-Processing Glue</strong>: PySpark jobs created specifically to pre-process data at the table level.</p><p>1 question: How does Lambda figure out which glue job to trigger for a given table? Yes, our old Config table in DynamoDB.<br>Let me finally show you what it all contains:</p><pre>{<br> &quot;table_name&quot;: &quot;&quot;,<br> &quot;dynamodb_to_s3_schedule&quot;: 15,<br> &quot;is_dynamo_to_s3_enabled&quot;: true,<br> &quot;is_s3_to_postgres_enabled&quot;: true,<br> &quot;last_glue_job_ran_timestamp&quot;: &quot;&quot;,<br> &quot;last_glue_job_status&quot;: &quot;SUCCESS/PROCESSING/FAILED&quot;,<br> &quot;last_processed_file_timestamp&quot;: &quot;&quot;,<br> &quot;load_type&quot;: &quot;incremental/full&quot;,<br> &quot;primary_keys&quot;: &quot;&quot;,<br> &quot;pre_processing_file&quot;:&quot;&quot;,<br> &quot;s3_to_postgres_schedule&quot;: 30<br>}</pre><ul><li><strong>last_glue_job_status</strong> —Smart safety check. No double-processing headaches.<br> — Glue job starts: marks status as PROCESSING<br> — Job finishes: updates to either SUCCESS or FAIL<br> — New trigger comes in: checks status first<br>Status is<strong> PROCESSING?</strong> Skip it. Don’t start another job.<br>Status is<strong> SUCCESS </strong>or<strong> FAIL?</strong> Good to go. Fire up the next one.</li></ul><p>No overlapping jobs. No resource conflicts. No weird data issues from multiple jobs hitting the same table.</p><ul><li><strong>load_type: incremental/full</strong> — if it&#39;s incremental, then only new files will be provided to glue, else if full, then all the files from path &lt;table_name&gt;/ will be processed.</li><li><strong>pre_processing_file — </strong>if it&#39;s not provided, then generic glue will be triggered, else specific preprocessing glue job.</li></ul><p>Adding a new table that needs pre-processing?<br>Build your preprocessing Glue job separately<br> — Test it until it works<br> — Update the config table<br> — Done<br>Everything else? The pipeline handles it automatically.</p><p>Only 1 thing is remaining in this pipeline. What if there is a schema change? Currently, it just alerts. Thinking of ways to handle this automatically. Feel free to drop some ideas in comments.</p><p>Till then, Happy Coding. Happy Learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4820b4af149b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Reduced DB Sync Cost by 60% Using Incremental Strategy]]></title>
            <link>https://kuldeepkr16.medium.com/how-we-reduced-sync-costs-by-60-using-incremental-strategy-039cabcdb7fb?source=rss-ddfef8ceeb54------2</link>
            <guid isPermaLink="false">https://medium.com/p/039cabcdb7fb</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[aws-data-pipeline]]></category>
            <dc:creator><![CDATA[Kuldeep Trivedi]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 18:38:38 GMT</pubDate>
            <atom:updated>2025-08-09T05:56:52.155Z</atom:updated>
            <content:encoded><![CDATA[<p>When we set out to implement incremental sync between two databases, we explored various approaches — logical replication, external sync tools, and cloud-native solutions. In the end, we chose to build a custom AWS Data Pipeline.</p><p>First Question.<br><strong>Why not use pg_logical?<br></strong>Because it puts a heavy load on the database, it consumes significant storage and system resources, which can start affecting your normal queries. Plus, setting it up and maintaining it is quite complicated.</p><p>Then what is the solution?<br>AWS Data Pipeline. Our old favourite.</p><p>2 different databases with endpoints. Read user in source database and write user in destination db. That&#39;s all you need.<br>In my current company, we initially used an external tool to do this: it would pull data from the source and push it to the destination. But as expected, we ran into frequent downtimes and ended up with a huge monthly bill.</p><p>Let&#39;s discuss the AWS Data Pipeline solution we came up with. Configurable. Low Cost. Scalable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXFsitCGlKCePrjo47udug.png" /><figcaption>AWS Data Pipeline — Sync 2 DBs</figcaption></figure><p>Let&#39;s go through the resources. One by one —</p><ol><li><strong>EventBridge Rule</strong> — Acts like a cron job. It triggers our Lambda every 15 minutes to initiate the pipeline.</li><li><strong>Lambda Function</strong> — Reads the DynamoDB config table containing source table names, last record timestamps, primary keys, and their schedules. It checks if each table is due for sync based on the schedule, and if so, triggers a Glue job with the required config.</li><li><strong>DynamoDB Table</strong> — Config of source tables — this is a creative part, where we are storing table info and keep updating in every glue job run. Columns in this table — <br>- table_name: source table name.<br>- active_flag: true/false, enable or disable table refresh.<br>- glue_last_ran_at: &lt;timestamp&gt;, to trigger next glue job, if it&#39;s past next scheduled time<br>- last_record_timestamp: &lt;timestamp&gt;, to keep track of the incremental data state.<br>- schedule: minutes, to trigger the glue job. every n minutes.</li><li><strong>Glue Job</strong> — Uses last_record_timestamp to fetch only new data from the source DB. This data is first inserted into a staging table. To handle upserts, it identifies overlapping records in the main table using primary keys, deletes them, and then inserts all records from the staging table into the main table. Finally, it truncates the staging table to prepare for the next run.</li><li><strong>Source db</strong> — Just create a new user. Give read permission to the required schema and tables.</li><li><strong>Destination db</strong> — Create a user. Give write permission to the required schema and tables.</li></ol><p><strong>Key Features of the Pipeline</strong></p><ol><li><strong>Fully Configurable</strong>: Add any number of source tables and define a custom schedule for each one.</li><li><strong>Easily Skippable</strong>: Toggle any table on or off by changing its active flag.</li><li><strong>Supports Historical Loads</strong>: Need past data? Just update the last_record_timestamp to an earlier date, and the job will pick up from there.</li><li><strong>Idempotent by Design</strong>: The pipeline ensures consistent results — running it multiple times with the same input won’t create duplicates or alter the outcome.</li><li><strong>Parallel</strong> — Sync runs concurrently for multiple tables, improving efficiency and reducing total processing time.</li></ol><p><strong>Result</strong> — Achieved a 62.5% monthly cost reduction. This pipeline is more configurable and easier to maintain.<br>A few enhancements are still in the pipeline. Will share updates soon.</p><p>Until then — Happy Coding, Happy Learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=039cabcdb7fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of Table-Valued Functions in PostgreSQL]]></title>
            <link>https://kuldeepkr16.medium.com/unlocking-the-power-of-table-valued-functions-in-postgresql-5eb6a15dd85f?source=rss-ddfef8ceeb54------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eb6a15dd85f</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Kuldeep Trivedi]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 17:29:20 GMT</pubDate>
            <atom:updated>2025-04-21T17:29:20.484Z</atom:updated>
            <content:encoded><![CDATA[<p>Most developers are familiar with functions that return scalar values—like integers, text, or booleans—when working with Postgresql. However, PostgreSQL also supports a more powerful concept: <strong>Table-Valued Functions (TVFs)</strong>. These functions return an entire table as a result and can significantly improve readability, modularity, and reusability in your SQL code.</p><p>In this post, we’ll walk through what Table-Valued Functions are, why you might use them, and how to implement them in PostgreSQL.</p><h3>What Are Table-Valued Functions?</h3><p>A <strong>Table-Valued Function</strong> is a user-defined function that returns a set of rows, behaving much like a regular table. You can query it using SELECT * FROM, join it with other tables, or apply filters and aggregations.</p><p>This feature is extremely helpful when you want to encapsulate logic that produces a dataset, such as complex joins, filters, or aggregations, and make it reusable across different queries or applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUG1jLWd6DMS0TB8oxLpyg.png" /></figure><h3>Why Use Table-Valued Functions?</h3><p>Here are a few practical advantages of using TVFs:</p><ul><li><strong>Code Reusability</strong>: Encapsulate logic used across multiple queries.</li><li><strong>Modularity</strong>: Keep complex query logic clean and separate.</li><li><strong>Security</strong>: Apply access control via function privileges.</li><li><strong>Performance</strong>: Can be optimised similarly to views when used effectively.</li></ul><h3>Creating a Table-Valued Function</h3><p>Let’s look at an example.</p><p>Suppose you have a table orders and want to create a function that returns all orders above a certain total amount.</p><h3>Table Schema</h3><pre>CREATE TABLE orders (<br>    id SERIAL PRIMARY KEY,<br>    customer_id INT,<br>    order_date DATE,<br>    total_amount NUMERIC<br>);</pre><h3>Creating the Function</h3><pre>CREATE OR REPLACE FUNCTION get_large_orders(min_amount NUMERIC)<br>RETURNS TABLE (<br>    order_id INT,<br>    customer_id INT,<br>    order_date DATE,<br>    total_amount NUMERIC<br>)<br>AS $$<br>BEGIN<br>    RETURN QUERY<br>    SELECT id, customer_id, order_date, total_amount<br>    FROM orders<br>    WHERE total_amount &gt; min_amount;<br>END;<br>$$ LANGUAGE plpgsql;</pre><h3>Using the Function</h3><p>You can use it just like a table in your SQL queries:</p><pre>SELECT * FROM get_large_orders(500);</pre><p>This will return all orders where the total amount is greater than 500.</p><h3>Alternative: SQL Inline Function</h3><p>PostgreSQL also supports writing TVFs in SQL directly without the plpgsql block:</p><pre>CREATE OR REPLACE FUNCTION get_large_orders(min_amount NUMERIC)<br>RETURNS TABLE (<br>    order_id INT,<br>    customer_id INT,<br>    order_date DATE,<br>    total_amount NUMERIC<br>)<br>AS $$<br>    SELECT id, customer_id, order_date, total_amount<br>    FROM orders<br>    WHERE total_amount &gt; min_amount;<br>$$ LANGUAGE sql;</pre><p>This version is shorter and works well for simpler queries.</p><h3>Real-World Use Cases</h3><ul><li>Reusable filters for reporting dashboards.</li><li>Encapsulating business logic like “active users,” “high-value transactions,” or “expired subscriptions.”</li><li>Modularising complex joins and aggregations for better maintainability.</li></ul><h3>Things to Keep in Mind</h3><ul><li>Functions return a snapshot of data at the time of execution. Unlike views, they don’t reflect live updates unless re-executed.</li><li>TVFs can be slower than views if overused or written inefficiently, so always analyse execution plans.</li></ul><h3>Conclusion</h3><p>Table-Valued Functions are an underutilised feature in PostgreSQL that can greatly simplify and structure your SQL logic. They promote cleaner, more maintainable code and enable you to write complex logic once and reuse it across your application or analytics workflows.</p><p>If you haven’t used TVFs before, try creating a few based on your most frequently used queries — you might be surprised by how much cleaner your code becomes.</p><p>Happy Learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eb6a15dd85f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Prepare for a Data Analyst Interview]]></title>
            <link>https://kuldeepkr16.medium.com/how-to-prepare-for-a-data-analyst-interview-a3f824994404?source=rss-ddfef8ceeb54------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3f824994404</guid>
            <category><![CDATA[sql-interview]]></category>
            <category><![CDATA[data-analyst]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Kuldeep Trivedi]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 19:14:45 GMT</pubDate>
            <atom:updated>2025-04-14T19:14:45.237Z</atom:updated>
            <content:encoded><![CDATA[<p>I have taken around 25+ interviews for data analyst roles recently.</p><p>And if I had to summarize one common pattern:<br>Most candidates are underprepared in the one skill that matters the most — SQL.</p><p>Not fancy dashboards.<br>Not ML algorithms.<br>Not anything related to business intelligence.<br><strong><em>Just plain, solid, clean SQL</em></strong></p><p>We don&#39;t ask trick questions. We just expect candidates to be fluent in a few basic SQL concepts like Joins, Aggregates, CTEs, Window functions and Subqueries. These aren’t “bonus” skills — they’re the daily bread of a data analyst.<br>And it’s painful to see talented people stumble just because they skipped mastering the fundamentals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9V3mheRLJo9HNIsutkR6Wg.png" /><figcaption>Worried about next interview?</figcaption></figure><p>Few candidates have theoretical knowledge, but while implementing they will fail to even write the Join at the correct place. They will ask me in the end, am I on the correct path of learning data analysis, am I preparing for the interviews correctly? What else can I do to prepare?</p><p>My only answer is — practice a lot. There are so many websites available which have lots of SQL questions. All from basics to advanced. Just sign up and start practising.</p><p>Let&#39;s talk about the basics of SQL —</p><ol><li>Joins: Definition, types of joins. And a few questions to solve.<br>Self joins can be tricky so practice those a lot. Example — Leetcode Question 181. Employees Earning More Than Their Managers.</li><li>Aggregates: Aggregate functions are used to perform a calculation on a set of values and return a single value.<br>Most Common Aggregate Functions:<br> • COUNT() — Number of rows<br> • SUM() — Total of a numeric column<br> • AVG() — Average value<br> • MIN() — Minimum value<br> • MAX() — Maximum value</li></ol><p>Tip: Always practice using GROUP BY with aggregate functions. <br>Know how to filter aggregated results using HAVING. <br>Example — LeetCode 1141. User Activity for the Past 30 Days I — involves COUNT() and GROUP BY.</p><p>3. CTEs (Common Table Expressions): CTEs let you create temporary result sets that can be referred to within a SELECT, INSERT, UPDATE, or DELETE statement.<br>Why use CTEs?<br> • Improves readability.<br> • Makes complex queries modular.<br> • Can be recursive for hierarchical data.</p><p>Example — LeetCode 570. Managers with at Least 5 Direct Reports — writing clean queries using CTEs helps a lot here.</p><p>4. Window Functions: Window functions perform a calculation across a set of table rows that are somehow related to the current row.<br>Common Functions:<br> • ROW_NUMBER()<br> • RANK()<br> • DENSE_RANK()<br> • SUM() OVER(…)<br> • AVG() OVER(…)</p><p>Use with: PARTITION BY, ORDER BY.<br>Example — LeetCode 178. Rank Scores — great for learning DENSE_RANK().</p><p>5. Subqueries: Subqueries are queries nested inside another query.<br>Types:<br> • Scalar Subquery — returns a single value<br> • Correlated Subquery — depends on the outer query<br> • IN/EXISTS/NOT IN/NOT EXISTS subqueries</p><p>Tip: Correlated subqueries can be tricky but powerful.<br>Example — LeetCode 183. Customers Who Never Order — simple subquery with NOT IN.</p><p>Happy Learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3f824994404" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>