<?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 Tiye Baldwin-Anderson on Medium]]></title>
        <description><![CDATA[Stories by Tiye Baldwin-Anderson on Medium]]></description>
        <link>https://medium.com/@tiye_78900?source=rss-8b514f478a8c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jhmOaMJPpi4iZfCkeJCPMA.png</url>
            <title>Stories by Tiye Baldwin-Anderson on Medium</title>
            <link>https://medium.com/@tiye_78900?source=rss-8b514f478a8c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 04:25:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tiye_78900/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[SQL Pattern Series #5: The Deduplication Pattern]]></title>
            <link>https://medium.com/@tiye_78900/sql-pattern-series-5-the-deduplication-pattern-a1c0a1cfbe02?source=rss-8b514f478a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1c0a1cfbe02</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-analyst]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Tiye Baldwin-Anderson]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 14:35:50 GMT</pubDate>
            <atom:updated>2026-07-01T14:26:59.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gF-qJWT1Adepfqiz.png" /></figure><blockquote><em>SQL Pattern Series #5 of 21</em></blockquote><blockquote><em>A collection of practical SQL patterns that help developers recognize common solutions to recurring database problems.</em></blockquote><h3>What You’ll Learn</h3><p>In this article you’ll learn:</p><ul><li>How to identify duplicate records</li><li>Why duplicates are often unavoidable in real systems</li><li>How ROW_NUMBER() helps isolate the record you want to keep</li><li>A common pattern for deduplicating data</li></ul><p>Most developers eventually encounter a table that contains duplicate records.</p><p>Sometimes the duplicates are accidental.</p><p>Sometimes they are the result of imports, integrations, retries, or application bugs.</p><p>The challenge is usually not finding the duplicates.</p><p>The challenge is deciding:</p><blockquote><em>Which row should survive?</em></blockquote><h3>The Problem</h3><p>Imagine a Users table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*pSopaot0JIFpv3IsY__EtQ.png" /></figure><p>The email address appears more than once.</p><p>If only one row should remain, which one do we keep?</p><p>The oldest?</p><p>The newest?</p><p>The one with the highest ID?</p><p>The answer depends on the business rule.</p><p>Once that rule is defined, the Deduplication Pattern becomes useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*EBg4WIdIACa9HjM4rOH4CA.png" /></figure><h3>The Deduplication Pattern</h3><p>The most common approach uses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*SkQ5MgdV4xWQ9lwAgihuXg.png" /></figure><p>combined with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*A_o8SgEFeo3gp2HZP5euMg.png" /></figure><p>to assign a sequence number to each duplicate group.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*6xum__4Lq9XBeSltoz-3iw.png" /></figure><p>This creates groups based on Email.</p><p>Within each group, rows are numbered.</p><p>The newest record receives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*PZr-YmcCjZ4JXUm_GTIniA.png" /></figure><p>The next receives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*q8xL82bZF0HjzdMKuA-4XA.png" /></figure><p>and so on.</p><h3>Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*cuW2lB6Gf0WInL--tCGz2A.png" /></figure><p>This returns:</p><blockquote><em>The most recent record for each email address.</em></blockquote><p>All other duplicates are excluded.</p><h3>Why This Pattern Matters</h3><p>Deduplication is one of the most common data-cleaning tasks.</p><p>You’ll encounter it when:</p><ul><li>importing data</li><li>merging systems</li><li>cleaning customer records</li><li>preparing analytics datasets</li><li>fixing application issues</li></ul><p>The pattern allows you to express exactly which record should survive.</p><p>That makes the logic clear and repeatable.</p><h3>Window Functions Make This Easy</h3><p>Before window functions became widely available, deduplication often required:</p><ul><li>self joins</li><li>nested subqueries</li><li>temporary tables</li></ul><p>Window functions simplified the process dramatically.</p><p>By combining:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*pstUguxOcXyYBRHcfbiPAA.png" /></figure><p>with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*puR1Y1WRk_Mem8Epp5hOgQ.png" /></figure><p>you can isolate duplicates in a single query.</p><h3>Choosing the Winning Row</h3><p>The most important part of the pattern is often:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*w9cEbWZljOl49KnQuebnhQ.png" /></figure><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*j-hBqB0PbkInXS4weBrz5w.png" /></figure><p>keeps the newest row.</p><p>But you could also choose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*xHZXHbNBqLc9lBDehFJ4KQ.png" /></figure><p>to keep the oldest.</p><p>Or:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*tY2jO_GeH6entnr_RyDW4g.png" /></figure><p>to keep the highest ID.</p><p>The ordering defines the business rule.</p><h3>A Note on Ties</h3><p>One subtle detail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*uwAd9OBtinfOrdLs4d149w.png" /></figure><p>works well when every CreatedDate value is unique.</p><p>But what happens if two rows share the same timestamp?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*0S6EGT9jFRsCJLtSEPZLrA.png" /></figure><p>In that case, ROW_NUMBER() will still assign:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*hsM6dsEYpjntpAAJaZfALg.png" /></figure><p>but the database may choose either row as the winner.</p><p>If the result must be predictable, add a tiebreaker:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*lMo53FAlv7Kx6zrvPs01Sg.png" /></figure><p>Now the ordering is deterministic.</p><p>When multiple rows share the same timestamp, the row with the highest UserID wins consistently.</p><h3>When I Reach for This Pattern</h3><p>I typically use the Deduplication Pattern when:</p><ul><li>duplicate records exist</li><li>I need one row per business entity</li><li>data quality issues must be cleaned</li><li>multiple systems have been merged</li></ul><p>Examples include:</p><ul><li>duplicate customer records</li><li>duplicate email addresses</li><li>repeated imports</li><li>overlapping transaction data</li></ul><h3>Key Takeaway</h3><p>Finding duplicates is only half the problem.</p><p>The real question is:</p><blockquote><em>Which row should survive?</em></blockquote><p>The Deduplication Pattern provides a repeatable way to answer that question.</p><p>By combining:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*q47dq09WLhz68_9mskKW5g.png" /></figure><p>with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*eW0XDxKRHlvOjLstqn6bVQ.png" /></figure><p>you can identify the winning row and remove the rest.</p><h3>SQL Pattern Series</h3><p>This article is part of the <strong>SQL Pattern Series</strong>, a collection of practical SQL patterns that help developers recognize common problem-solving approaches found in reporting, analytics, and application development.</p><h3>SQL Patterns: The Recognition Approach</h3><p><a href="https://www.amazon.com/SQL-Patterns-Recognition-Memorizing-Recognizing/dp/B0H663V6PB/">SQL Patterns: The Recognition Approach</a> is now available on Amazon.</p><p>This book grew out of the SQL Pattern Series.</p><h3>SQL Bubble Pop</h3><p>If you are learning SQL or helping others learn SQL, I created <a href="https://apps.apple.com/us/app/sql-bubble-pop-sql-coding-game/id6744767120"><strong>SQL Bubble Pop</strong></a>, a mobile game that teaches SQL concepts through quick, interactive challenges and pattern recognition exercises.</p><p>The goal is simple:</p><blockquote><em>Learn SQL by recognizing patterns instead of memorizing syntax.</em></blockquote><p><em>Originally published at </em><a href="https://dev.to/baldwin_apps/sql-pattern-series-5-the-deduplication-pattern-125g"><em>https://dev.to</em></a><em> on June 13, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1c0a1cfbe02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Pattern Series #4: The Moving Sum Pattern]]></title>
            <link>https://medium.com/@tiye_78900/sql-pattern-series-4-the-moving-sum-pattern-9a1141569f38?source=rss-8b514f478a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a1141569f38</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Tiye Baldwin-Anderson]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 14:35:06 GMT</pubDate>
            <atom:updated>2026-06-15T01:43:05.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*llpwfrlNgZNrhHO1.png" /></figure><p><em>Seeing what is happening over the last N rows</em></p><blockquote><em>SQL Pattern Series #4 of 21</em></blockquote><blockquote><em>A collection of practical SQL patterns that help developers recognize common solutions to recurring database problems.</em></blockquote><h3>What You’ll Learn</h3><p>In this article you’ll learn:</p><ul><li>What a moving sum is</li><li>How window functions make moving calculations possible</li><li>Why moving sums are useful for trend analysis</li><li>When to use ROWS BETWEEN</li></ul><p>Most reports start with simple totals.</p><pre>SELECT SUM(SalesAmount)<br>FROM SalesData;</pre><p>But eventually a different question appears:</p><blockquote><em>What has happened over the last 30 days?</em></blockquote><p>or:</p><blockquote><em>What is the rolling total over the last 30 transactions?</em></blockquote><p>That is where the Moving Sum Pattern becomes useful.</p><h3>The Problem</h3><p>Looking at individual rows often hides the bigger picture.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*5uaG9_y6fjgakCKKo7iaQA.png" /></figure><p>Individual values move up and down.</p><p>Sometimes what matters is the cumulative behavior over a recent window.</p><p>Questions such as:</p><ul><li>What were sales during the last 30 days?</li><li>How many errors occurred during the last 100 events?</li><li>What is the rolling total of customer purchases?</li></ul><p>require more context than a single row provides.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*NR0ADNDfXB0giCT8.png" /></figure><h3>The Moving Sum Pattern</h3><p>A moving sum calculates the total of the current row plus a specified number of previous rows.</p><p>For example:</p><pre>SUM(value) OVER (<br>    ORDER BY date<br>    ROWS BETWEEN 29 PRECEDING<br>         AND CURRENT ROW<br>)</pre><p>Conceptually this creates a window.</p><p>As each row is processed, the window moves forward.</p><p>Rows enter the window.</p><p>Older rows leave the window.</p><p>The calculation updates automatically.</p><h3>Example</h3><pre>SELECT<br>    date,<br>    value,<br>    SUM(value) OVER (<br>        ORDER BY date<br>        ROWS BETWEEN 29 PRECEDING<br>             AND CURRENT ROW<br>    ) AS moving_sum<br>FROM SalesData;</pre><p>This produces a rolling 30-row total.</p><p>Each result includes:</p><ul><li>the current row</li><li>the previous 29 rows</li></ul><p>The window moves forward one row at a time.</p><h3>Why This Pattern Matters</h3><p>Moving sums help reveal trends that individual rows often hide.</p><p>Instead of asking:</p><blockquote><em>What happened today?</em></blockquote><p>you begin asking:</p><blockquote><em>What has happened recently?</em></blockquote><p>This makes the pattern useful for:</p><ul><li>sales reporting</li><li>financial analysis</li><li>monitoring systems</li><li>operational dashboards</li><li>customer activity tracking</li></ul><p>The result is often smoother and easier to interpret than raw values alone.</p><h3>Window Functions Change Everything</h3><p>Many SQL developers first encounter moving sums when learning window functions.</p><p>Without window functions, moving calculations often require:</p><ul><li>self joins</li><li>correlated subqueries</li><li>temporary tables</li></ul><p>Window functions provide a cleaner solution.</p><p>The Moving Sum Pattern is one of the most common examples.</p><h3>A Note on Rows vs Dates</h3><p>One important detail:</p><pre>ROWS BETWEEN 29 PRECEDING</pre><p>means:</p><blockquote><em>Previous 29 rows</em></blockquote><p>not:</p><blockquote><em>Previous 29 days</em></blockquote><p>Those are different concepts.</p><p>If dates contain gaps, weekends, or missing records, row counts and date ranges may not align.</p><p>Always verify that the window matches the business requirement.</p><h3>When I Reach for This Pattern</h3><p>I typically use the Moving Sum Pattern when:</p><ul><li>I need rolling totals</li><li>I want to smooth noisy data</li><li>I need trend visibility</li><li>The analysis depends on recent activity</li></ul><p>Examples include:</p><ul><li>rolling sales totals</li><li>rolling transaction counts</li><li>rolling inventory movement</li><li>rolling customer activity</li></ul><h3>Key Takeaway</h3><p>Individual rows show events.</p><p>Moving sums show context.</p><p>The Moving Sum Pattern helps answer:</p><blockquote><em>What has happened recently?</em></blockquote><p>instead of:</p><blockquote><em>What happened on this row?</em></blockquote><p>That shift often makes trends easier to see and decisions easier to make.</p><h3>SQL Pattern Series</h3><p>This article is part of the <strong>SQL Pattern Series</strong>, a collection of practical SQL patterns that help developers recognize common problem-solving approaches found in reporting, analytics, and application development.</p><h3>SQL Bubble Pop</h3><p>If you are learning SQL or helping others learn SQL, I created <a href="https://apps.apple.com/us/app/sql-bubble-pop-sql-coding-game/id6744767120"><strong>SQL Bubble Pop</strong></a>, a mobile game that teaches SQL concepts through quick, interactive challenges and pattern recognition exercises.</p><p>The goal is simple:</p><blockquote><em>Learn SQL by recognizing patterns instead of memorizing syntax.</em></blockquote><p><em>Originally published at </em><a href="https://dev.to/baldwin_apps/sql-pattern-series-4-the-moving-sum-pattern-3ca2"><em>https://dev.to</em></a><em> on June 9, 2026.</em></p><p><em>Originally published at </em><a href="https://dev.to/baldwin_apps/sql-pattern-series-4-the-moving-sum-pattern-3ca2"><em>https://dev.to</em></a><em> on June 9, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a1141569f38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Pattern Series #3: The Missing Data Pattern]]></title>
            <link>https://medium.com/@tiye_78900/sql-pattern-series-3-the-missing-data-pattern-27919d8baa73?source=rss-8b514f478a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/27919d8baa73</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql-queries]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Tiye Baldwin-Anderson]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 14:39:44 GMT</pubDate>
            <atom:updated>2026-06-07T05:57:04.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kJe_as94btHIqHorsXPRMg.png" /></figure><p><em>Finding rows that disappear because of the wrong JOIN</em></p><blockquote><em>SQL Pattern Series #3 of 21</em></blockquote><blockquote><em>A collection of practical SQL patterns that help developers recognize common solutions to recurring database problems.</em></blockquote><h3>What You’ll Learn</h3><p>In this article you’ll learn:</p><ul><li>Why rows sometimes disappear unexpectedly</li><li>The difference between INNER JOIN and LEFT JOIN</li><li>How to identify missing related data</li><li>When to use the Missing Data Pattern</li></ul><p>Most SQL developers eventually encounter a report that looks wrong.</p><p>The numbers seem too low.</p><p>Rows appear to be missing.</p><p>And yet the query runs successfully.</p><p>Often the issue is not the data.</p><p>It’s the JOIN.</p><h3>The Question Behind the Query</h3><p>Many SQL queries involve combining information from multiple tables.</p><p>The key question becomes:</p><blockquote><em>Do I only want matching rows?</em></blockquote><p>or:</p><blockquote><em>Do I want all rows from one table, even when no match exists?</em></blockquote><p>Those questions lead to very different results.</p><h3>Matching Rows Only</h3><pre>INNER JOIN</pre><p>Returns only rows that exist in both tables.</p><h3>Keep All Rows</h3><pre>LEFT JOIN</pre><p>Returns all rows from the left table, even when no matching row exists in the right table.</p><p>Rows without a match return NULL values for the right-side columns.</p><h3>The Missing Data Pattern</h3><p>The Missing Data Pattern appears when data seems to have vanished from a result set.</p><p>In many cases, nothing is actually missing.</p><p>The query is simply filtering rows through an INNER JOIN.</p><p>Imagine a list of orders.</p><p>Some orders have matching customers.</p><p>Some do not.</p><p>An INNER JOIN only returns the orders with matching customer records.</p><p>The remaining rows disappear from the result.</p><p>A LEFT JOIN reveals those unmatched rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*r-Jtr6g5F-rkJU1t.png" /></figure><p>The image above summarizes the core idea:</p><ul><li>INNER JOIN returns only matching rows</li><li>LEFT JOIN keeps all rows from the left table</li><li>Missing matches appear as NULL</li><li>Sometimes the missing rows are the most important rows</li></ul><h3>Example Using INNER JOIN</h3><pre>SELECT o.OrderID,<br>       c.CustomerName<br>FROM Orders o<br>INNER JOIN Customers c<br>    ON o.CustomerID = c.ID;</pre><p>This query returns only orders that have a matching customer record.</p><p>Any order without a match is excluded.</p><p>Conceptually, SQL asks:</p><blockquote><em>Show me only the rows that exist in both tables.</em></blockquote><h3>Example Using LEFT JOIN</h3><pre>SELECT o.OrderID,<br>       c.CustomerName<br>FROM Orders o<br>LEFT JOIN Customers c<br>    ON o.CustomerID = c.ID;</pre><p>This query keeps every order.</p><p>If a matching customer does not exist, the customer columns return NULL.</p><p>Conceptually, SQL asks:</p><blockquote><em>Show me every order, whether a matching customer exists or not.</em></blockquote><h3>Why This Pattern Matters</h3><p>Many reporting problems are not caused by bad data.</p><p>They are caused by accidental filtering.</p><p>Developers often write an INNER JOIN without realizing that unmatched rows are being removed.</p><p>The Missing Data Pattern encourages you to ask:</p><ul><li>What rows am I losing?</li><li>Should unmatched rows be visible?</li><li>Is the absence of a match important information?</li></ul><p>Sometimes the missing rows are exactly what you’re trying to find.</p><h3>A Note on Investigation</h3><p>When a report seems incomplete, one of the first things I check is the JOIN type.</p><p>A quick comparison between:</p><pre>INNER JOIN</pre><p>and</p><pre>LEFT JOIN</pre><p>can often reveal whether rows are being filtered unintentionally.</p><p>This is especially useful when troubleshooting:</p><ul><li>incomplete reports</li><li>missing customers</li><li>orphaned records</li><li>failed imports</li><li>data quality issues</li></ul><h3>When I Reach for This Pattern</h3><p>I often think about the Missing Data Pattern when I need to find:</p><ul><li>customers without orders</li><li>orders without customers</li><li>employees without managers</li><li>products without sales</li><li>records missing related data</li></ul><p>In these situations, the absence of a relationship is often the most valuable information.</p><h3>Key Takeaway</h3><p>When data seems to disappear, ask:</p><blockquote><em>Is the data actually missing?</em></blockquote><p>or:</p><blockquote><em>Is my JOIN hiding it?</em></blockquote><p>Sometimes changing:</p><pre>INNER JOIN</pre><p>to:</p><pre>LEFT JOIN</pre><p>completely changes what you discover.</p><p>And sometimes the missing rows are the story.</p><h3>SQL Pattern Series</h3><p>This article is part of the <strong>SQL Pattern Series</strong>, a collection of practical SQL patterns that help developers recognize common problem-solving approaches found in reporting, analytics, and application development.</p><h3>SQL Bubble Pop</h3><p>If you are learning SQL or helping others learn SQL, I created <a href="https://apps.apple.com/us/app/sql-bubble-pop-sql-coding-game/id6744767120"><strong>SQL Bubble Pop</strong></a>, a mobile game that teaches SQL concepts through quick, interactive challenges and pattern recognition exercises.</p><p>The goal is simple:</p><blockquote><em>Learn SQL by recognizing patterns instead of memorizing syntax.</em></blockquote><p><em>Originally published at </em><a href="https://dev.to/baldwin_apps/sql-pattern-series-3-the-missing-data-pattern-411e"><em>https://dev.to</em></a><em> on June 6, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27919d8baa73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Pattern Series #2: The Match Pattern]]></title>
            <link>https://medium.com/@tiye_78900/sql-pattern-series-2-the-match-pattern-252ff892f72a?source=rss-8b514f478a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/252ff892f72a</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Tiye Baldwin-Anderson]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 16:31:11 GMT</pubDate>
            <atom:updated>2026-06-07T05:51:16.031Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OrPOtpgHzM3bcze-3iiEmg.png" /><figcaption><em>Choosing between exact matches and pattern matches</em></figcaption></figure><p><em>Choosing between exact matches and pattern matches</em></p><blockquote><em>SQL Pattern Series #2 of 21</em></blockquote><blockquote><em>A collection of practical SQL patterns that help developers recognize common solutions to recurring database problems.</em></blockquote><h3>What You’ll Learn</h3><p>In this article you’ll learn:</p><ul><li>The difference between exact matching and pattern matching</li><li>When to use =</li><li>When to use LIKE</li><li>Why a small operator change can change the meaning of a query</li></ul><p>Most SQL developers run into this distinction eventually.</p><p>= and LIKE solve different problems.</p><p>= checks for an exact value.</p><p>LIKE checks whether a value fits a pattern.</p><p>That difference matters when the question changes from:</p><blockquote><em>Is this exactly Admin?</em></blockquote><p>to:</p><blockquote><em>Does this start with Admin?</em></blockquote><p>The image above summarizes the core idea:</p><ul><li>= asks whether a value is exactly equal.</li><li>LIKE asks whether a value matches a pattern.</li><li>Both are useful, but they answer different questions.</li></ul><h3>Exact Match Example</h3><p>Use = when the value must match exactly.</p><pre>SELECT *<br>FROM Users<br>WHERE Role = &#39;Admin&#39;;</pre><p>This query asks:</p><blockquote><em>Is the role exactly </em><em>Admin?</em></blockquote><p>It will match:</p><pre>Admin</pre><p>But it will not match:</p><pre>AdminAssistant<br>Administrator<br>SuperAdmin</pre><p>That is the point.</p><p>The = operator is precise.</p><h3>Pattern Match</h3><p>Use LIKE when the value may vary but still follows a recognizable pattern.</p><pre>SELECT *<br>FROM Users<br>WHERE Role LIKE &#39;Admin%&#39;;</pre><p>This query asks:</p><blockquote><em>Does the role start with </em><em>Admin?</em></blockquote><p>It may match values like:</p><pre>Admin<br>AdminAssistant<br>Administrator</pre><p>The % wildcard means:</p><blockquote><em>Any number of characters may appear here.</em></blockquote><p>So Admin% means:</p><blockquote><em>Starts with </em><em>Admin.</em></blockquote><h3>The Match Pattern</h3><p>The <strong>Match Pattern</strong> is about choosing the right kind of comparison for the question being asked.</p><p>Sometimes you need precision.</p><p>Sometimes you need flexibility.</p><p>The pattern is simple:</p><ul><li>Use = for exact matches</li><li>Use LIKE for pattern-based matches</li></ul><p>But the effect can be significant.</p><p>A query that is too strict may miss valid rows.</p><p>A query that is too broad may return rows you did not intend to include.</p><h3>Why This Pattern Matters</h3><p>This distinction shows up in many real-world queries.</p><p>For example:</p><ul><li>Find one exact status</li><li>Find names that start with a prefix</li><li>Find emails from a specific domain</li><li>Find product codes with a shared pattern</li><li>Find log messages containing a phrase</li></ul><p>Each of these questions requires a different kind of match.</p><h3>Common Examples</h3><h3>Exact status match</h3><pre>SELECT *<br>FROM Orders<br>WHERE Status = &#39;Pending&#39;;</pre><p>This asks for orders where the status is exactly Pending.</p><h3>Prefix match</h3><pre>SELECT *<br>FROM Users<br>WHERE Username LIKE &#39;test%&#39;;</pre><p>This asks for usernames that start with test.</p><h3>Contains match</h3><pre>SELECT *<br>FROM Products<br>WHERE ProductName LIKE &#39;%keyboard%&#39;;</pre><p>This asks for product names that contain keyboard anywhere in the value.</p><h3>Suffix match</h3><pre>SELECT *<br>FROM Customers<br>WHERE Email LIKE &#39;%@example.com&#39;;</pre><p>This asks for email addresses that end with @example.com.</p><h3>A Note on Performance</h3><p>Pattern matching can be powerful, but it can also affect performance.</p><p>For example:</p><pre>WHERE Username LIKE &#39;Admin%&#39;</pre><p>may be easier for a database to optimize because the pattern has a fixed beginning.</p><p>But this:</p><pre>WHERE Username LIKE &#39;%Admin%&#39;</pre><p>can be more expensive because the database may need to search inside the value rather than starting from the beginning.</p><p>The exact behavior depends on:</p><ul><li>the database system</li><li>indexes</li><li>collation settings</li><li>data size</li><li>query plan</li></ul><p>As always, validate assumptions with real execution plans and real workloads.</p><h3>When I Reach for This Pattern</h3><p>I typically use = when:</p><ul><li>I need one exact value</li><li>The column contains controlled values</li><li>The comparison should be strict</li><li>The query should not include partial matches</li></ul><p>I typically use LIKE when:</p><ul><li>I need prefix matching</li><li>I need suffix matching</li><li>I need contains matching</li><li>The data is text-based and variable</li><li>I am intentionally searching for a pattern</li></ul><h3>Key Takeaway</h3><p>Small operator difference.</p><p>Very different behavior.</p><p>When writing SQL, ask:</p><blockquote><em>Am I looking for an exact value?</em></blockquote><p>or:</p><blockquote><em>Am I looking for a pattern?</em></blockquote><p>That question determines whether the query should use = or LIKE.</p><p>The better you understand the match you need, the easier it becomes to write queries that return the right rows.</p><h3>SQL Pattern Series</h3><p>This article is part of the <strong>SQL Patterns</strong> series, a collection of practical SQL patterns that help developers recognize common problem-solving approaches found in reporting, analytics, and application development.</p><p>Previous article:</p><ul><li>SQL Pattern Series #1: The Presence Pattern</li></ul><h3>SQL Bubble Pop</h3><p>If you are learning SQL or helping others learn SQL, I created <a href="https://apps.apple.com/us/app/sql-bubble-pop-sql-coding-game/id6744767120"><strong>SQL Bubble Pop</strong></a>, a mobile game that teaches SQL concepts through quick, interactive challenges and pattern recognition exercises.</p><p>The goal is simple:</p><blockquote><em>Learn SQL by recognizing patterns instead of memorizing syntax.</em></blockquote><p><em>Originally published at </em><a href="https://dev.to/baldwin_apps/sql-pattern-series-2-the-match-pattern-4716"><em>https://dev.to</em></a><em> on June 2, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=252ff892f72a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Pattern Series #1: The Presence Pattern]]></title>
            <link>https://medium.com/@tiye_78900/sql-pattern-series-1-the-presence-pattern-7bb87df3da92?source=rss-8b514f478a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bb87df3da92</guid>
            <category><![CDATA[sql-queries]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Tiye Baldwin-Anderson]]></dc:creator>
            <pubDate>Sat, 30 May 2026 03:27:42 GMT</pubDate>
            <atom:updated>2026-05-31T09:16:23.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Infographic showing SQL EXISTS vs IN operators. EXISTS checks if any row exists; IN checks if a value is in a list. Code example shows SELECT * FROM Customers c WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.CustomerID = c.CustomerID)." src="https://cdn-images-1.medium.com/max/1024/0*hWh6hCetxOUZb-jA.png" /><figcaption>SQL Pattern #1: Use EXISTS when checking for related rows in another table, and IN when matching against a known list of values.</figcaption></figure><blockquote>Thinking in terms of existence instead of lists</blockquote><blockquote><em>SQL Pattern Series #1 of 21</em></blockquote><blockquote><em>A collection of practical SQL patterns that help developers recognize common solutions to recurring database problems.</em></blockquote><h3>What You’ll Learn</h3><p>In this article you’ll learn:</p><ul><li>When EXISTS and IN solve the same problem</li><li>The difference between set membership and existence</li><li>Why the underlying mental model matters</li><li>When I typically reach for EXISTS</li></ul><p>Most SQL developers write a query like this at some point:</p><pre>SELECT c.CustomerID,<br>       c.CustomerName<br>FROM Customers c<br>WHERE c.CustomerID IN (<br>    SELECT o.CustomerID<br>    FROM Orders o<br>);</pre><p>And it works.</p><p>But sometimes it isn’t the best way to think about the problem.</p><h3>The Question Behind the Query</h3><p>Many SQL problems can be framed in two different ways.</p><h3>Set Membership</h3><blockquote><em>Is this value in a set?</em></blockquote><pre>WHERE CustomerID IN (...)</pre><h3>Existence</h3><blockquote><em>Does at least one matching row exist?</em></blockquote><pre>WHERE EXISTS (...)</pre><p>Both approaches often return the same result.</p><p>But they represent different mental models.</p><h3>The Presence Pattern</h3><p>The <strong>Presence Pattern</strong> is useful when you do not actually care about the values being returned from a related table.</p><p>You only care whether a matching row exists.</p><p>For example:</p><ul><li>Customers who have placed an order</li><li>Users who have logged in</li><li>Employees assigned to a project</li><li>Products that have sales</li></ul><p>In these cases, the question is often:</p><blockquote><em>Does a related row exist?</em></blockquote><p>rather than:</p><blockquote><em>What values are contained in this list?</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JT1y7GzPTHE5G-iaqBx_gg.png" /></figure><p>The image above summarizes the core idea:</p><ul><li>EXISTS asks whether at least one matching row exists</li><li>IN checks whether a value belongs to a set</li><li>Both often return the same result</li><li>The difference is usually the mental model</li></ul><h3>Example Using EXISTS</h3><pre>SELECT c.CustomerID,<br>       c.CustomerName<br>FROM Customers c<br>WHERE EXISTS (<br>    SELECT 1<br>    FROM Orders o<br>    WHERE o.CustomerID = c.CustomerID<br>);</pre><p>The subquery is correlated to the outer query.</p><p>Conceptually, SQL asks:</p><blockquote><em>For this customer, does at least one matching order exist?</em></blockquote><p>As soon as the answer becomes true, the condition is satisfied.</p><h3>Why This Pattern Matters</h3><p>Many SQL developers initially learn syntax.</p><p>Over time, they discover that query writing is really about choosing the right mental model.</p><p>The Presence Pattern encourages you to think in terms of:</p><ul><li>existence</li><li>relationships</li><li>matching rows</li></ul><p>instead of building lists unnecessarily.</p><p>That shift often makes queries easier to reason about.</p><h3>A Note on Performance</h3><p>Modern database optimizers are extremely sophisticated.</p><p>In many systems, IN and EXISTS may be rewritten into similar execution plans.</p><p>As a result:</p><blockquote><em>The same result does not necessarily mean the same execution strategy.</em></blockquote><p>And the same syntax does not necessarily mean different performance.</p><p>Always validate assumptions with execution plans and real-world testing.</p><p>The value of this pattern is primarily conceptual:</p><ul><li>existence vs. membership</li><li>relationship vs. list</li><li>presence vs. values</li></ul><h3>When I Reach for This Pattern</h3><p>I typically consider EXISTS when:</p><ul><li>I only need to know whether related data exists</li><li>The subquery may return many rows</li><li>The relationship itself is the focus of the query</li><li>I want the query to communicate intent clearly</li></ul><p>Examples include:</p><ul><li>customers with orders</li><li>users with activity</li><li>products with transactions</li><li>accounts with associated records</li></ul><h3>Key Takeaway</h3><p>Many SQL problems become easier when you ask:</p><blockquote><em>Do I need the values?</em></blockquote><p>or:</p><blockquote><em>Do I simply need to know whether they exist?</em></blockquote><p>That small distinction changes how you think about the query.</p><p>And sometimes, changing how you think about the problem is more important than changing the syntax.</p><h3>SQL Pattern Series</h3><p>This article is part of the <strong>SQL Pattern Series</strong>, a collection of practical SQL patterns that help developers recognize common problem-solving approaches found in reporting, analytics, and application development.</p><h3>SQL Bubble Pop</h3><p>If you are learning SQL or helping others learn SQL, I created <a href="https://apps.apple.com/us/app/sql-bubble-pop-sql-coding-game/id6744767120"><strong>SQL Bubble Pop</strong></a>, a mobile game that teaches SQL concepts through quick, interactive challenges and pattern recognition exercises.</p><p>The goal is simple:</p><blockquote><em>Learn SQL by recognizing patterns instead of memorizing syntax.</em></blockquote><p><em>Originally published at </em><a href="https://dev.to/baldwin_apps/sql-pattern-series-1-the-presence-pattern-a5f"><em>https://dev.to</em></a><em> on May 30, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bb87df3da92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Before SQL, We Had to Tell Computers Everything. Then One Idea Changed That Forever.]]></title>
            <link>https://medium.com/@tiye_78900/before-sql-we-had-to-tell-computers-everything-then-one-idea-changed-that-forever-aa205418c18d?source=rss-8b514f478a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa205418c18d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Tiye Baldwin-Anderson]]></dc:creator>
            <pubDate>Thu, 28 May 2026 18:10:16 GMT</pubDate>
            <atom:updated>2026-05-28T18:10:16.000Z</atom:updated>
            <content:encoded><![CDATA[<p>The shift from procedural to declarative thinking didn’t just change databases — it changed how we reason about problems.</p><figure><img alt="Side-by-side infographic comparing procedural data access with SQL. The left side, labeled “The Old Way,” shows a dark vintage computer monitor displaying a multi-line T-SQL cursor script with steps: Get Data, Check Condition, Process Row, Store Result, Repeat — with callouts noting manual processing, more code, more time, and more risk. The right side, labeled “The SQL Way,” shows a modern monitor displaying a three-line SELECT query against a clean bright background." src="https://cdn-images-1.medium.com/max/1024/1*QsYTqhXFfSYsrxYgT2pptQ.png" /><figcaption>Before SQL, retrieving data required writing out every step manually: declare variables, open a cursor, loop through each row, check conditions, store results, repeat. SQL replaced all of that with a single declarative query. The shift wasn’t just about less code — it was about moving from instructions to intent.</figcaption></figure><p>Here’s something most SQL tutorials skip entirely:</p><p>SQL wasn’t just a new syntax. It was a new <em>way of thinking</em>.</p><p>Before SQL existed, most systems were built around procedural programming. You didn’t describe a result — you described every step to get there. Fetch the data. Check a condition. Process row by row. Loop again. Handle the edge cases. Store the result. Repeat.</p><p>It worked. But it was exhausting. And fragile. And hard to scale.</p><p>Then SQL introduced an idea that sounds almost too simple:</p><p><strong>Tell the system what you want — not how to do it.</strong></p><h3>The Old Way Was Expensive</h3><p>Procedural data access put all the cognitive weight on the developer. You were responsible for:</p><ul><li>Deciding how to traverse the data</li><li>Managing every loop and condition manually</li><li>Anticipating performance edge cases</li><li>Writing code that was tightly coupled to <em>how</em> the data was stored</li></ul><p>Change the storage structure, and your code broke. Add more records, and your performance tanked. It scaled poorly in both directions — complexity and volume.</p><p>The database engine knew things about the data that you didn’t. But you weren’t allowed to use that knowledge. You had to do it yourself, row by row, the hard way.</p><h3>One Query. A Radically Different Contract.</h3><pre>SELECT *<br>FROM customers<br>WHERE balance &gt; 1000;</pre><p>That’s it. No loops. No manual traversal. No step-by-step instruction manual.</p><p>You described the <em>outcome</em>. The database figured out the <em>path</em>.</p><p>That’s not a small thing. That’s a complete inversion of the relationship between the developer and the system.</p><p>With SQL, you stopped being the engine and started being the director. You tell the system what matters. The query optimizer decides how to get there — what index to use, what join order makes sense, what execution plan fits the data.</p><p>More power. Less code. More room to focus on <em>what the problem actually is</em>.</p><h3>Why This Still Matters in 2025</h3><p>You might think this is ancient history — SQL is nearly 50 years old at this point. But the shift it introduced isn’t historical trivia.</p><p>Every modern analytics dashboard you’ve ever seen is built on it. Every reporting pipeline. Every business intelligence tool. Every time a developer writes a query to answer a business question, they’re standing on that original insight: <em>describe the result, let the system do the work.</em></p><p>The declarative mindset also spread far beyond SQL. It shaped how we think about CSS (describe the layout, not the pixel math), how React works (describe the UI state, not the DOM manipulation), how infrastructure-as-code tools like Terraform operate.</p><p>SQL was influential beyond databases. It was a template for how humans could collaborate with computers more effectively.</p><h3>The Mindset Shift Is the Point</h3><p>This is why I always tell new learners: SQL isn’t really about memorizing syntax. The syntax is a few keywords. You can look those up.</p><p>The deeper skill is learning to think in outcomes.</p><p>What result do you need? What does the data look like? What shape do you want the answer in? Let the engine worry about the how.</p><p>That’s a trainable skill. And once it clicks, it changes the way you approach problems — not just in databases, but everywhere you interact with systems.</p><h3>You Can Practice This Right Now</h3><p>If you’ve been avoiding SQL because it feels technical or gatekept, I want to offer a different frame:</p><p>SQL is one of the most <em>human-readable</em> languages we have. You’re not writing machine code. You’re describing what you want in something close to plain English. “Select all customers where their balance is greater than 1000” — that <em>is</em> the query, almost word for word.</p><p>The barrier is lower than it looks. The mental model is the thing worth building.</p><p>Start there. The syntax will follow.</p><p><em>Tiye Baldwin-Anderson is the founder of </em><a href="https://baldwinapps.com/"><em>Baldwin Apps LLC</em></a><em> and the creator of </em><a href="https://apps.apple.com/us/app/sql-bubble-pop-sql-coding-game/id6744767120"><em>SQL Bubble Pop</em></a><em>, a gamified iOS app for learning SQL through play. She writes about SQL, tech literacy, and building things that make learning feel like a game.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa205418c18d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where Did My Data Go? Five SQL Outcomes That Surprise Almost Everyone]]></title>
            <link>https://medium.com/@tiye_78900/where-did-my-data-go-five-sql-outcomes-that-surprise-almost-everyone-ad911228adbf?source=rss-8b514f478a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad911228adbf</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Tiye Baldwin-Anderson]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 20:38:15 GMT</pubDate>
            <atom:updated>2026-04-24T20:38:15.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A SQL Tip of the Day infographic titled “The Missing Data Pattern.” Two sections compare INNER JOIN and LEFT JOIN using Venn diagrams, data tables, and result sets. The INNER JOIN section shows an Orders table with four rows (OrderIDs 1–4) joined to a Customers table, with a blue and green Venn diagram labeled Returned and Dropped — the result shows only three matching rows: Alice, Bob, and Charlie. The LEFT JOIN section shows the same Orders table with a gold and green Venn diagram keeping all" src="https://cdn-images-1.medium.com/max/1024/1*kJe_as94btHIqHorsXPRMg.png" /><figcaption>INNER JOIN keeps only what matches. LEFT JOIN shows you what doesn’t, including the rows you didn’t know were missing.</figcaption></figure><p>You ran the query. You expected results. And then — nothing. Or not enough. Or way too many rows, and none of them look right.</p><p>If you’ve spent time with SQL, you’ve been here. The query isn’t broken. The database isn’t lying. But something happened between what you intended and what came back — and figuring out what can feel like detective work.</p><p>This article is about five of the most common “where did my data go?” moments in SQL, why they happen, and how to find your way back.</p><h3>1. The Silent Drop: INNER JOIN</h3><p>This is the most common source of mysteriously missing rows — and it’s especially disorienting because the query runs without errors. It just quietly leaves data behind.</p><p>An INNER JOIN returns only rows that have a match in both tables. If a row in your left table has no corresponding row in the right table, it’s dropped from the result entirely. No warning. No NULL. Just gone.</p><pre>-- This looks reasonable...<br>SELECT o.OrderID, c.CustomerName<br>FROM Orders o<br>INNER JOIN Customers c<br>    ON o.CustomerID = c.ID;</pre><p>If Orders has a row where CustomerID = 104 and there’s no matching customer with ID = 104 in the Customers table, that order simply doesn’t appear in the results.</p><p><strong>How to find the missing rows:</strong></p><p>Switch to a LEFT JOIN and filter for NULLs on the right side:</p><pre>SELECT o.OrderID, c.CustomerName<br>FROM Orders o<br>LEFT JOIN Customers c<br>    ON o.CustomerID = c.ID<br>WHERE c.ID IS NULL;</pre><p>Any row where c.ID comes back NULL is a row that had no match. That&#39;s your missing data — and now you can see it.</p><p><strong>The pro tip:</strong> If your result set is smaller than you expected after a JOIN, LEFT JOIN + IS NULL is the first diagnostic to reach for. It shows you exactly what got dropped and why.</p><p><em>This behavior is consistent across SQL Server, MySQL, PostgreSQL, and Oracle.</em></p><h3>2. The NULL That Doesn’t Match Anything</h3><p>This one shows up constantly in real-world data — and it’s connected to a fundamental rule about how SQL handles NULL that trips people up until it clicks.</p><p>In SQL, NULL means unknown. And because of that, NULL is never considered equal to anything — including another NULL. So if you try to filter for missing values using =, you get nothing back.</p><pre>-- This returns zero rows, even if NULLs exist<br>SELECT *<br>FROM Customers<br>WHERE Email = NULL;</pre><p>The database isn’t broken. It’s just that = NULL always evaluates to unknown, never true. The filter never matches.</p><p>What you need instead:</p><pre>-- This returns rows where Email has no value<br>SELECT *<br>FROM Customers<br>WHERE Email IS NULL;</pre><p>IS NULL is specifically designed to check for the absence of a value. It&#39;s the only reliable way to find NULL rows.</p><p><strong>The related gotcha:</strong> The same rule applies in the opposite direction. != NULL won&#39;t find non-null rows either — you need IS NOT NULL.</p><p><strong>How to find the missing rows:</strong></p><p>If your filter isn’t returning what you expect, check whether the column contains NULLs and whether you’re using = or IS NULL correctly. A quick SELECT COUNT(*) WHERE column IS NULL tells you immediately whether NULLs are in play.</p><p><em>This behavior is consistent across SQL Server, MySQL, PostgreSQL, and Oracle.</em></p><h3>3. The Filter That Fired Too Early</h3><p>This one is subtle — and it produces results that look plausible but aren’t quite right, which makes it harder to spot than an empty result set.</p><p>The issue is the difference between WHERE and HAVING, and when each one runs.</p><p>WHERE filters rows <em>before</em> they&#39;re grouped. HAVING filters groups <em>after</em> aggregation. If you use WHERE to filter on an aggregated value, you get an error. But if you use WHERE in a way that accidentally excludes rows before they reach the aggregation, you get silently wrong results.</p><pre>-- Intended: departments with more than 5 active employees<br>-- Problem: WHERE filters BEFORE grouping,<br>-- so inactive employees are excluded from the count entirely<br>SELECT department_id, COUNT(*) AS total<br>FROM employees<br>WHERE status = &#39;active&#39;<br>GROUP BY department_id<br>HAVING COUNT(*) &gt; 5;</pre><p>Whether that’s the right query depends on what you’re actually asking. If you want departments where more than five <em>total</em> employees exist, the WHERE clause is filtering out the inactive ones before the count runs — and your totals will be lower than you expect.</p><p><strong>How to find the issue:</strong></p><p>Remove the WHERE clause temporarily and compare the counts. If the numbers change in a way that surprises you, the WHERE is filtering data you didn’t mean to exclude at that stage.</p><p>The fix is usually moving the condition to HAVING, or restructuring the query to be explicit about what gets filtered before vs after grouping.</p><p><em>This behavior is consistent across SQL Server, MySQL, PostgreSQL, and Oracle.</em></p><h3>4. The DISTINCT That Ate Your Duplicates</h3><p>Sometimes data goes missing not because of a JOIN or a NULL, but because something upstream in the query removed rows you actually needed.</p><p>DISTINCT is the most common culprit. It&#39;s easy to add to a query to clean up results — and easy to forget that it&#39;s there, or to apply it at the wrong level.</p><pre>-- This removes ALL duplicate rows across all selected columns<br>SELECT DISTINCT CustomerID, OrderDate<br>FROM Orders;</pre><p>If a customer placed two orders on the same date, DISTINCT collapses them into one row. If you were counting orders, your count is now wrong. If you were auditing for duplicates, you&#39;ve just hidden the very thing you were looking for.</p><p><strong>The related scenario:</strong> DISTINCT applied inside a COUNT affects what gets counted:</p><pre>-- Counts unique customers, not total orders<br>SELECT COUNT(DISTINCT CustomerID) FROM Orders;<br><br>-- Counts total orders<br>SELECT COUNT(*) FROM Orders;</pre><p>Both are valid — but they answer different questions. The confusion happens when you use one and expect the other.</p><p><strong>How to find the issue:</strong></p><p>If your row count is lower than expected, check whether DISTINCT appears anywhere in the query — including in subqueries or CTEs further up the chain. Remove it temporarily and compare counts.</p><p><em>This behavior is consistent across SQL Server, MySQL, PostgreSQL, and Oracle.</em></p><h3>5. The Data That Can’t Come Back</h3><p>This one is less about a query behaving unexpectedly and more about an operation that behaves exactly as designed — just not in the way you anticipated.</p><p>TRUNCATE removes every row from a table. Unlike DELETE, which logs individual row removals and can typically be rolled back, TRUNCATE is a DDL operation in most databases. It auto-commits. And in many databases, that means once it runs, the data is gone.</p><pre>-- In many databases, this cannot be rolled back<br>TRUNCATE TABLE staging_orders;</pre><p>This shows up most often in ETL workflows and data refresh processes, where someone runs a TRUNCATE to clear a staging table before reloading it — and something goes wrong between the truncate and the reload.</p><p><strong>The diagnostic question:</strong></p><p>If data disappeared from an entire table rather than specific rows, and there’s no WHERE clause that could explain it, TRUNCATE is the first thing to check in the query history or execution logs.</p><p><strong>The prevention habit:</strong></p><p>In development and staging environments, wrap destructive operations in explicit transactions where your database supports it. In SQL Server, TRUNCATE can be rolled back inside an explicit transaction. In MySQL and Oracle, it typically cannot.</p><pre>-- SQL Server only: TRUNCATE inside a transaction can be rolled back<br>BEGIN TRANSACTION;<br>TRUNCATE TABLE staging_orders;<br><br>-- Verify before committing<br>ROLLBACK; -- or COMMIT if everything looks right</pre><p><em>For a full breakdown of </em><a href="https://medium.com/@tiye_78900/truncate-vs-delete-the-sql-difference-worth-knowing-cold-4c81cc0afc2b"><em>TRUNCATE vs DELET</em></a><em>E behavior across databases, see the </em><a href="https://medium.com/@tiye_78900/truncate-vs-delete-the-sql-difference-worth-knowing-cold-4c81cc0afc2b"><em>earlier article</em></a><em> in this series.</em></p><h3>The Common Thread</h3><p>Each of these scenarios shares the same underlying dynamic: the database did exactly what the SQL told it to do. The gap was between the instruction and the intent.</p><p>That gap closes with experience — with seeing enough queries, debugging enough unexpected results, and building the habit of asking <em>why</em> a result looks the way it does rather than just accepting it.</p><p>A few diagnostic habits worth building:</p><ul><li>When results are smaller than expected: check your JOINs first, then your WHERE clauses</li><li>When a filter returns nothing: check for NULLs and confirm you’re using IS NULL correctly</li><li>When counts don’t add up: look for DISTINCT anywhere in the query chain</li><li>When an entire table is empty: check execution logs for TRUNCATE operations</li></ul><p>SQL becomes more predictable once you know where the surprises tend to hide.</p><p><a href="https://apps.apple.com/us/app/sql-bubble-pop-sql-coding-game/id6744767120">SQL Bubble Pop</a> covers the query patterns, filtering logic, and active recall that helps these concepts become reflexes rather than things you have to look up every time.</p><p><strong>Download </strong><a href="https://apps.apple.com/us/app/sql-bubble-pop-sql-coding-game/id6744767120"><strong>SQL Bubble Pop</strong></a><strong> free on the App Store.</strong> Search “SQL Bubble Pop.”</p><h3>TL;DR</h3><figure><img alt="A dark navy “Where Did My Data Go? · TL;DR” reference graphic with five numbered items. Item 01, The Silent Drop: INNER JOIN silently drops unmatched rows — use LEFT JOIN + IS NULL to find what’s missing. Item 02, The NULL That Doesn’t Match: = NULL never works — use IS NULL and IS NOT NULL to filter for missing values. Item 03, The Filter That Fired Too Early: WHERE fires before grouping — use HAVING to filter on aggregated values. Item 04, The DISTINCT That Ate Your Duplicates: …" src="https://cdn-images-1.medium.com/max/840/1*W71MdJjfgTWtiC9TSPcOXw.png" /><figcaption>Five reasons your SQL results don’t look the way you expected — and how to find what went missing.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad911228adbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Isn’t About Syntax — It’s About Patterns]]></title>
            <link>https://medium.com/@tiye_78900/sql-isnt-about-syntax-it-s-about-patterns-47129d8636f4?source=rss-8b514f478a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/47129d8636f4</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tiye Baldwin-Anderson]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 04:20:13 GMT</pubDate>
            <atom:updated>2026-04-22T04:20:13.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A cinematic retro Miami-style graphic titled “SQL Isn’t About Syntax — It’s About Patterns.” A developer in a Hawaiian shirt sits at a desk working at a monitor displaying a SQL query joining employees and departments tables filtered by salary, with a result set showing names, departments, and salaries. A coffee mug reads “Data &gt; Instinct &gt; Results.” A notepad reads “Filter. Join. Aggregate. Repeat.” A book reads “Think in Patterns.” A neon billboard in the background reads “Data is Power.”" src="https://cdn-images-1.medium.com/max/1024/1*c6KSTr5p6gSh57DE-4IlJQ.png" /><figcaption>SQL becomes much clearer when you start to see the patterns behind the queries.</figcaption></figure><p>There’s a reason SQL can feel frustrating even after you’ve watched tutorials, read documentation, and practiced on your own.</p><p>Most approaches to learning SQL teach commands.</p><p>Memorize SELECT.</p><p>Memorize JOIN.</p><p>Memorize GROUP BY.</p><p>And then, when something doesn’t work, go back and memorize more syntax.</p><p>The problem is that memorization isn’t the same as understanding. And without understanding, every new query feels like starting from scratch.</p><p>Here’s the shift that tends to make things click:</p><p>SQL isn’t a collection of commands to remember.</p><p>It’s a set of patterns to recognize.</p><p>Once you start seeing the patterns, queries become easier to read, easier to write, and much easier to debug.</p><p>If you’re working with SQL — or getting started with it — these seven patterns are worth knowing.</p><h3>Pattern 1: Filter Then Shape</h3><p>Almost every SQL query follows the same basic flow, even when it doesn’t look like it:</p><pre>SELECT columns<br>FROM table<br>WHERE filter_conditions;</pre><p>The order of execution matters here — and it’s not the order the clauses are written.</p><p>The database starts with FROM (get the data), applies WHERE (narrow it down), and then processes SELECT (decide what to show). Understanding that sequence helps you reason about why a query returns what it returns.</p><p>A practical example:</p><pre>SELECT name, salary<br>FROM employees<br>WHERE salary &gt; 100000;</pre><p>You’re not writing SQL for its own sake. You’re answering a question:</p><p><em>Which employees make more than $100,000?</em></p><p>The pattern is just the structure that lets you ask it.</p><p>Most queries — even complex ones — are built on this foundation. Everything else is an extension of it.</p><h3>Pattern 2: The Relationship Pattern</h3><p>JOINs are where a lot of people get stuck, and it’s usually because the focus lands on the syntax rather than the intent.</p><p>A JOIN answers one question:</p><p>H<em>ow are these two datasets related?</em></p><pre>SELECT e.name, d.department_name<br>FROM employees e<br>JOIN departments d<br>    ON e.department_id = d.id;</pre><p>If you read the ON clause as the relationship rule, &quot;connect employees to departments where the department IDs match&quot;, the rest of the syntax follows naturally.</p><p>The table on the left is your starting point.</p><p>The table on the right is what you&#39;re looking up.</p><p>The ON condition is the bridge between them.</p><p>Once the relationship is clear, the syntax stops feeling arbitrary.</p><h3>Pattern 3: The Accidental Explosion</h3><p>This one is worth knowing early because it’s one of the most common real-world SQL mistakes.</p><p>If you write a JOIN without an ON condition:</p><pre>SELECT *<br>FROM employees e<br>JOIN departments d;</pre><p>You don’t get a smart match. You get every possible combination of every row from both tables — what’s called a Cartesian product.</p><p>One hundred employees joined to ten departments produces one thousand rows. On larger tables, this can produce millions of rows and bring a query to its knees.</p><p>The pattern to recognize:</p><p><em>If your result set is dramatically larger than you expected, a missing or incorrect JOIN condition is the first place to look.</em></p><h3>Pattern 4: The Aggregation Pattern</h3><p>When you need summaries instead of raw rows, the aggregation pattern is what you reach for:</p><pre>SELECT department_id, COUNT(*) AS total<br>FROM employees<br>GROUP BY department_id;</pre><p>The mental model here is simple: group the data by some category, then apply a calculation to each group. COUNT, SUM, AVG, MIN, MAX — these all follow the same structure.</p><p>One thing worth knowing: WHERE filters rows before grouping, and HAVING filters groups after aggregation.</p><p>If you need to filter on an aggregated value, for example, only departments with more than ten employees , useHAVING, not WHERE.</p><pre>SELECT department_id, COUNT(*) AS total<br>FROM employees<br>GROUP BY department_id<br>HAVING COUNT(*) &gt; 10;</pre><h3>Pattern 5: The Ranking Pattern</h3><p>This is where SQL starts to feel genuinely powerful.</p><p>Window functions let you add context to each row without collapsing the result set the way GROUP BY does. Instead of summarizing, you&#39;re annotating.</p><pre>SELECT<br>    name,<br>    salary,<br>    ROW_NUMBER() OVER (ORDER BY salary DESC) AS rank<br>FROM employees;</pre><p>Every row stays in the result. Each one just gets an additional piece of information — in this case, its rank by salary.</p><p>The pattern:</p><p><em>Keep all rows, but give each one context about where it sits relative to the others.</em></p><p>Once that clicks, RANK, DENSE_RANK, LAG, LEAD, and PARTITION BY all start to make sense as variations on the same idea.</p><h3>Pattern 6: The Missing Data Pattern</h3><p>Real-world data is rarely clean. Columns have NULLs. Expected values are absent. Queries that work perfectly on tidy sample data behave unexpectedly on production data.</p><p>COALESCE is one of the most useful tools for handling this:</p><pre>SELECT name, COALESCE(bonus, 0) AS bonus<br>FROM employees;</pre><p>The pattern:</p><p>I<em>f this value is NULL, substitute something usable instead.</em></p><p>COALESCE returns the first non-NULL value from its list of arguments, which makes it flexible for a range of substitution scenarios.</p><p>Worth knowing alongside it: NULLIF (returns NULL if two values are equal — useful for avoiding division by zero) and ISNULL / IFNULL depending on your database.</p><p>They&#39;re all variations of the same underlying idea:</p><p><em>Handle the absence of data explicitly rather than letting it propagate silently through your results.</em></p><h3>Pattern 7: The Reusable Logic Pattern</h3><p>As queries grow more complex, structure matters as much as syntax. A query that works but can’t be read — by you next month, or by a colleague today — is harder to maintain and harder to debug.</p><p>Common Table Expressions (CTEs) let you break a complex query into named, readable steps:</p><pre>WITH high_earners AS (<br>    SELECT *<br>    FROM employees<br>    WHERE salary &gt; 100000<br>)<br>SELECT *<br>FROM high_earners;</pre><p>The pattern:</p><p><em>Solve one piece of the problem, give it a name, then build on it.</em></p><p>CTEs don’t change what the query does — they change how it’s organized. And organized queries are easier to reason about, easier to test, and easier to hand off.</p><p><em>CTEs are supported in SQL Server, MySQL 8.0+, PostgreSQL, and Oracle. If you’re on MySQL 5.x, subqueries are the closest equivalent.</em></p><h3>The Real Insight</h3><p>If SQL has felt hard, it’s probably not because you’re missing syntax.</p><p>Syntax is learnable — a quick search fills in the details.</p><p>What’s harder to pick up from documentation alone is the sense of <em>which pattern applies here</em>, and <em>why this query is doing what it’s doing</em>.</p><p>That recognition develops with practice. The more queries you read, write, and work through, the more the patterns become familiar — and eventually automatic.</p><p>That’s also the idea behind <a href="https://apps.apple.com/us/app/sql-bubble-pop-sql-coding-game/id6744767120">SQL Bubble Pop</a>. Daily challenges, streak tracking, and active recall that turns pattern recognition into a habit rather than an effort.</p><p><strong>Download </strong><a href="https://apps.apple.com/us/app/sql-bubble-pop-sql-coding-game/id6744767120"><strong>SQL Bubble Po</strong></a><strong>p free on the App Store.</strong> Search “SQL Bubble Pop.”</p><h3>TL;DR</h3><figure><img alt="A dark navy “SQL Patterns · TL;DR” reference graphic with seven numbered items. Item 01, Filter Then Shape: FROM gets the data, WHERE narrows it, SELECT decides what to show. Item 02, The Relationship Pattern: A JOIN connects two datasets — the ON clause is the relationship rule. Item 03, The Accidental Explosion: A JOIN without an ON condition produces a Cartesian product — every combination of every row. Item 04, The Aggregation Pattern: GROUP BY groups data by category — use HAVING to filter" src="https://cdn-images-1.medium.com/max/843/1*Rq5SHFX5-AB7SKrGZP8vMA.png" /><figcaption>Seven SQL patterns worth recognizing — because once you see them, queries start to make sense.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47129d8636f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UNION vs UNION ALL: The SQL Difference That’s Worth a Few Extra Seconds]]></title>
            <link>https://medium.com/@tiye_78900/union-vs-union-all-the-sql-difference-thats-worth-a-few-extra-seconds-2d18b39e3c36?source=rss-8b514f478a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d18b39e3c36</guid>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Tiye Baldwin-Anderson]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 23:57:25 GMT</pubDate>
            <atom:updated>2026-04-13T23:57:25.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A cinematic SQL Bubble Pop graphic comparing UNION and UNION ALL against a sunny Los Santos cityscape with palm trees. Two clipboards side by side each show a query selecting email from Customers and Employees tables. The UNION clipboard shows the queries separated by UNION with a green checkmark and “No Duplicates.” The UNION ALL clipboard shows the queries separated by UNION ALL with a warning icon and “Includes Duplicates.”" src="https://cdn-images-1.medium.com/max/1024/1*0oGnJO_8Kd1TqhmlKkUOkQ.png" /><figcaption>Same data, different results. The one you reach for depends on whether duplicates matter.</figcaption></figure><h3>UNION vs UNION ALL: The SQL Difference That’s Worth a Few Extra Seconds</h3><p>If you’re working with SQL — or getting started with it — you’ll run into both UNION and UNION ALL fairly early.</p><p>They both combine the results of two or more SELECT statements into a single result set. But they don’t behave the same way — and the difference has real implications for both your results and your query performance.</p><p>Let’s break it down.</p><h3>The Core Difference</h3><p>UNION combines results and removes duplicate rows.</p><p>UNION ALL combines results and keeps everything — including duplicates.</p><pre>-- UNION: removes duplicates<br>SELECT City FROM Customers<br>UNION<br>SELECT City FROM Suppliers;<br><br>-- UNION ALL: keeps everything<br>SELECT City FROM Customers<br>UNION ALL<br>SELECT City FROM Suppliers;</pre><p>If the same city appears in both tables, UNION returns it once. UNION ALL returns it twice.</p><p>Neither is wrong. They’re answering different questions.</p><h3>Why UNION ALL Is Often the Better Default</h3><p>This surprises a lot of people: UNION ALL is almost always faster than UNION.</p><p>The reason is straightforward. To remove duplicates, UNION has to do extra work — it sorts or hashes the combined result set to find and eliminate matching rows. On large datasets, that extra step has a real cost.</p><p>UNION ALL skips that step entirely. It just stacks the results and moves on.</p><pre>-- If you know there are no duplicates, this is faster:<br>SELECT OrderID, OrderDate FROM Orders2023<br>UNION ALL<br>SELECT OrderID, OrderDate FROM Orders2024;</pre><p>If you’re combining data from sources that can’t overlap — like orders from different years stored in separate tables — there’s no reason to pay the deduplication cost. UNION ALL is the right tool.</p><h3>When UNION Is the Right Choice</h3><p>UNION earns its extra overhead when duplicate rows would genuinely distort your results.</p><p>The classic example: you’re pulling a distinct list of values from multiple tables and you need each value to appear exactly once.</p><pre>-- Get a clean list of all cities where we have customers OR suppliers<br>SELECT City FROM Customers<br>UNION<br>SELECT City FROM Suppliers;</pre><p>If New York appears in both tables, you want to see it once — not twice. UNION handles that automatically.</p><p>You could achieve the same thing with UNION ALL plus a DISTINCT, but that&#39;s more code for the same result:</p><pre>-- Same outcome, more work to write<br>SELECT DISTINCT City FROM (<br>    SELECT City FROM Customers<br>    UNION ALL<br>    SELECT City FROM Suppliers<br>) AS AllCities;</pre><p>When deduplication is genuinely what you need, UNION is cleaner.</p><h3>The Rules Both Follow</h3><p>Whether you use UNION or UNION ALL, both require the same things:</p><ul><li>Each SELECT statement must return the same number of columns</li><li>The corresponding columns must have compatible data types</li><li>Column names in the result set come from the first SELECT statement</li></ul><pre>-- This works: same number of columns, compatible types<br>SELECT FirstName, LastName FROM Employees<br>UNION ALL<br>SELECT ContactName, CompanyName FROM Suppliers;<br><br>-- This does not work: different number of columns<br>SELECT FirstName, LastName, Department FROM Employees<br>UNION ALL<br>SELECT ContactName, CompanyName FROM Suppliers;</pre><p><em>These rules apply consistently across SQL Server, MySQL, PostgreSQL, and Oracle.</em></p><h3>Ordering the Combined Results</h3><p>One thing that trips people up: if you want to sort the final combined result, the ORDER BY goes at the very end — after the last SELECT statement.</p><pre>SELECT City, &#39;Customer&#39; AS SourceType FROM Customers<br>UNION ALL<br>SELECT City, &#39;Supplier&#39; AS SourceType FROM Suppliers<br>ORDER BY City ASC;</pre><p>You can’t add ORDER BY to individual SELECT statements within a UNION — only to the final combined result.</p><p><em>This behavior is consistent across SQL Server, MySQL, PostgreSQL, and Oracle.</em></p><h3>A Quick Note on NULL Handling</h3><p>Both UNION and UNION ALL treat NULL as a value when stacking rows. Where the behavior differs slightly is in deduplication:</p><p>UNION considers two NULL values in the same column to be duplicates of each other and will collapse them into one row. This is one of the rare places in SQL where NULL is treated as equal to NULL — which is the opposite of how comparison operators like = work.</p><pre>-- If both tables have a row where City IS NULL,<br>-- UNION returns one NULL row, UNION ALL returns two<br>SELECT City FROM Customers<br>UNION<br>SELECT City FROM Suppliers;</pre><p><em>This NULL deduplication behavior is consistent across SQL Server, MySQL, PostgreSQL, and Oracle.</em></p><h3>The Performance Habit Worth Building</h3><p>A small habit that pays off over time: reach for UNION ALL first, then ask yourself whether you actually need deduplication. If the answer is yes, switch to UNION. If the answer is no — or if you&#39;re not sure whether duplicates are even possible — UNION ALL is the safer and faster default.</p><p>On small datasets the difference is negligible. On large datasets, or in queries that run frequently, it adds up.</p><h3>The Fluency Factor</h3><p>Reading this once plants a seed. Having it as a reflex — where you reach for UNION ALL by default and consciously choose UNION when you need it — that comes from practice.</p><p>SQL Bubble Pop covers set operations, filtering patterns, and the query-building decisions that make these distinctions click. Daily challenges, streak tracking, skill focus modes. Ten minutes a day builds the kind of fluency that feels good to have.</p><p><strong>Download SQL Bubble Pop free on the App Store.</strong> Search “SQL Bubble Pop.”</p><h3>TL;DR</h3><ul><li>UNION combines results and removes duplicates — UNION ALL combines results and keeps everything</li><li>UNION ALL is faster because it skips the deduplication step</li><li>Use UNION when duplicate rows would genuinely distort your results</li><li>Use UNION ALL when sources can&#39;t overlap or when you&#39;ll handle deduplication yourself</li><li>Both require the same number of columns and compatible data types across SELECT statements</li><li>ORDER BY goes at the end — after the last SELECT statement</li><li>In UNION, two NULL values in the same column are treated as duplicates — one of the few places SQL does this</li></ul><figure><img alt="A dark navy “UNION vs UNION ALL · TL;DR” reference graphic with seven numbered items. Item 01: UNION combines results and removes duplicates — UNION ALL combines results and keeps everything. Item 02: UNION ALL is faster because it skips the deduplication step. Item 03: Use UNION when duplicate rows would genuinely distort your results. Item 04: Use UNION ALL when sources can’t overlap or when you’ll handle deduplication yourself…" src="https://cdn-images-1.medium.com/max/774/1*g-XgiGQHpKM2HRhZvZ41nQ.png" /><figcaption>Seven things worth knowing about UNION and UNION ALL — including the one that surprises almost everyone.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d18b39e3c36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Practical SQL Trigger Example You Can Actually Use]]></title>
            <link>https://medium.com/@tiye_78900/one-practical-sql-trigger-example-you-can-actually-use-39341b4c76d3?source=rss-8b514f478a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/39341b4c76d3</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Tiye Baldwin-Anderson]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 18:23:24 GMT</pubDate>
            <atom:updated>2026-04-05T18:23:24.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A cinematic comic book style graphic titled “SQL Triggers” split across four panels. Top left shows a server room with glowing database racks. Top right shows a warm sunset cityscape with palm trees and a helicopter. Center displays an audit log table with columns EmployeeID, OldSalary, NewSalary, and ChangedAt, showing Employee 1’s salary change from 60000.00 to 65000.00 on 04/24/2024 at 15:30. Bottom left shows a magnifying glass examining an audit log with OLD and NEW values highlighted." src="https://cdn-images-1.medium.com/max/1024/1*PkavYbr7DItm1r3-BMz_uw.png" /><figcaption>One UPDATE statement. One trigger. One automatic audit record — no extra code required.</figcaption></figure><p>Triggers are one of those SQL features that can seem a little mysterious at first, but the basic idea is simple: a trigger lets the database automatically do something when data changes.</p><p>In this example, we’ll use a trigger to create a basic audit trail.</p><p>Whenever a row in an Employees table is updated, the trigger will record the old and new salary values in a separate audit table.</p><p><em>Note: The primary examples use SQL Server / T-SQL syntax. Where behavior or syntax differs meaningfully across SQL Server, MySQL, PostgreSQL, and Oracle, that’s called out directly.</em></p><h3>What Is a Trigger?</h3><p>A trigger is a block of SQL that runs automatically in response to an event such as an INSERT, UPDATE, or DELETE.</p><p>That means the database can react to changes without relying on someone to remember to run extra code manually.</p><h3>Step 1: Create the Main Table</h3><pre>-- SQL Server / MySQL / PostgreSQL<br>CREATE TABLE Employees (<br>    EmployeeID INT PRIMARY KEY,<br>    FullName VARCHAR(100),<br>    Salary DECIMAL(10,2)<br>);</pre><p><em>This syntax works across SQL Server, MySQL, and PostgreSQL. In Oracle, </em><em>VARCHAR is supported but </em><em>VARCHAR2 is the preferred type:</em></p><pre>-- Oracle<br>CREATE TABLE Employees (<br>    EmployeeID NUMBER PRIMARY KEY,<br>    FullName VARCHAR2(100),<br>    Salary NUMBER(10,2)<br>);</pre><h3>Step 2: Insert Some Sample Data</h3><pre>INSERT INTO Employees (EmployeeID, FullName, Salary)<br>VALUES<br>(1, &#39;Alice Johnson&#39;, 60000.00),<br>(2, &#39;Brian Smith&#39;, 72000.00);</pre><p><em>Multi-row INSERT with VALUES works across all four databases.</em></p><h3>Step 3: Create the Audit Table</h3><pre>-- SQL Server<br>CREATE TABLE EmployeeSalaryAudit (<br>    AuditID INT IDENTITY(1,1) PRIMARY KEY,<br>    EmployeeID INT,<br>    OldSalary DECIMAL(10,2),<br>    NewSalary DECIMAL(10,2),<br>    ChangedAt DATETIME DEFAULT GETDATE()<br>);</pre><p>This table will store each salary change, including the old value, the new value, and when the change happened.</p><p><em>Auto-incrementing primary keys and current timestamp functions vary across databases:</em></p><pre>-- MySQL<br>CREATE TABLE EmployeeSalaryAudit (<br>    AuditID INT AUTO_INCREMENT PRIMARY KEY,<br>    EmployeeID INT,<br>    OldSalary DECIMAL(10,2),<br>    NewSalary DECIMAL(10,2),<br>    ChangedAt DATETIME DEFAULT NOW()<br>);</pre><pre>-- PostgreSQL<br>CREATE TABLE EmployeeSalaryAudit (<br>    AuditID SERIAL PRIMARY KEY,<br>    EmployeeID INT,<br>    OldSalary DECIMAL(10,2),<br>    NewSalary DECIMAL(10,2),<br>    ChangedAt TIMESTAMP DEFAULT NOW()<br>);</pre><pre>-- Oracle<br>CREATE TABLE EmployeeSalaryAudit (<br>    AuditID NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,<br>    EmployeeID NUMBER,<br>    OldSalary NUMBER(10,2),<br>    NewSalary NUMBER(10,2),<br>    ChangedAt DATE DEFAULT SYSDATE<br>);</pre><p><em>Key differences:</em></p><ul><li><em>SQL Server uses </em><em>IDENTITY(1,1) and </em><em>GETDATE()</em></li><li><em>MySQL uses </em><em>AUTO_INCREMENT and </em><em>NOW()</em></li><li><em>PostgreSQL uses </em><em>SERIAL (or </em><em>GENERATED ALWAYS AS IDENTITY in newer versions) and </em><em>NOW()</em></li><li><em>Oracle uses </em><em>GENERATED ALWAYS AS IDENTITY and </em><em>SYSDATE</em></li></ul><h3>Step 4: Create the Trigger</h3><p>This is where the databases diverge most significantly.</p><pre>-- SQL Server<br>CREATE TRIGGER trg_LogSalaryChange<br>ON Employees<br>AFTER UPDATE<br>AS<br>BEGIN<br>    INSERT INTO EmployeeSalaryAudit (EmployeeID, OldSalary, NewSalary)<br>    SELECT<br>        d.EmployeeID,<br>        d.Salary AS OldSalary,<br>        i.Salary AS NewSalary<br>    FROM deleted d<br>    INNER JOIN inserted i<br>        ON d.EmployeeID = i.EmployeeID<br>    WHERE d.Salary &lt;&gt; i.Salary<br>       OR (d.Salary IS NULL AND i.Salary IS NOT NULL)<br>       OR (d.Salary IS NOT NULL AND i.Salary IS NULL);<br>END;</pre><p>In SQL Server, triggers can access two special logical tables:</p><ul><li>deleted contains the old version of updated rows</li><li>inserted contains the new version of updated rows</li></ul><p>The trigger joins those tables on EmployeeID and logs only rows where the salary actually changed.</p><p><em>A note on the WHERE clause: a simple </em><em>d.Salary &lt;&gt; i.Salary won&#39;t catch changes involving NULL values — in SQL, </em><em>NULL &lt;&gt; anything evaluates to unknown, not true. The additional </em><em>IS NULL conditions ensure those changes are captured correctly. This applies to all four database versions below.</em></p><pre>-- MySQL<br>CREATE TRIGGER trg_LogSalaryChange<br>AFTER UPDATE ON Employees<br>FOR EACH ROW<br>BEGIN<br>    IF OLD.Salary &lt;&gt; NEW.Salary<br>       OR (OLD.Salary IS NULL AND NEW.Salary IS NOT NULL)<br>       OR (OLD.Salary IS NOT NULL AND NEW.Salary IS NULL)<br>    THEN<br>        INSERT INTO EmployeeSalaryAudit (EmployeeID, OldSalary, NewSalary)<br>        VALUES (OLD.EmployeeID, OLD.Salary, NEW.Salary);<br>    END IF;<br>END;</pre><pre>-- PostgreSQL (requires a trigger function)<br>-- Note: EXECUTE FUNCTION requires PostgreSQL 11+<br>-- Use EXECUTE PROCEDURE for older versions<br>CREATE OR REPLACE FUNCTION log_salary_change()<br>RETURNS TRIGGER AS $$<br>BEGIN<br>    IF OLD.Salary &lt;&gt; NEW.Salary<br>       OR (OLD.Salary IS NULL AND NEW.Salary IS NOT NULL)<br>       OR (OLD.Salary IS NOT NULL AND NEW.Salary IS NULL)<br>    THEN<br>        INSERT INTO EmployeeSalaryAudit (EmployeeID, OldSalary, NewSalary)<br>        VALUES (OLD.EmployeeID, OLD.Salary, NEW.Salary);<br>    END IF;<br>    RETURN NEW;<br>END;<br>$$ LANGUAGE plpgsql;<br><br>CREATE TRIGGER trg_LogSalaryChange<br>AFTER UPDATE ON Employees<br>FOR EACH ROW<br>EXECUTE FUNCTION log_salary_change();</pre><pre>-- Oracle<br>CREATE OR REPLACE TRIGGER trg_LogSalaryChange<br>AFTER UPDATE ON Employees<br>FOR EACH ROW<br>BEGIN<br>    IF :OLD.Salary &lt;&gt; :NEW.Salary<br>       OR (:OLD.Salary IS NULL AND :NEW.Salary IS NOT NULL)<br>       OR (:OLD.Salary IS NOT NULL AND :NEW.Salary IS NULL)<br>    THEN<br>        INSERT INTO EmployeeSalaryAudit (EmployeeID, OldSalary, NewSalary)<br>        VALUES (:OLD.EmployeeID, :OLD.Salary, :NEW.Salary);<br>    END IF;<br>END;</pre><p><em>Key differences across databases:</em></p><ul><li><em>SQL Server uses </em><em>deleted and </em><em>inserted virtual tables and handles multiple rows as sets in a single statement-level trigger</em></li><li><em>MySQL uses </em><em>OLD and </em><em>NEW and requires </em><em>FOR EACH ROW — MySQL only supports row-level triggers</em></li><li><em>PostgreSQL separates the trigger logic into a reusable trigger function, then attaches it to the table — </em><em>OLD and </em><em>NEW are used inside the function. </em><em>EXECUTE FUNCTION requires PostgreSQL 11 or later; use </em><em>EXECUTE PROCEDURE for older versions</em></li><li><em>Oracle uses </em><em>:OLD and </em><em>:NEW (note the colon prefix) and requires </em><em>FOR EACH ROW for row-level triggers</em></li></ul><h3>A Note on Statement-Level vs Row-Level Triggers</h3><p>This is one of the most important distinctions to understand — and one that can produce unexpected results if you’re not aware of it.</p><p>A <strong>row-level trigger</strong> fires once for every row affected by the operation. Update 50 rows and it fires 50 times.</p><p>A <strong>statement-level trigger</strong> fires once per SQL statement, regardless of how many rows were affected.</p><ul><li>SQL Server triggers are statement-level by default, which is why the SQL Server example joins deleted and inserted as sets rather than referencing single OLD/NEW values</li><li>MySQL only supports row-level triggers</li><li>PostgreSQL supports both — FOR EACH ROW for row-level, FOR EACH STATEMENT for statement-level</li><li>Oracle supports both — FOR EACH ROW for row-level, statement-level is the default without it</li></ul><p>This matters in practice: if you run a bulk update affecting 1,000 rows, a row-level trigger fires 1,000 times. For audit logging on large tables, that’s worth thinking about before you deploy.</p><h3>Step 5: Test It</h3><pre>UPDATE Employees<br>SET Salary = 65000.00<br>WHERE EmployeeID = 1;</pre><h3>Step 6: Check the Audit Table</h3><pre>SELECT *<br>FROM EmployeeSalaryAudit;</pre><p>You should see a row showing that Employee 1’s salary changed from 60000.00 to 65000.00.</p><p>That happened automatically because of the trigger.</p><h3>Why This Is Useful</h3><p>This kind of trigger can be useful when you want the database to help maintain a history of important changes.</p><p>Instead of depending on application code to remember to log the update, the database handles it consistently — regardless of which application, tool, or user made the change.</p><h3>A Quick Caution</h3><p>Triggers are powerful, but they should be used carefully.</p><p>Because they run automatically behind the scenes, they can make database behavior harder to understand if too much hidden logic accumulates. A developer looking at the UPDATE statement alone has no visible indication that something else is happening as a result.</p><p>For a simple audit trail like this, though, a trigger can be a practical and readable solution — and audit logging is one of the most widely accepted use cases for triggers across all four major databases.</p><h3>Final Thought</h3><p>This is a small example, but it demonstrates the central idea: when data changes, the database can respond automatically.</p><p>The syntax looks different depending on which database you’re working with — but the concept is the same everywhere. A trigger watches for an event, and when that event happens, it acts.</p><p>That’s what makes triggers useful — and why they’re worth understanding.</p><p><a href="https://apps.apple.com/us/app/sql-bubble-pop-sql-coding-game/id6744767120">SQL Bubble Pop</a> covers the query logic and filtering patterns that form the building blocks of trigger design — through daily challenges and active recall that make these concepts click faster.</p><p><strong>Download </strong><a href="https://apps.apple.com/us/app/sql-bubble-pop-sql-coding-game/id6744767120"><strong>SQL Bubble Pop</strong></a><strong> free on the App Store.</strong> Search “SQL Bubble Pop.”</p><h3>TL;DR</h3><figure><img alt="A dark navy “SQL Triggers · TL;DR” reference graphic with six numbered items. Item 01: A trigger runs automatically when data changes — no manual intervention needed. Item 02: SQL Server uses deleted and inserted virtual tables — other databases use OLD and NEW, with Oracle adding a colon prefix (:OLD and :NEW). Item 03: PostgreSQL requires a separate trigger function before attaching the trigger to a table, with a note that EXECUTE FUNCTION requires PostgreSQL 11 or later." src="https://cdn-images-1.medium.com/max/778/1*Oidnf_GF1aELdfLlZe2RCA.png" /><figcaption>Triggers look different across databases — but the concept is the same everywhere. Here’s what’s worth knowing before you deploy one.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39341b4c76d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>