<?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 Mehdi Akoudad on Medium]]></title>
        <description><![CDATA[Stories by Mehdi Akoudad on Medium]]></description>
        <link>https://medium.com/@akoudadmehdi01?source=rss-ba63759cdaca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z5bGcF-sQd9mQigULJ5V7Q@2x.jpeg</url>
            <title>Stories by Mehdi Akoudad on Medium</title>
            <link>https://medium.com/@akoudadmehdi01?source=rss-ba63759cdaca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 18:36:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akoudadmehdi01/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 LIKE Pattern Matching]]></title>
            <link>https://medium.com/@akoudadmehdi01/sql-like-pattern-matching-35155f295c9b?source=rss-ba63759cdaca------2</link>
            <guid isPermaLink="false">https://medium.com/p/35155f295c9b</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[pattern-matching]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Mehdi Akoudad]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 03:34:17 GMT</pubDate>
            <atom:updated>2025-08-23T03:34:17.635Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8-0TnXyXFcpgvyn-klefg.png" /></figure><blockquote>Use LIKE to filter SQL records on specific string matches. This tutorial teaches you to use wildcards, NOT, LOWER, UPPER, and CASE WHEN with LIKE.</blockquote><p>Like it or not, the LIKE operator is essential in SQL. It gives data scientists and <strong>data engineers</strong> the power to filter data on specific string matches. This article provides a quick tutorial on LIKE for beginners and intermediates.</p><h3>The SQL LIKE Operator for Pattern Matching</h3><p>Suppose you have an employees table and would like to find all names that start with ‘A’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHR-e60RppJBDFA2_4um7Q.png" /></figure><p>You could spend time looking through the table manually. But why would you do that when you have the LIKE operator?</p><pre>SELECT DISTINCT<br>	first_name<br>FROM employees<br>WHERE first_name LIKE &#39;A%&#39;</pre><p>The magic here is in the clause `WHERE first_name LIKE ‘A%’`, which means “find all first_name starting with &quot;A&quot; and ending with any number of characters.” The `A%` here is known as a pattern for matching.</p><p>The `%` is not the only wildcard you can use in conjunction with the LIKE operator. You could use the underscore sign `_` , too:</p><ul><li>`%` matches any number of characters.</li><li>`_` matches any single character.</li></ul><p>The syntax is easy to remember. It is simply:</p><pre>column_name LIKE pattern</pre><p>You can use LIKE to achieve a variety of pattern-matching. Here’s how:</p><h3>Beginner SQL LIKE Examples</h3><p>Below, we’ve outlined some practical examples of how you can use the LIKE statement and the results from our sample data set.</p><h3>1. Use LIKE for exact string match</h3><p>If you’d like to perform an exact string match, use LIKE without ‘%’ or ‘_’</p><pre>SELECT<br>    first_name, last_name<br>FROM employees<br>WHERE first_name LIKE &#39;Barry&#39; -- the same as WHERE first_name = ‘Barry’</pre><h3>2. Use ‘%’ to match any number of characters</h3><p>‘%’ can be used to match any (even zero) number of characters – a number, an alphabet, or a symbol.</p><p>Suppose you want to find all employees whose name starts with ‘Adam’; you can use the pattern ‘Adam%’</p><pre>SELECT DISTINCT<br>    first_name<br>FROM employees<br>WHERE first_name LIKE &#39;Adam%&#39;</pre><p>To find names that end with “z” try the pattern ‘%z’. You can also use multiple ‘%’ in one pattern. For example, if you want to find names that contain &quot;z&quot;, use ‘%z%’.</p><h3>3. Use ‘_’ to match one (and only one) character</h3><p>Like the game Hangman, the underscore sign _ can only fit one character.</p><p>How many ways are there to spell Le_n? The pattern would match anything from &quot;Lexn&quot;, &quot;LeAn&quot;, &quot;Le3n&quot;, or &quot;Le-n&quot;.</p><pre>SELECT DISTINCT<br>    first_name<br>FROM employees<br>WHERE first_name LIKE &#39;Le_n&#39;</pre><p>What are the different names with only three characters? We can find out using three consecutive underscores ___ as the pattern.</p><pre>SELECT DISTINCT<br>    first_name<br>FROM employees<br>WHERE first_name LIKE &#39;___&#39;</pre><h3>4. Use both ‘%’ and ‘_’ to match any pattern</h3><p>Of course, you can use both ‘%’ and ‘_’ to create interesting patterns.</p><pre>SELECT DISTINCT<br>    first_name<br>FROM employees<br>WHERE first_name LIKE &#39;%ann_&#39;</pre><p>The pattern ‘%ann_’ matches a string that starts with any number of characters and ends with &quot;ann&quot; and one other character.</p><h3>5. Use NOT to find strings that do not match a pattern</h3><p>What if you want to find all rows that do not match a specific criterion? You can use the NOT LIKEoperator. For example, to find all titles except for &quot;Staff&quot;, we can use the syntax</p><pre>`WHERE title NOT LIKE ‘Staff’`</pre><p>This is exactly equivalent to the syntax</p><pre>`WHERE title != ‘Staff’`</pre><pre>SELECT DISTINCT<br>    title<br>FROM titles<br>WHERE title NOT LIKE &#39;Staff&#39;</pre><p>Of course, you can use NOT LIKE with any of the patterns we described.</p><pre>SELECT DISTINCT<br>    title<br>FROM titles <br>WHERE title NOT LIKE &#39;%engineer&#39;</pre><h3>6. Use LOWER (or UPPER) with LIKE for case-insensitive pattern matching</h3><p>You can use the following syntax if you need to perform pattern matching but aren’t sure if the string is stored in lowercase, uppercase, or mixed case.</p><pre>`LOWER(column_name) LIKE pattern`</pre><p>The function LOWER() returns all strings in lowercase, regardless of whether they are stored as upper-, lower-, or mixed case.</p><p>When using the syntax, make sure you spell the pattern in all lowercase! Else, you might not get any matches.</p><p>You could replace LOWER with UPPER in the syntax above, too. Be sure to spell out the pattern in capital letters.</p><pre>`UPPER(column_name) LIKE PATTERN`</pre><p>For example, to find out if an employee’s name is “Joanne”, “JoAnne”, “Joanna”, or “JoAnna”, try either of the following:</p><pre>SELECT DISTINCT<br>    first_name<br>FROM employees<br>WHERE lower(first_name) LIKE &#39;joann_&#39;</pre><pre>SELECT DISTINCT<br>    first_name<br>FROM employees<br>WHERE UPPER(first_name) LIKE &#39;JOANN_&#39;</pre><h3>7. SQL LIKE with multiple values using OR/AND</h3><p>You can combine multiple conditions using the LIKE syntax, too.</p><p>For example, use the OR condition to find results that satisfy at least one out of multiple LIKE patterns.</p><pre>SELECT DISTINCT<br>    first_name<br>FROM employees<br>WHERE<br>first_name LIKE &#39;Ad_l&#39; OR<br>first_name LIKE &#39;Ad_m&#39;</pre><p>On the other hand, to find a string that matches multiple LIKE conditions, use the AND keyword.</p><pre>SELECT DISTINCT<br>    first_name<br>FROM employees<br>WHERE<br>first_name LIKE &#39;%am%&#39; AND<br>first_name LIKE &#39;%me%&#39;</pre><p>The LIKE syntax can be applied to multiple columns as long as their variable type is a variable-length character (varchar). Knowing that we can find the names of employees whose initials are &quot;Z. Z.&quot;</p><pre>SELECT DISTINCT<br>    first_name, last_name<br>FROM employees<br>WHERE<br>first_name LIKE &#39;Z%&#39; AND<br>last_name LIKE &#39;Z%&#39;</pre><h3>8. Use LIKE in the SELECT CASE WHEN clause</h3><p>Thus far, we have focused on using LIKE as a condition for selecting records in the WHERE clause. We also use LIKE in the SELECT clause. For example, can we find out how many employees named &quot;Adam&quot; are in our database?</p><pre>SELECT<br>    COUNT(CASE WHEN first_name LIKE &#39;Adam&#39; THEN 1 END) num_employees_adam<br>FROM employees</pre><p>On the other hand, how many employees have the initials “A.Z.”?</p><pre>SELECT<br>    COUNT(CASE WHEN first_name LIKE &#39;A%&#39; AND last_name LIKE &#39;Z%&#39; THEN 1 END) num_employees<br>FROM employees</pre><h3>Common patterns used in SQL LIKE</h3><p>Here’s a summary of the patterns we discussed for quick reference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRPKfgNE3BlzyIoauO_PJQ.png" /></figure><h3>Intermediate Examples of SQL LIKE</h3><p>The LIKE function is largely similar across different flavors of SQL (e.g. PostgreSQL, MySQL, Redshift, etc.). However some have additional variations of the LIKE function that are worth mentioning.</p><h3>1. The ILIKE operator</h3><p>Available in Redshift and PostgreSQL, ILIKE is the case-insensitive version of LIKE. As such, all of the following are equivalent.</p><pre>SELECT<br>  datacamp ILIKE ‘datacamp’, -- returns TRUE<br>  DATACAMP ILIKE ‘datacamp’, -- returns TRUE<br>  Datacamp ILIKE ‘datacamp’, -- returns TRUE<br>  datacamp ILIKE ‘DataCamp’, -- returns TRUE</pre><h3>2. Using square brackets [] and [^] as wildcard characters</h3><p>Users of T-SQL or SQL Server have additional wildcard characters for more complex pattern matching.</p><p>The square bracket syntax [] matches any specific character within the range or set. For example, the following will all return TRUE.</p><pre>SELECT<br>  ‘Carson’ LIKE ‘[C-K]arson’, -- returns TRUE because C is in the range C-K<br>  ‘Karson’ LIKE ‘[C-K]arson’, -- returns TRUE because K is in range<br>  ‘Larson’ LIKE ‘[CKL]arson’, -- returns TRUE because L is in the set [CKL]<br>  ‘Parson’ LIKE ‘[C-K]arson’ -- returns FALSE because P is out of range</pre><p>The caret-in-square-bracket [^] wildcard matches any single character that is not within the specified range or set. Can you see why the following results are such?</p><pre>SELECT<br>  ‘Carson’ LIKE ‘[^C-K]arson’ -- returns FALSE <br>  ‘Parson’ LIKE ‘[^C-K]arson’ -- returns TRUE</pre><p>Here, since “C” is within the range of [C-K], the pattern ‘C’ will not match [^C-K]. Thus, &quot;Carson&quot; will not match [^C-K]arson, but &quot;Parson&quot; will.</p><h3>3. The RLIKE operator</h3><p>Available in MySQL, the RLIKE operator recognizes regular expressions (RegEx) in the pattern. RegEx is a powerful and versatile tool for advanced pattern matching.</p><pre>SELECT DISTINCT<br>    first_name<br>FROM employees<br>WHERE first_name RLIKE &#39;Susann[a-e]&#39;</pre><h3>4. The ‘~~’ operator</h3><p>In PostgreSQL, ‘~~’ is completely synonymous with LIKE. There are also equivalents of ILIKE, NOT LIKE, and NOT ILIKE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*Teys-y23hOtOImCDf2SUEA.png" /></figure><h3>Troubleshooting: Common Errors and Mistakes with LIKE</h3><p>Here are some common errors you may run into when using LIKE, and how to correct them:</p><ol><li><strong>No results returned</strong>: Check for case sensitivity. In some SQL dialects, LIKE is case-sensitive by default. Use LOWER() or ILIKE (if supported) for case-insensitive matching.</li><li><strong>Unexpected results with wildcards</strong>: Make sure % and _ are used correctly. % matches any number of characters, while _ matches exactly one character. Misplacing these can lead to unexpected matches.</li><li><strong>Performance issues</strong>: If your query is slow, look for leading % in patterns (e.g., %pattern), which disables index usage. Rewrite patterns to start with a specific string if possible. See the section below for more on performance.</li><li><strong>SQL injection errors</strong>: If you’re using user input in your query, make sure it is properly parameterized to avoid syntax errors or vulnerabilities.</li><li><strong>Special characters in patterns</strong>: Wildcard symbols like % and _ in the search string must be escaped if intended as literal characters. Use ESCAPE in your query to define an escape character.</li></ol><pre>WHERE column_name LIKE &#39;50\% OFF&#39; ESCAPE &#39;\&#39;</pre><h3>Performance Considerations When Using the LIKE Operator</h3><p>The LIKE operator is great, but it can potentially impact query performance, especially when used on large datasets. Here are some considerations to optimize its use:</p><ol><li><strong>Indexes:</strong> The LIKE operator performs best when the pattern starts with a constant string, such as Adam%, because the database can use indexes. However, patterns like %Adam or %Adam%require a full table scan, which can be slow for large tables.</li><li><strong>Avoid leading wildcards:</strong> Starting a pattern with %, such as %pattern, disables index usage, as the database has to examine every record.</li><li><strong>Collation and case-insensitive matching:</strong> Using functions like LOWER() or UPPER() on columns for case-insensitive searches can also prevent indexes from being used. Instead, make sure the database collation is set appropriately for case-insensitive comparisons.</li><li><strong>Alternative approaches:</strong> For large datasets, consider using full-text search or database-specific search features, such as GIN indexes in PostgreSQL or FULLTEXT indexes in MySQL, when performing complex or frequent string matching.</li><li><strong>Selective queries: </strong>Limit the scope of your queries using additional filters, such as date ranges or numerical columns, to reduce the data processed by the LIKE operator.</li></ol><h3>LIKE vs. Full-Text Search</h3><p>Full-text search, available in databases like MySQL, PostgreSQL, and SQL Server, is optimized for advanced text queries, such as searching for keywords, handling linguistic variations, and ranking results by relevance. While LIKE is great for basic tasks, full-text search is better for scalable and sophisticated text search.</p><h3>Use SQL LIKE Confidently</h3><p>Mastering SQL functions is key to succeeding in data science, and SQL’s LIKE command is no exception. A good command of SQL will supercharge your analytics progress, so be sure to learn it well!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35155f295c9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside Uber’s 2024 Ride Data: What the Numbers Reveal About City Mobility]]></title>
            <link>https://medium.com/@akoudadmehdi01/inside-ubers-2024-ride-data-what-the-numbers-reveal-about-city-mobility-5cf4916cba64?source=rss-ba63759cdaca------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cf4916cba64</guid>
            <category><![CDATA[mobility-insights]]></category>
            <category><![CDATA[insights]]></category>
            <category><![CDATA[kaggle-dataset]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-storytelling]]></category>
            <dc:creator><![CDATA[Mehdi Akoudad]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 17:27:20 GMT</pubDate>
            <atom:updated>2025-08-14T17:27:20.268Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*ft9rA40rWQf6lsFZUtOSrQ.png" /></figure><p>When we think of ride hailing we imagine convenience, speed, and the ability to summon a car with a tap. Beneath that simple experience there is a rich layer of data shaping every ride. From when people book to why they cancel each number tells part of the story. In this deep dive I explore Uber’s 2024 ride booking dataset to uncover patterns in demand, cancellations, ratings, and payments. The data reveals how the daily life of a city plays out in real time.</p><h3>Mapping the Rhythm of the City</h3><p>The first step in understanding ride patterns was to visualize demand over time. By plotting bookings across hours and days we could see the natural pulse of the city. Weekdays have a steady work driven flow of rides with clear peaks during morning and evening commutes. Weekends shift the pattern and the largest surges happen late at night which reflects social events and nightlife.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ny0d2jp84D1DoBnUZgP8zQ.png" /></figure><p>The heatmap makes this rhythm easy to see. Weekday mornings surge between 7 and 9 AM and again between 5 and 7 PM. Weekends peak later in the evening from 8 PM until well past midnight. For Uber these patterns are essential for surge pricing decisions, driver scheduling, and matching supply to demand.</p><h3>When Rides Do Not Happen</h3><p>Cancellations are one of the biggest sources of friction for riders and drivers. The data shows that customer cancellations are most frequent within the first few minutes after booking. This often happens due to long estimated arrival times, wrong pick up addresses, or sudden changes in plans. Driver cancellations are more common in periods of high traffic when pick up locations are far from the driver or in areas that feel unsafe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Az35vuQwRJjnxSip8TATw.png" /></figure><p>Looking at the hourly breakdown driver cancellations spike during late night hours. This could be related to safety concerns, low trip profitability, or fatigue. Insights like these show why optimizing driver assignment and offering targeted incentives during these hours could reduce cancellations.</p><h3>Ratings as Silent Feedback</h3><p>Ratings are a quieter but equally important form of feedback. By analyzing average ratings across times of day and days of the week we found low rating clusters in late night hours on weekends and during weekday evenings affected by rain. Likely causes include delays from heavy traffic, longer waiting times, and changes in rider mood after long nights out.</p><p>Spotting these patterns makes it possible to improve the rider experience through better communication during delays or by offering ride type upgrades during known high stress periods.</p><h3>Payment Preferences in Transition</h3><p>Payment method analysis shows that digital payments dominate but certain routes still have a high share of cash transactions. These areas often have lower adoption of digital wallets or a cultural preference for paying in cash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8GbAnyVP1ZAu1UCe-QO_SQ.png" /></figure><p>Encouraging digital payment in these areas through small fare discounts or loyalty rewards can improve operational efficiency and reduce the risks tied to handling cash.</p><h3>Distance and Supply Strategy</h3><p>Trip distance patterns revealed that short rides are more common in dense urban cores while long haul trips are tied to airports or suburban destinations. When combined with the hourly demand heatmap this becomes a valuable supply planning tool. Placing more drivers in long trip areas just before peak demand can reduce wait times and improve revenue per trip.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJ9daf5jv7vvpvbgHUJKKw.png" /></figure><h3>Moving Forward</h3><p>From these findings several opportunities become clear. Reduce customer cancellations by making estimated arrival times more accurate, improving address validation, and showing the cost of cancelling before booking. Reduce driver cancellations by adjusting assignment logic, refining pick up radius, and offering targeted incentives. Watch for low rating periods and use proactive solutions such as better routing information or rider communication. Continue to shift cash heavy areas toward digital payments to lower operational costs.</p><p>Ride hailing data is more than a record of past trips. It is a guide for creating a smoother, faster, and more reliable transport experience for everyone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cf4916cba64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside the Checkout: What a Year of Supermarket Transactions Really Tells Us]]></title>
            <link>https://medium.com/@akoudadmehdi01/inside-the-checkout-what-a-year-of-supermarket-transactions-really-tells-us-ec1dfb653bff?source=rss-ba63759cdaca------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec1dfb653bff</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[data-storytelling]]></category>
            <category><![CDATA[retail-analytics]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Mehdi Akoudad]]></dc:creator>
            <pubDate>Sat, 09 Aug 2025 03:19:45 GMT</pubDate>
            <atom:updated>2025-08-09T03:19:45.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulvQvqAcXPJ6bROmXN2cHQ.jpeg" /></figure><blockquote>Walk into any supermarket and you’ll see the same dance: baskets filling up, barcodes beeping, cash and cards changing hands.</blockquote><p>But behind that everyday rhythm, <strong>every checkout holds a piece of a much bigger story</strong> about when we shop, how much we spend, and even how stores decide how many people to put on the tills.</p><p>Over the past weeks, I dug into <strong>2019 supermarket transaction logs</strong> from Poland, matching them with operator data, to answer a few deceptively simple questions:</p><ul><li>Do we really spend more when we pay by card?</li><li>Which days are the “hidden giants” of supermarket sales?</li><li>Could staffing shifts be smarter — without hurting revenue?</li></ul><p>The answers turned out to be far more revealing than I expected.</p><h3>The Pulse of the Week — When the Store Really Comes Alive</h3><p>I started by mapping every single 2019 transaction to its day and week. The goal: <strong>see the heartbeat of the supermarket year</strong>.</p><p>📊 <strong>Daily Trends Chart</strong></p><pre>SELECT <br>DATE_PART(&#39;week&#39;, end_date_time::DATE) as week_num,<br>end_date_time::DATE AS end_date,<br>COUNT(id) as total_transactions,<br>SUM(amount) as total_sales,<br>AVG(amount) as avg_sale_amount<br><br>FROM &#39;pos_transactions.csv&#39;<br>WHERE EXTRACT (YEAR FROM (end_date)) &gt;= &#39;2019&#39;<br>GROUP BY end_date ORDER BY week_num</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fug-8VZvODxmlaTOzWjwPQ.png" /></figure><p>And there it was a pattern you could set your watch to.</p><ul><li><strong>Thursdays, Fridays, and Saturdays</strong> aren’t just a little busier — they’re <em>25% higher in transactions</em> and <em>40% higher in sales revenue</em> than early-week days.</li><li><strong>Sundays are a wildcard</strong>: some roar with activity, others are eerily quiet a side effect of Poland’s partial Sunday trading bans introduced in 2018.</li></ul><p><strong>Weeks 8 and 13</strong> jumped out — those “working Sundays” brought in huge traffic, even when other weeks lagged.</p><p><strong>💡 <em>Story insight:</em></strong> Supermarkets don’t just react to foot traffic; they can <em>create</em> it. With the right promotion, these high-energy weeks can turn into record-breakers.</p><h3>Basket Size — The Secret Behind Big Sales Weeks</h3><p>It’s easy to think more transactions mean more money. But the real gold mine? <strong>Bigger baskets</strong>.</p><p>📊 <strong>Median Basket Size per Day Chart</strong></p><pre>SELECT <br>DATE_PART(&#39;week&#39;, end_date_time::DATE) as week_num,<br>end_date_time::DATE AS end_date,<br>COUNT(id) as total_transactions,<br>SUM(amount) as total_sales,<br>AVG(amount) as avg_sale_amount,<br>PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY amount)  as median_sale_amount,<br>AVG(basket_size) as avg_basket_size,<br>PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY basket_size)  as median_basket_size<br><br>FROM &#39;pos_transactions.csv&#39;<br>WHERE EXTRACT(YEAR FROM end_date_time) &gt;= &#39;2019&#39;<br>GROUP BY (end_date) ORDER BY week_num</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VO7qL-4qLlRAHeec9k4KBA.png" /></figure><p>When I layered in <strong>basket size data</strong>, the story sharpened:</p><ul><li>Peak weeks didn’t just have more customers, those customers were <strong>buying more per visit</strong>.</li><li>In Week 14, the median basket size hit its highest point all year.</li></ul><p><strong>💡 <em>Story insight:</em></strong> If you know customers are already in “stock-up mode,” it’s the perfect time to push bundle deals, multi-buy discounts, or loyalty point boosts. You’re not creating demand from scratch, you’re riding the wave.</p><h3>Sundays &amp; Staffing — The Balancing Act</h3><p>Every retailer knows the pain of <strong>too many staff on a quiet day</strong> or <strong>too few on a busy one</strong>.</p><p>So I turned to the operator logs to see how many people were working each Sunday.</p><p>📊 <strong>Staffing on Sundays Chart</strong></p><pre>SELECT <br>(begin_date_time::DATE) as working_day,<br>COUNT(DISTINCT(operator_id)),<br>DATE_PART(&#39;week&#39;,(begin_date_time::DATE)) as week_num<br><br>FROM &#39;pos_operator_logs.csv&#39;<br><br>WHERE EXTRACT(YEAR FROM begin_date_time) &gt;= &#39;2019&#39;<br><br>GROUP BY working_day</pre><p><strong>Here’s what stood out:</strong></p><ul><li>Working Sundays (like 24 Feb) had more staff — 18 operators — to match demand.</li><li>But some high-traffic Saturdays actually had fewer operators than quieter Sundays.</li></ul><p><strong>💡 <em>Story insight:</em></strong> Predictive staffing could save serious labor costs without sacrificing service. Imagine using last year’s data to schedule shifts for <em>next year’s exact dates</em>.</p><h3>The Bigger Picture — What This Data Really Says</h3><p>When you zoom out, the data tells a clear, three-part story:</p><ol><li><strong>Sales aren’t evenly spread.</strong> They surge late in the week and during specific “event weeks.”</li><li><strong>Bigger baskets are where the money is.</strong> Customers in buying mode are your best upsell audience.</li><li><strong>Staffing can be smarter.</strong> Data-backed scheduling means fewer wasted hours and happier customers.</li></ol><p>This isn’t just trivia for data geeks — it’s the kind of insight that changes how a supermarket operates week to week.</p><h3>Why This Matters Beyond Supermarkets</h3><p>This isn’t just about groceries. Any business with recurring customer traffic , gyms, cafés, retail stores can pull the same levers:</p><ul><li><strong>Find your peak patterns</strong> and build promotions around them.</li><li><strong>Spot your “big basket” moments</strong> and stack upsells when they’re most likely to work.</li><li><strong>Match your team to your traffic</strong> so you’re never over- or under-staffed.</li></ul><h3>Final Thought</h3><p>Data is only numbers until you find the story inside.</p><p>In this supermarket’s case, the story is about timing, momentum, and knowing when to double down.</p><p>You can explore the full analysis and SQL code here:</p><p><strong><em>Author:</em> Mehdi Akoudad — Data Analyst turning raw datasets into business stories.</strong></p><p>🔗 <a href="https://www.linkedin.com/in/mehdiakoudad/">LinkedIn</a> | 📂 <a href="https://github.com/mehdiakoudad/portofolio">Portfolio</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec1dfb653bff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[90 Years of FIFA World Cup History in Power BI]]></title>
            <link>https://medium.com/@akoudadmehdi01/90-years-of-fifa-world-cup-history-in-power-bi-3a0aba31f74d?source=rss-ba63759cdaca------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a0aba31f74d</guid>
            <category><![CDATA[sports-analytics]]></category>
            <category><![CDATA[fifa-world-cup]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[power-bi]]></category>
            <dc:creator><![CDATA[Mehdi Akoudad]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 22:43:52 GMT</pubDate>
            <atom:updated>2025-08-03T22:43:52.933Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNec7fo-NWqZdiyvF_GD_A.png" /></figure><blockquote>The FIFA Men’s World Cup is a global event with rich history.</blockquote><p>In this project I explored the full history of the World Cup using Power BI.</p><p>The goal was to build an interactive dashboard that answers common questions:</p><p><strong>Which country scored the most goals?</strong></p><p><strong>Who reached the most finals?</strong></p><p><strong>Which year had the most goals?</strong></p><p><strong>Do host nations have an advantage?</strong></p><h3>Project Goal</h3><p>Turn raw historical data into an exploratory and story driven dashboard that is useful for fans and for data learners.</p><h3>How I Built It:</h3><blockquote><strong>Data preparation</strong></blockquote><p>I used Power Query to clean the data, standardize team codes and fix dates.</p><blockquote><strong>Data modeling and metrics</strong></blockquote><p>With DAX I calculated host win percentage, finals reached by country, and goal distributions by tournament year.</p><blockquote><strong>Design</strong></blockquote><p>The report has two pages.</p><p>Page one is an Overview with big picture trends.</p><p>Page two is By Tournament for detailed exploration of any single World Cup.</p><h3>Page 1. Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zvUKhFxs25zfklRSDayMg.png" /></figure><p>Overview of 21 World Cups. Finals reached by team, host win rate, and goal distributions by year.</p><p>Key takeaways on this page:</p><p><strong>• Total tournaments 21</strong></p><p><strong>• Host win percentage 28.6 percent</strong></p><p><strong>• Germany leads final appearances with 8. Brazil and Italy follow</strong></p><p><strong>• Box plots show how scoring patterns changed across time</strong></p><h3>Page 2. By Tournament</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2e_Gp4AuubZkzKr0O3laA.png" /></figure><p>Choose any World Cup. See host nation, goals by team, and a map of match locations.</p><p>This page lets you select a tournament and explore the host country, team goals, and where matches were played.</p><p>For example, in 1938 France hosted the event. Hungary and Brazil were top scorers, and matches took place in cities such as Paris, Marseille, and Bordeaux.</p><h3>Interactivity. Tooltips that add context</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*oBWrJBoX0RqEnX2FlbohhQ.png" /></figure><p>Custom tooltip for the city A Coruña with a compact list of matches and final scores.</p><p>I created a report page tooltip that appears when you hover over the map and venue visuals.</p><p>The tooltip shows the city name and a small table with each match and its final result.</p><p>This helps readers get context quickly without changing pages.</p><p>How it works:</p><p><strong>• A dedicated tooltip page with Tooltip set to On and page size set to Tooltip</strong></p><p><strong>• The City field filters the tooltip. A table visual lists Match and Final Result</strong></p><h3>Insights</h3><p>• Germany shows long term consistency with 8 final appearances</p><p>• The host advantage is real. Almost one third of tournaments are won by the host</p><p>• Some years have many more goals. These peaks often align with rule or format changes</p><p>• Matches are usually in larger cities with strong stadium infrastructure</p><h3>Why it matters</h3><p>This project shows how data visualization can turn decades of information into a clear and interactive story. The same approach works for any industry that tracks performance across time.</p><h3>Skills shown</h3><blockquote>- Power BI dashboard design</blockquote><blockquote>- DAX for custom calculations</blockquote><blockquote>- Power Query for ETL</blockquote><blockquote>- Sports analytics storytelling</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a0aba31f74d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Analytical Features in Power BI Tutorial]]></title>
            <link>https://medium.com/@akoudadmehdi01/advanced-analytical-features-in-power-bi-tutorial-0316b489cbb8?source=rss-ba63759cdaca------2</link>
            <guid isPermaLink="false">https://medium.com/p/0316b489cbb8</guid>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[advanced-analytics]]></category>
            <category><![CDATA[ai-in-data-analysis]]></category>
            <dc:creator><![CDATA[Mehdi Akoudad]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 21:05:06 GMT</pubDate>
            <atom:updated>2025-08-03T21:05:06.002Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_MNv5l0HdZziRYGAQDUuTA.png" /></figure><blockquote>Discover how to make your Power BI reports more insightful, informative, and interactive with this advanced analytical features tutorial.</blockquote><p><strong>Power BI</strong> is one of the leading platforms for incorporating Artificial Intelligence and advanced analytics into their application. With updates released every month, it is possible to overlook or miss out on key features that can make it much easier and faster to analyze your data and generate insights.</p><p>The goal of this tutorial is to walk you through some of the more advanced features of Power BI, which can greatly enhance the analytical capabilities of your reports. We will be using a <strong>sample report and dataset</strong> provided by Microsoft that was specifically created to try out these advanced analytics features.</p><h3>The Analytics Pane for Visuals in Power BI</h3><p>Some visuals in Power BI Desktop have the option to add dynamic reference lines through the use of the Analytics pane. It is worth noting that not all options are available for all visuals, and some visuals, such as combination charts like the line and clustered column chart, have no options available in the Analytics pane.</p><h3>The types of dynamic lines you can add to visuals are:</h3><ul><li>Constant line (as well as options for separate x-axis and y-axis constant lines)</li><li>Max line</li><li>Min line</li><li>Average line</li><li>Median line</li><li>Percentile line</li><li>Symmetry shading</li><li>Trend line</li><li>Forecasts</li></ul><p>These dynamic lines are especially useful for adding context to your visuals, which can help the user to extract useful insights faster.</p><p>For example, suppose you have a clustered bar chart showing sales by country. By adding an average line, you can quickly determine which country is performing above or below average; this can then inform further decision-making.</p><p>I have found the average and trend lines to be the most useful.</p><p>Let us go over how to add these to your charts below.</p><h3>Adding an Average Line to Charts in Power BI</h3><p>In this example, we will be adding an average line to a clustered bar chart showing the total opportunity value by-product. First, select the ‘Analytics’ icon; then, under ‘Average line’ click ‘Add line’. You can customize the look of the line if you like, or leave it as is.</p><p>In the chart below, we can see that the products from Tablets to Webcams are all performing below average. A company could decide to drop some of the worst performing products, or they could intensify their marketing efforts to try to increase sales. Adding an average line to charts makes it easier to identify where these kinds of decisions need to be made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B-S7RzhTfnQRfYK8.png" /></figure><h3>Adding a Trend Line to Charts in Power BI</h3><p>In this example, we will be adding a trend line to a line chart showing the total opportunity value over time. First, select the ‘Analytics’ icon. If you have a compatible time-series chart, you will be given the option to add a trend line. As with the average line, you can customize the look of the trend line with a few simple options such as color and line style.</p><p>In the example below, we can see that sales over time are following a downward trend. This trend line is helpful for forecasting over short periods of time. If you know the approximate trend your data is following, you will be in a better position to estimate possible future values. Without this information, your eyes tend to focus only on the intense fluctuation in sales on a daily basis without being able to draw a meaningful conclusion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5xGBN3cH2zauSUe2.png" /></figure><h3>Using What-If Parameters in Power BI Visuals</h3><p>The what-if parameter feature in Power BI allows you to create custom ‘what-if’ scenarios ideal for forecasting. For example, a company may observe a 10% growth in sales year after year. However, what if they would like to forecast a range of different growth rates for the coming months or year and observe how this may affect the KPI’s in their Power BI report?</p><p>To do this quickly and easily, they can use what-if parameters.</p><p>In this tutorial, we will be adding a what-if parameter that allows us to dynamically adjust the growth rate for our opportunity value forecast.</p><p>We will visualize the effect in a line chart showing actual values and 3 months of forecasted opportunity values.</p><p>To add a what-if parameter, select the Modeling tab from the ribbon and then select ‘New Parameter’.</p><p>This will bring up a dialogue box where we can enter the name of the parameter (Opportunity Growth Rate), the data type (decimal), and then the values we would like the parameter to have (from -1 to 1 in increments of 0.01).</p><p>Enter the default value as 0 as this is the value that the parameter will take when no value is selected by the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DOk7HQkNElMydqii.png" /></figure><p>Next, it is important to check the option to add a slicer to the page since we will need this to be able to dynamically adjust our forecast growth rate.</p><p>In essence, this what-if parameter will create a table with a column for all the individual values that were specified in the range. It will also create a measure that returns the selected value from that table. We will use this measure in our calculations for the forecasted opportunity value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/0*xxQEaP3D8Va6D46_.png" /></figure><p>To see how this forecast works for future months, create a date table containing the current date range in the data as well as the dates for as many months into the future as you need. The forecasted time period that we will be using in this example is 3 months.</p><p>To calculate the forecasted sales, we need to create a measure with the following DAX formula:</p><p>Opportunity Forecast =</p><p>IF( MAX ( &#39;Opportunity Calendar&#39;[Date] ) &gt; DATE(2021, 09, 21), CALCULATE ( SUM ( Opportunities[Value] ), DATEADD ( &#39;Opportunity Calendar&#39;[Date], -1, YEAR ) ) * ( 1+&#39;Opportunity Growth Rate&#39;[Opportunity Growth Rate Value] ), SUM ( Opportunities[Value] ) )</p><p>This DAX formula will return the forecasted opportunity value (increased by the opportunity growth rate from our what-if parameter) if the dates fall above the latest date in our dataset (21 Sep 2021); otherwise, it will simply return the actual opportunity value. If you were applying this <strong>DAX formula</strong> to present-day data, you would need to replace the portion containing DATE(2021, 09, 21) with the function TODAY().</p><p>Lastly, we can add the actual opportunity value and this opportunity forecast measure to a line chart so that these two lines overlap each other. Change the format of the forecast line to a dashed line in order to see where the forecast starts. Now, we can dynamically adjust the growth rate from the slicer to change the forecast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/0*AV88l2DpBiMlwuX6.png" /></figure><h3>AI-Driven Features</h3><p>Power BI has taken giant steps toward incorporating more AI-driven features into the platform. This makes it easier and faster to uncover insights in our data even without specialized data science training.</p><h3>Anomaly Detection</h3><p>Anomaly detection is useful for quickly identifying potential issues or highlights by adding dynamic markers. However, it only works with time-series line charts. The idea is that the algorithm will determine the expected value for a given date; and then, based on a confidence interval, the actual value will either be regarded as an anomaly or not.</p><p>In the example below, anomaly detection was used on a revenue chart over time. For the selected date, the actual revenue is R90k while the expected revenue is R82k with a range of R79k — R85k. Therefore, this is considered to be an anomaly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LLNmLWnfUQ6_RE6L.png" /></figure><h3>Key Influencers</h3><p>Key influencers is a visualization option that shows how likely a particular metric is to occur based on the features you specify.</p><p>In the example below, an opportunity is 2.76 times more likely to have the status ‘Won’ if there is an increase in the discount of 0.02. This result is illustrated in the scatterplot to the right side of the visual.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*POl0U3BRzWxgRQs2.png" /></figure><p>The key influencers visual is very helpful for comparing the effect of multiple features against each other. This leads to faster insights into what feature is the most important contributor to a metric and could require further exploration.</p><h3>Decomposition Trees</h3><p>The decomposition tree is a visualization option that allows you to arrange features in a hierarchy and show the breakdown of a metric at each level in that hierarchy.</p><p>For example, the image below begins with the Sales Opportunity metric which is broken down into categories, products and then regions. In this way, you can see how sales is distributed across the elements of each level and which element is currently contributing the most towards sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c9R8unTcOEnnqBYO.png" /></figure><p>If you are not sure what the best breakdown for your metric is, you can use an option in the formatting for this visual called ‘AI splits’. If you enable this option, you can let Power BI choose the best feature to add based on whether it generates the highest or lowest value compared to the others.</p><p>The chart above was generated by selecting ‘High value’ for each level in the hierarchy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/0*O1dcH6lhk2GZDvXn.png" /></figure><h3>Smart Narratives</h3><p>Smart Narratives is a visualization option that creates a text box containing a written narrative of the key observation in the data. You can easily edit and format the text to add, remove, or highlight the most important parts for your users.</p><p>This feature is very useful for quickly adding key insights about your data to presentations or reports. The ability to customize these narratives means that you can tailor them towards the audience to which you are delivering the presentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*vAY0Ornei5sEfn1i.png" /></figure><h3>Context-Specific Insights</h3><p>These insights vary depending on the chart or the variations in your data. The types of insights you can generate are:</p><ul><li>Explain the increase</li><li>Explain the decrease</li><li>Find where the distribution is different (typically for the bar and column charts that compare categories).</li></ul><p>In the example below, we have right-clicked on a point that is slightly higher than the rest; and the option ‘Explain the increase’ appears in the Analyze section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DWYIYPJfP7CWeMdi.png" /></figure><p>Selecting this option gives a detailed analysis of many of the features in the dataset that could describe the possible reasons for this increase. The charts shown are typically waterfall charts, but you can also choose from a selection of other visualization types, such as scatterplots, column charts, and line charts. If any of the charts catch your eye and you want to add them to your report, you can simply click the plus icon at the top right-hand side of the chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/0*zWq38fXI9Iynh0Aj.png" /></figure><p>These contextual insights are very valuable when you want to generate fast insights. I have often used this feature to find points for further investigation and analysis into a sudden change in the data. This expedites my data exploration process because I do not need to start from scratch.</p><h3>Conclusion</h3><p>Using the tools in this tutorial, you’ll be able to produce dynamic, powerhouse analytical reports. Adding advanced Power BI skills to your arsenal will not only make you a more effective data scientist, but it can also unlock a broader array of career possibilities as Power BI is one of the most sought-after business intelligence skills in the job market.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0316b489cbb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the LAG() Function in SQL]]></title>
            <link>https://medium.com/@akoudadmehdi01/understanding-the-lag-function-in-sql-55b9b37d3f91?source=rss-ba63759cdaca------2</link>
            <guid isPermaLink="false">https://medium.com/p/55b9b37d3f91</guid>
            <category><![CDATA[sql-queries]]></category>
            <category><![CDATA[lag-function-examples]]></category>
            <category><![CDATA[sql-window-functions]]></category>
            <category><![CDATA[sql-analytics]]></category>
            <dc:creator><![CDATA[Mehdi Akoudad]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 17:49:56 GMT</pubDate>
            <atom:updated>2025-08-03T17:49:56.218Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Explore how the LAG() function allows you to access previous rows in your dataset, enabling time series analysis and comparisons of sequential observations.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5V4Yf7jiKKtzjejus4YOA.png" /></figure><p>SQL queries can do much more than retrieving or manipulating data. SQL has a lot of functions that enable us to do advanced analysis that can be crucial in our business intelligence reporting.</p><p>One of these powerful functions is the LAG() function, which is one of the commonly used <strong>window functions</strong>. It opens the door to comparing and calculating the change in values over a sequence of data. That is why the functions can be crucial, especially for time series analytics in SQL.</p><h3>The Short Answer: What is the LAG() Function?</h3><p>The LAG() function is one of SQL’s window functions that allows you to create a new column that accesses a previous row from another column. It gets its name from the fact that each row in the new column you create would be lagging to fetch a value from a preceding row in the other column you specify.</p><p>Let’s see the basic syntax in action. Suppose we have a simple two-column table with daily stock prices that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/0*xJVnrrbALORCAq4E.png" /></figure><p>.We can use the following query to create a new column that gets the price of the previous day in each row with the following query:</p><pre>SELECT date, <br>	price,<br>	LAG(price) OVER(ORDER BY date) AS one_day_before<br>FROM stock_price;</pre><p>And we would have the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/0*dWRTozutkOlxVnrO.png" /></figure><p>Notice that we have introduced one [null] value because there is no previous day&#39;s value for the first row.</p><h3>Basic Syntax of the LAG() Function</h3><p>The LAG() function is written as part of the SELECT clause. In its most basic syntax, the function can be written as follows:</p><pre>LAG(column1) OVER(ORDER BY column2)</pre><p>Here is the same LAG() function applied in a standalone query:</p><pre>SELECT <br>   column1, <br>   column2, <br>   LAG(column1) OVER (ORDER BY column2) AS previous_value <br>FROM <br>   table_name;</pre><p>As you can see, the basic syntax consists of several parts. Let’s break them down together:</p><ul><li><strong>column1:</strong> This is the column from which the earlier row’s value will be taken.</li><li><strong>OVER():</strong> OVER() is a mandatory keyword for every window function. The clause defines the frame over which the window function will run. In the above example, the window function will run over the ordered column2.</li><li><strong>ORDER BY:</strong> ORDER BY is not mandatory but it is highly recommended when used with the LAG() function; usually, the function does not make sense without it.</li><li><strong>column2:</strong> This column determines the order the LAG() function will follow. More than one column can be used as a basis for sorting.</li></ul><h3>Why Use the LAG() Function</h3><p>You might be wondering what is so great about the LAG() function. Well, the answer is that the new lagging column can be used to compare values from two different rows.</p><p>This is why the LAG() function is commonly used with time series data. For example, in our demo dataset, we can easily calculate the daily change in stock price with the following query:</p><pre>SELECT date, <br>	price,<br>	LAG(price) OVER(ORDER BY date) AS one_day_before,<br>	price - LAG(price) OVER(ORDER BY date) AS daily_change<br>FROM stock_price;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*ADY2V06FKB7TKNjO.png" /></figure><p>We can also graduate to a more sophisticated calculation and consider daily percent changes instead.</p><pre>SELECT date, <br>	price,<br>	LAG(price) OVER(ORDER BY date) AS one_day_before,<br>	price - LAG(price) OVER(ORDER BY date) AS daily_change,<br>	((price - LAG(price) OVER(ORDER BY date))*100 / <br>		(LAG(price) OVER(ORDER BY date))) AS daily_perc_change<br>FROM stock_price;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*mMdDWMajFlY6viGg.png" /></figure><h3>Advanced Usage of the LAG() Function</h3><p>Now, as we understand the basic use of the LAG() function, let’s level up our game step by step and see what else we can do with it.</p><p>Here we will be switching to another demo dataset that records the monthly revenue for three imaginary companies: Welsh LLC, Jones Group, and Green-Keebler, from the start of 2022 till mid-2024. This is how the data is structured:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/0*CRlm8BGQrWMmdmLL.png" /></figure><h3>Ordering by multiple columns</h3><p>In our new dataset, the lagging column should be ordered based on two columns: year and month. As we mentioned earlier, this can be done by giving the two columns to the ORDER BY clause.</p><p>In the following query we create a lagging column and a month-on-month (MoM) revenue difference column, ordered according to both year and month. We also filter our query with a WHERE clause to focus on one company for now.</p><pre>SELECT *,<br>	LAG(revenue) OVER(ORDER BY year, month) AS one_month_before,<br>	revenue - LAG(revenue) OVER(ORDER BY year, month) AS mom_difference<br>FROM revenues<br>WHERE company = &#39;Welch LLC&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/0*zBuKA-4fDjReYISr.png" /></figure><h3>Partitioning the LAG() frame</h3><p>Suppose we want to calculate the same two columns for the three companies that we have in our dataset. If we calculate them in the same way we have been using the LAG() function so far, the lagging column would be running over the three companies, and the difference column would be mixing between the revenues of all of them, and that is not what we want.</p><p>What we want is to get the previous month’s revenue, and calculate the MoM difference for each company alone, then start over for the new company.</p><p>To do this, we introduce a new clause in our LAG() function syntax. That clause is PARTITION BY, and it can be added to our basic syntax as follows:</p><pre>LAG(column1) OVER(PARTITION BY column3 ORDER BY column2)</pre><p>The column that we need to partition by in our example is company. So, we will be modifying our previous query by adding the PARTITION BY clause and taking out the WHERE statement.</p><pre>SELECT *,<br>	LAG(revenue) OVER(PARTITION BY company ORDER BY year, month) AS one_month_before,<br>	revenue - LAG(revenue) OVER(PARTITION BY company ORDER BY year, month) AS mom_difference<br>FROM revenues;</pre><p>In the result, we would see that the lagging and MoM columns now run over the monthly revenues of the first company alone, and then start over for the next one. We are able to see this in the screenshot below, which shows the last months of Green-Keebler and the first months of Jones Group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*gU91b5C-TrNgMBSn.png" /></figure><h3>Customizing the offset</h3><p>What if we do not need to fetch the value from the previous row, but from six rows or twelve rows above? In other words, what if we need to calculate the year-on-year (YoY) difference instead of the MoM?</p><p>In this case, we would add a new parameter to the LAG() function syntax. This parameter is called the offset, and it specifies how many rows above the current row we want the LAG() function to get the value from. Its position in the syntax is shown below:</p><pre>LAG(column1, offset) OVER(PARTITION BY column3 ORDER BY column2)</pre><p>By default, and by the way we have used the function so far, the value of the offset is equal to one. However, by explicitly specifying the offset in the LAG() expression, we can change this default parameter.</p><p>Back to our example, to get the YoY revenue change, we need to get the revenue for the same month in the previous year. We can do so with the following query, where we specify 12 as our offset:</p><pre>SELECT *,<br>	LAG(revenue, 12) OVER(PARTITION BY company ORDER BY year, month) AS one_year_before,<br>	revenue - LAG(revenue, 12) OVER(PARTITION BY company ORDER BY year, month) AS yoy_difference<br>FROM revenues;</pre><p>And the result would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/0*YC7ivvT_diFx4ZYK.png" /></figure><h3>Handling the NULLs</h3><p>You may have noticed that the LAG() function returns NULL in the rows where previous periods are not available, like in rows of the year 2022 in our previous query.</p><p>This is the default behavior of the LAG() function, but it can be altered by explicitly specifying a new parameter called “default”. This parameter can take any integer or float numerical value. In the function’s syntax, the parameter is positioned as follows:</p><pre>LAG(column1, offset, default) OVER(PARTITION BY column3 ORDER BY column2)</pre><p>The common use case of the “default” parameter is when the values actually start from zero in the time series data.</p><p>In our example, we can assume that the three companies were founded in January 2022 (the earliest date in our dataset), and therefore we can consider the revenue before the foundation as zero. By doing so, we will more accurately calculate the change in revenues, as any revenue gained in the first months would be a positive change.</p><p>In our query, we will be specifying zero as the “default” parameter in both of our LAG() expressions as follows:</p><pre>SELECT *,<br>	LAG(revenue, 12, 0) OVER(PARTITION BY company ORDER BY year, month) AS one_year_before,<br>	revenue - LAG(revenue, 12, 0) OVER(PARTITION BY company ORDER BY year, month) AS yoy_difference<br>FROM revenues;</pre><p>And the result would yield zeros in the lagging column, and the net revenue from zero in the YoY revenue change column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/0*Q6SQKMixxg_1GZZH.png" /></figure><p>Note that to be able to explicitly specify a value for the “default” parameter, it becomes mandatory to explicitly specify a value for the offset as well, as the first number given after the column name inside the LAG() function will be taken as the offset anyway.</p><p>If you need to change the “default” but not the offset, set the offset parameter as one, and it will behave as it normally does.</p><h3>Ordering After the LAG() Function</h3><p>It is useful to know that the order that the LAG() function depends on does not need to be the same order of the resulting view. You can always change that order by normally using the ORDER BY clause in your query.</p><p>In our example, we can reorder our result to show the same month of the same year for the three companies before moving to the next month of the year, by ordering the query according to year and month in the outer ORDER BYclause:</p><pre>SELECT *,<br>	LAG(revenue, 12, 0) OVER(PARTITION BY company ORDER BY year, month) AS one_year_before,<br>	revenue - LAG(revenue, 12, 0) OVER(PARTITION BY company ORDER BY year, month) AS yoy_difference<br>FROM revenues<br>ORDER BY year, month;</pre><p>And we would have what we need:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/0*435fGJCA88u_XOwJ.png" /></figure><h3>Common Mistakes and Best Practices</h3><p>Let’s take a look at common issues, in case you need help troubleshooting.</p><h3>Incorrect ordering</h3><ul><li><strong>Pitfall:</strong> Not specifying the ORDER BY clause in the LAG() statement can lead to incorrect results. Even if the original order of the source table is suitable for the function, never depend on that original order as it may change over time.</li><li><strong>Best Practice:</strong> Always use the ORDER BY clause in the LAG()statement, and make sure you order by the correct column.</li></ul><h3>Incorrect partitioning</h3><ul><li><strong>Pitfall:</strong> Incorrect LAG() frame due to overlooking the use of PARTITION BY clause or using it with the wrong column.</li><li><strong>Best Practice:</strong> Double check the partitions that your LAG() function runs over.</li></ul><h3>Incorrect offset</h3><ul><li><strong>Pitfall:</strong> Incorrect lagging values due to an incorrect offset.</li><li><strong>Best Practice:</strong> Double check the offset value that you need, and remember that the default offset value may not be what you need in some cases.</li></ul><h3>Improper NULLs</h3><ul><li><strong>Pitfall:</strong> Leaving the NULL values in the LAG() function output when another value is more proper, by not declaring the “default” parameter.</li><li><strong>Best Practice:</strong> Always consider what the values from before your dataset time series starts mean. In some cases, it is more proper to use zeros instead of nulls, as we saw in our example.</li></ul><h3>Declaring default without declaring offset</h3><ul><li><strong>Pitfall:</strong> Declaring the “default” parameter without declaring the offset means that “default” value would become the offset’s value.</li><li><strong>Best Practice:</strong> If you explicitly specified the “default” parameter, never forget to declare the offset as well.</li></ul><h3>Using aliases instead of function statement</h3><ul><li><strong>Pitfall:</strong> If you are using the same LAG() statement in more than one column, you would still have to write the full LAG() statement in the second column, not its alias. Using the alias of the first LAG() column would raise an error.</li><li><strong>Best Practice:</strong> Always write LAG() statements in full within the SELECTstatement.</li></ul><h3>Ignoring indexes</h3><ul><li><strong>Pitfall:</strong> The LAG() function, like all window functions, can be computationally expensive with large datasets. Therefore, ignoring the indexing of the columns used in the PARTITION BY and ORDER BYclauses can lead to poor performance.</li><li><strong>Best Practice:</strong> Ensure that the columns used in the PARTITION BY and ORDER BY clauses are indexed, if possible, to <strong>improve query performance</strong>.</li></ul><h3>Ignoring comments</h3><ul><li><strong>Pitfall:</strong> Without comments and documentation, LAG() and other window functions can get messy and not easy to read or understand, especially when more than one function is used.</li><li><strong>Best Practice:</strong> Whenever you are using LAG() and other window functions, make sure to add comments and document what the query tries to achieve. This helps others and yourself understand the purpose and logic behind LAG() usage, whenever the query is revisited.</li></ul><h3>Conclusion and Additional Resources</h3><p>In this tutorial, we have seen what the LAG() function is and how it can be a powerful tool to perform time series analytics. Additionally, we explored its arguments, and the clauses related to it. The next time you work with time-related, or any sequenced, data in SQL, consider the use of the LAG()function and what it enables you to do. In other contexts, the LAG() function is helpful in finding autocorrelations, smoothing data, or checking for irregular intervals as part of data cleaning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55b9b37d3f91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Mistakes I Made When Learning GROUP BY and HAVING in SQL]]></title>
            <link>https://python.plainenglish.io/5-mistakes-i-made-when-learning-group-by-and-having-in-sql-370d13023616?source=rss-ba63759cdaca------2</link>
            <guid isPermaLink="false">https://medium.com/p/370d13023616</guid>
            <category><![CDATA[having-clause]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[sql-best-practices]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[group-by]]></category>
            <dc:creator><![CDATA[Mehdi Akoudad]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 00:58:45 GMT</pubDate>
            <atom:updated>2025-08-03T00:58:45.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*71mU1i-nJRnW0qA6jUsUHQ.avif" /></figure><p><em>And what they taught me about writing smarter queries</em></p><p>When I first started using SQL for real-world data analysis, I thought I had a solid grasp of it. SELECT, WHERE, maybe even some JOINs. But once I started summarizing data, things got confusing — fast.</p><p>Here are the five biggest mistakes I made when working with GROUP BY and HAVING, and what I wish I had known earlier.</p><h3>1. I Aggregated Without Grouping — and Got Confused</h3><p>Aggregation sounds easy: just use AVG(), SUM(), or COUNT(). But I quickly learned that if you don’t pair them with GROUP BY, your results won’t always be useful.</p><p>For example, if you run:</p><pre>SELECT AVG(total) FROM sales;</pre><p>That gives you a single number. But what if you want to see the average per product line? That’s when you need to group:</p><pre>SELECT product_line, AVG(total) <br>FROM sales <br>GROUP BY product_line;</pre><p><strong>Lesson learned</strong>: Aggregation only becomes meaningful when you <strong>split your data first</strong>. Think “group, then aggregate.”</p><h3>2. I Tried to Use WHERE With Aggregate Functions</h3><p>I wanted to filter my grouped data — only show product lines where total gain was greater than 40,000. So I did this:</p><pre>SELECT product_line, SUM(total) AS total_gain<br>FROM sales<br>WHERE SUM(total) &gt; 40000<br>GROUP BY product_line;</pre><p>Result? An error.</p><p>Turns out, WHERE happens <strong>before</strong> grouping. You can’t use aggregate functions there.</p><p><strong>Fix</strong>: Use HAVING, which filters <strong>after</strong> grouping.</p><pre>SELECT product_line, SUM(total) AS total_gain<br>FROM sales<br>GROUP BY product_line<br>HAVING SUM(total) &gt; 40000;</pre><p><strong>Lesson learned</strong>: Use WHERE to filter rows <strong>before</strong> grouping, and HAVING to filter <strong>after</strong> aggregation.</p><h3>3. I Tried to Use Aliases in HAVING</h3><p>I got excited about writing clean queries, so I used aliases for my aggregates:</p><pre>SELECT product_line, SUM(total) AS total_gain<br>FROM sales<br>GROUP BY product_line<br>HAVING total_gain &gt; 40000;</pre><p>Another error.</p><p>Even though I <em>defined</em> total_gain, HAVING didn’t recognize it.</p><p><strong>Why?</strong> SQL executes in a different order than we write it. HAVING runs <strong>before SELECT</strong>, so it doesn’t know what total_gain means.</p><p><strong>Fix</strong>: Use the original expression.</p><pre>HAVING SUM(total) &gt; 40000;</pre><p><strong>Lesson learned</strong>: Aliases don’t exist yet in HAVING. Use raw expressions there.</p><h3>4. I Didn’t Understand the Execution Order</h3><p>I assumed SQL runs from top to bottom, like Python or R. But that’s not how SQL engines work.</p><p>Here’s the real execution order:</p><pre>FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT</pre><p>So when something “doesn’t work,” it’s often because I was writing my logic out of order — not understanding how SQL was actually interpreting my query.</p><p><strong>Lesson learned</strong>: Understanding <strong>SQL’s execution order</strong> helped me write better queries and debug faster.</p><h3>5. I Thought GROUP BY Was Only for COUNT()</h3><p>When I started, I used GROUP BY almost exclusively with COUNT(*).</p><p>But I missed its full power. You can combine it with AVG(), SUM(), MIN(), and MAX() to do deeper analysis. For example:</p><pre>SELECT product_line,<br>       AVG(unit_price) AS avg_price,<br>       SUM(quantity) AS total_pieces,<br>       SUM(total) AS total_gain<br>FROM sales<br>GROUP BY product_line<br>HAVING SUM(total) &gt; 40000<br>ORDER BY total_gain DESC;</pre><p>This shows not just frequency, but also revenue, quantity, and pricing insights — all from a single query.</p><p><strong>Lesson learned</strong>: GROUP BY is your key to <strong>summarizing</strong>, not just <strong>counting</strong>.</p><h3>Final Thoughts</h3><p>If you’re just getting into SQL or transitioning into analytics from another background, these mistakes are common — but avoidable.</p><p>Mastering GROUP BY and HAVING takes you from writing simple queries to building summaries, dashboards, and real insights.</p><p>Learn the order. Use the right filters. Don’t fear aggregate functions.</p><p>And most importantly, <strong>be intentional with your logic</strong>. SQL is not just about syntax — it’s about sequencing.</p><p><strong>Want to keep learning?</strong></p><p>Try this:</p><p>→ Recreate a sales summary for your own dataset using GROUP BY</p><p>→ Filter it with HAVING</p><p>→ Sort by an alias using ORDER BY</p><p>See what patterns you can uncover.</p><p>Thanks for reading — follow for more practical SQL breakdowns.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏️<strong>️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=370d13023616" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/5-mistakes-i-made-when-learning-group-by-and-having-in-sql-370d13023616">5 Mistakes I Made When Learning GROUP BY and HAVING in SQL</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use SQL PIVOT]]></title>
            <link>https://python.plainenglish.io/how-to-use-sql-pivot-1730c35bd14d?source=rss-ba63759cdaca------2</link>
            <guid isPermaLink="false">https://medium.com/p/1730c35bd14d</guid>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[data-transformation]]></category>
            <category><![CDATA[pivot-tables]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[oracle]]></category>
            <dc:creator><![CDATA[Mehdi Akoudad]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 00:58:39 GMT</pubDate>
            <atom:updated>2025-08-03T00:58:39.092Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*kIpmdkoqjAfiW2sV-eSKcQ.png" /></figure><blockquote>Enhance your SQL skills with the SQL PIVOT operator. Learn to convert rows into columns to create pivot tables in SQL Server and Oracle.</blockquote><p>The PIVOT operator in SQL Server and Oracle is an extremely useful technique that transforms table rows into columns. Not only does the PIVOT operator improve the readability and interpretation of query results, but it also makes it easier to understand data trends by using aggregations to create pivot tables or cross-tabulations. These pivot tables are particularly helpful in reports that require nice visualizations.</p><h3>The Quick Answer: How to Pivot in SQL</h3><p>The SQL Server PIVOT operator is useful when summarizing data since it allows for the transformation of rows into columns. Consider the city_sales table below, which shows the general sales of a product across five major US cities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/0*MLSHKGN03oPVoZjK.png" /></figure><p><em>Example of table to transform using SQL PIVOT.</em></p><p>We will use the following query, which uses the PIVOT operator, to pivot multiple columns in the above table.</p><pre>-- Select the columns for the output: city and sales data for 2019, 2020, and 2021<br>SELECT <br>    city,<br>    [2019] AS Sales_2019,<br>    [2020] AS Sales_2020,<br>    [2021] AS Sales_2021<br>FROM<br>    (<br>        -- Subquery to select city, year, and sales from city_sales table<br>        SELECT city, year, sales <br>        FROM city_sales<br>    ) AS src<br>PIVOT<br>(<br>    -- Pivot the sales data to have years as columns and sum the sales for each year<br>    SUM(sales)<br>    FOR year IN ([2019], [2020], [2021])<br>) AS pvt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/0*LioOB92Skyk_SJr-.png" /></figure><p><em>Example output transformation using SQL PIVOT.</em></p><h3>What is PIVOT in SQL</h3><p>Pivoting is a technique in SQL that is used to transform rows into columns in tabular data. In SQL Server and Oracle, pivoting is done with the PIVOT operator. The syntax for the SQL PIVOT operator, which is shown below, has three main parts:</p><ul><li><strong>SELECT</strong>: The SELECT statement references the columns to return in the SQL pivot table.</li><li><strong>Subquery</strong>: The subquery contains the data source or table to be included in the SQL pivot table.</li><li><strong>PIVOT</strong>: The PIVOT operator contains the aggregations and filter to be applied in the pivot table.</li></ul><pre>-- Select the non-pivoted column and the pivoted columns with aliases<br>SELECT <br>    [non-pivoted column],               <br>    [first pivoted column] AS [column name],   <br>    [second pivoted column] AS [column name],  <br>    ...<br>FROM<br>    (<br>        -- Subquery to select the necessary columns from the source table<br>        SELECT [columns] <br>        FROM [source_table]<br>    ) AS source_table<br>PIVOT<br>(<br>    -- Pivot operation to aggregate data and transform rows into columns<br>    [aggregate_function]([pivot_column])        <br>    FOR [pivot_column] IN ([first pivoted column], [second pivoted column], ...) <br>) AS pivot_table; -- Alias for the result of the pivot operation</pre><h3>Database-Specific Implementations of SQL PIVOT</h3><p>SQL Server and Oracle databases directly support the PIVOT operator. However, MySQL and PostgreSQL have alternative methods for creating pivot tables in SQL.</p><h3>PIVOT in SQL Server</h3><p>SQL Server provides native support for the PIVOT operator. Here, we will use the PIVOT operator to transform rows into columns and summarize data using aggregate functions like SUM(). We will also use SQL clauses, such as WHERE, GROUP BY, and ORDER BY for more refined data manipulation.</p><p>The example below demonstrates how to use the PIVOT operator to filter data for the year 2020 or later (WHERE), group data by city and year (GROUP BY), and sort the data by city (ORDER BY):</p><pre>-- Select the city and sales data for the years 2019, 2020, and 2021<br>SELECT <br>    city,                         <br>    [2019] AS Sales_2019,             <br>    [2020] AS Sales_2020,           <br>    [2021] AS Sales_2021              <br>FROM<br>    (<br>        -- Subquery to select city, year, and sales from the city_sales table<br>        SELECT city, year, sales <br>        FROM city_sales<br>        WHERE year &gt;= 2020 -- filtering<br>        GROUP BY city, year, sales -- grouping<br>    ) AS src                   <br>PIVOT<br>(<br>    -- Pivot the sales data to have years as columns, averaging the sales over each year<br>    SUM(sales) -- aggregating<br>    FOR year IN ([2019], [2020], [2021]) <br>) AS pvt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/0*J7Y2C7KyI12RYxnH.png" /></figure><p><em>Example output of transformed table using SQL PIVOT with common clauses.</em></p><h3>PIVOT in Oracle</h3><p>Similar to SQL Server, Oracle also uses the PIVOT operator to transform rows into columns. However, the syntax of the PIVOT operator in the Oracle database differs slightly from that in SQL Server. The query below shows how the PIVOT operator appears in Oracle. Note that the columns are aliased within the PIVOT operator, unlike the outer SELECT statement in SQL Server.</p><pre>-- Outer SELECT to choose all columns resulting from the PIVOT operation<br>SELECT *<br>FROM (<br>    -- Inner SELECT to retrieve the raw data of city, year, and sales<br>    SELECT city, year, sales<br>    FROM sales<br>)<br>-- PIVOT operation to convert rows to columns<br>PIVOT (<br>    SUM(sales) <br>    -- Specify the year values to pivot and alias them as Sales_&lt;year&gt;<br>    FOR year IN (2019 AS Sales_2019, 2020 AS Sales_2020, 2021 AS Sales_2021)<br>)<br>ORDER BY city;</pre><h3>Pivoting in MySQL</h3><p>The MySQL database does not support the SQL PIVOT operator. To create SQL pivot tables in MySQL, you must use the CASE statement with conditional aggregation. For example, the query below will create a pivot table to aggregate the data by the sum of sales for different years, grouped and ordered by city.</p><pre>-- Select the city and sum the sales data for the years 2019, 2020, and 2021<br>SELECT <br>    city,<br>    SUM(CASE WHEN year = 2019 THEN sales ELSE 0 END) AS Sales_2019,<br>    SUM(CASE WHEN year = 2020 THEN sales ELSE 0 END) AS Sales_2020,<br>    SUM(CASE WHEN year = 2021 THEN sales ELSE 0 END) AS Sales_2021<br>FROM <br>    city_sales <br>GROUP BY <br>    city<br>ORDER BY <br>    city;</pre><h3>Pivoting in PostgreSQL</h3><p>The PostgreSQL database also does not support the SQL PIVOT operator. Therefore, when creating pivot tables, it is important to use the CASE statement with conditional aggregation. The query below is an example of the conditional CASE statements used to create pivot tables in PostgreSQL.</p><pre>-- Select the city and sum the sales data for the years 2019, 2020, and 2021<br>SELECT <br>    city,<br>    SUM(CASE WHEN year = 2019 THEN sales ELSE 0 END) AS Sales_2019, <br>    SUM(CASE WHEN year = 2020 THEN sales ELSE 0 END) AS Sales_2020,<br>    SUM(CASE WHEN year = 2021 THEN sales ELSE 0 END) AS Sales_2021<br>FROM <br>    city_sales<br>GROUP BY <br>    city<br>ORDER BY <br>    city;</pre><h3>Advanced Techniques with SQL PIVOT</h3><p>There are some advanced SQL pivoting techniques for writing complex queries. In this section, we will look at dynamic pivoting, which we use to create queries for pivot tables where the columns to pivot are unknown. This method uses SQL to generate the pivot table at runtime.</p><h3>Dynamic PIVOT in SQL Server</h3><p>The query below uses PIVOT to dynamically pivot the year column in SQL Server. The query will retrieve distinct years from the city_sales table. It will then construct and execute a dynamic PIVOT query using the retrieved years.</p><pre>-- Declare variables to hold the column names and the dynamic query<br>DECLARE @cols AS NVARCHAR(MAX),<br>        @query AS NVARCHAR(MAX);<br>-- Get distinct values of the year column and concatenate them into a string<br>SELECT @cols = STRING_AGG(QUOTENAME(year), &#39;,&#39;) <br>               FROM (SELECT DISTINCT year FROM city_sales) AS years;<br>-- Construct the dynamic PIVOT query<br>SET @query = &#39;<br>SELECT city, &#39; + @cols + &#39;<br>FROM<br>(<br>    -- Subquery to select city, year, and sales from the city_sales table<br>    SELECT city, year, sales<br>    FROM city_sales<br>) AS src<br>PIVOT<br>(<br>    -- Pivot the sales data to have years as columns, summing the sales for each year<br>    SUM(sales)<br>    FOR year IN (&#39; + @cols + &#39;)<br>) AS pvt<br>ORDER BY city&#39;;  -- Order the results by city<br>-- Execute the dynamic PIVOT query<br>EXEC sp_executesql @query;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*lz6Zj297nHthj0td.png" /></figure><p><em>Example output of table using SQL dynamic PIVOT.</em></p><h3>Dynamic PIVOT in Oracle</h3><p>In the Oracle database, dynamic pivoting is supported by executing the dynamic query using the EXECUTE IMMEDIATE statement. The LISTAGG function is also used to dynamically aggregate the column names and single quotes &#39; &#39; used in aliases within the pivot.</p><pre>DECLARE<br>    cols VARCHAR2(4000);<br>    sql_query VARCHAR2(4000);<br>BEGIN<br>    -- Get the list of years dynamically<br>    SELECT LISTAGG(&#39;&#39;&#39;&#39; || year || &#39;&#39;&#39; AS &#39; || &#39;sales_&#39; || year, &#39;,&#39;) <br>    INTO cols<br>    FROM (SELECT DISTINCT year FROM city_sales);<br>    -- Construct the dynamic SQL query<br>    sql_query := &#39;SELECT * FROM (<br>                      SELECT city, year, sales<br>                      FROM city_sales<br>                  )<br>                  PIVOT (<br>                      SUM(sales)<br>                      FOR year IN (&#39; || cols || &#39;)<br>                  )<br>                  ORDER BY city&#39;;<br>    -- Execute the dynamic SQL query<br>    EXECUTE IMMEDIATE sql_query;<br>END;</pre><h3>Dynamic Pivoting in MySQL</h3><p>MySQL does not support direct dynamic SQL. Thus, you must create a stored procedure for dynamic PIVOT in MySQL. The query below shows how to use the stored procedure to create a dynamic PIVOT query.</p><pre>-- Declare variables to hold the dynamic columns (cols) and the final SQL query<br>DELIMITER $<br>CREATE PROCEDURE dynamic_pivot()<br>BEGIN<br>    DECLARE cols VARCHAR(1000);<br>    DECLARE sql_query VARCHAR(2000);<br>    -- Get the list of distinct years<br>    SELECT GROUP_CONCAT(DISTINCT<br>        CONCAT(&#39;SUM(CASE WHEN year = &#39;, year, &#39; THEN sales ELSE 0 END) AS &#39;, year, &#39;&#39;)<br>    ) INTO cols<br>    FROM city_sales;<br>    -- Construct the dynamic SQL query<br>    SET sql_query = CONCAT(&#39;SELECT city, &#39;, cols, &#39; FROM city_sales GROUP BY city ORDER BY city&#39;);<br>    -- Prepare and execute the SQL query<br>    PREPARE stmt FROM sql_query;<br>    EXECUTE stmt;<br>    DEALLOCATE PREPARE stmt;<br>END $<br>DELIMITER ;</pre><p>After creating the stored procedure, you must call the stored procedure to execute the dynamic PIVOT query:</p><pre>CALL dynamic_pivot();</pre><h3>Dynamic Pivoting in PostgreSQL</h3><p>Similarly, you can create a dynamic PIVOT in PostgreSQL using the following query:</p><pre>-- Block declaration to execute PL/pgSQL code in an anonymous code block<br>DO<br>$<br>DECLARE<br>    cols text;  -- Variable to store the list of columns for the dynamic query<br>    query text; -- Variable to store the dynamic SQL query<br>BEGIN<br>    -- Get distinct years and construct the list of SUM(CASE...) statements<br>    SELECT STRING_AGG(DISTINCT &#39;SUM(CASE WHEN year = &#39; || year || &#39; THEN sales ELSE 0 END) AS &quot;Sales_&#39; || year || &#39;&quot;&#39;, &#39;, &#39;)<br>    INTO cols<br>    FROM city_sales;<br>    -- Construct the dynamic PIVOT query<br>    query := &#39;SELECT city, &#39; || cols || &#39; FROM city_sales GROUP BY city ORDER BY city&#39;;<br>    -- Execute the dynamic PIVOT query<br>    EXECUTE query;<br>END<br>$;</pre><h3>Conclusion</h3><p>Understanding how to use PIVOT in SQL is important if you want to transform and analyze data efficiently. When creating pivot tables in SQL, learning the different implementations of the PIVOT operator in the different databases is crucial. As a data analyst, I encourage you to continue practicing your SQL skills to learn how and when to apply PIVOT to analyze different datasets.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏️<strong>️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1730c35bd14d" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/how-to-use-sql-pivot-1730c35bd14d">How to Use SQL PIVOT</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Subquery: A Comprehensive Guide]]></title>
            <link>https://medium.com/@akoudadmehdi01/sql-subquery-a-comprehensive-guide-8cbdc95dd44a?source=rss-ba63759cdaca------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cbdc95dd44a</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[subquery]]></category>
            <category><![CDATA[sql-queries]]></category>
            <category><![CDATA[database-management]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Mehdi Akoudad]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 17:28:32 GMT</pubDate>
            <atom:updated>2025-08-01T17:28:32.540Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EqADQaiflqk7KuPA0x-ezw.png" /></figure><blockquote>Discover how to master SQL subqueries to enhance your database queries. Learn about correlated, non-correlated, and recursive subqueries. Learn about execution order and how to combine SQL subqueries with other SQL features.</blockquote><p>SQL subqueries are a powerful tool in database management, allowing for more complex and efficient data retrieval. This guide will walk you through the fundamentals of SQL subqueries, offering insights into their practical applications and advanced techniques. Whether you’re a beginner or an experienced professional, mastering subqueries can significantly enhance your SQL skills.</p><h3>What is a SQL Subquery?</h3><p>A subquery allows SQL queries to be more modular by handling tasks that would otherwise require multiple separate queries.</p><h3>Definition and purpose</h3><p>A SQL subquery is a query nested within another SQL query, used to perform operations that require multiple steps or complex logic. The role of subqueries in SQL include the following:</p><ul><li>Filtering records based on data from related tables.</li><li>Aggregating data and performing calculations dynamically.</li><li>Cross-referencing data between tables to retrieve specific insights.</li><li>Conditionally selecting rows without requiring explicit joins or external code logic.</li></ul><p>It sounds like a lot, but it will make sense as we explore these things in the tutorial.</p><h3>Types of subqueries</h3><p>It might surprise you to learn that there are different types of subqueries. The different types are grouped based on and suited to different kinds of data retrieval needs. You can choose from the following subqueries depending on the operation you want to perform:</p><h4>Scalar subqueries</h4><p>Scalar subqueries return a single value, such as one row and one column. They are often used where a single value is expected, such as in calculations, comparisons, or assignments in SELECT or WHERE clauses.</p><p>In the example below, the scalar subquery (SELECT AVG(salary) FROM employees) returns a single value, the average salary, and compares it to each employee&#39;s salary.</p><pre>-- Example of Scalar Subquery <br>-- Compares each salary to the average salary<br>SELECT employee_name, <br>       salary,<br>       (SELECT AVG(salary) FROM employees) AS average_salary <br>FROM employees<br>WHERE salary &gt; (SELECT AVG(salary) FROM employees);</pre><h4>Column subqueries</h4><p>Column subqueries return a single column but multiple rows. These subqueries are often used with operators like IN or ANY, where the outer query compares values from multiple rows.</p><p>For example, the subquery below returns a list of department IDs for departments located in New York, which the main query then uses to filter employees in those departments.</p><pre>-- Example of Column Subquery <br>-- Filters based on departments in New York<br>SELECT employee_name<br>FROM employees<br>WHERE department_id IN (SELECT department_id FROM departments WHERE location = &#39;New York&#39;);</pre><h4>Row subqueries</h4><p>Row subqueries return a single row containing multiple columns. These subqueries are typically used with comparison operators that can compare a row of data, such as the = or IN operators, when multiple values are expected.</p><p>The following subquery retrieves a manager’s department and job title, and the outer query finds employees with matching values.</p><pre>-- Example of Row Subquery <br>-- Matches department and job title with a specific manager<br>SELECT employee_name<br>FROM employees<br>WHERE (department_id, job_title) = (SELECT department_id, job_title FROM managers WHERE manager_id = 1);</pre><h4>Table subqueries (derived tables)</h4><p>Table subqueries, or derived tables, return a complete table of multiple rows and columns. These are commonly used in the FROM clause as a temporary table within a query.</p><p>For example, the subquery below creates a derived table of average salaries by department, which is then used in the outer query to find departments with an average salary above a specified threshold.</p><pre>-- Example of Table Subquery <br>-- Uses derived table for average department salary comparison<br>SELECT dept_avg.department_id, dept_avg.avg_salary<br>FROM <br>    (SELECT department_id, AVG(salary) AS avg_salary FROM employees GROUP BY department_id) AS dept_avg<br>WHERE dept_avg.avg_salary &gt; 50000;</pre><h3>Understanding SQL Subqueries</h3><p>From the above examples, we have seen that a subquery is enclosed within parentheses.</p><h3>Syntax and structur</h3><p>The syntax of a subquery varies depending on where it is used in the main SQL statement, such as within SELECT, FROM, or WHERE clauses. Subqueries are typically enclosed in parentheses ( ), indicating a separate query.</p><p>The following example demonstrates a subquery within a WHERE clause, allowing us to filter data in the main query based on the results of a nested query.</p><pre>-- Selects the main column to retrieve from the main table to query<br>SELECT column_name<br>FROM table_name<br>-- Applies a condition to filter rows based on the subquery result<br>WHERE column_name operator <br>      -- Subquery retrieves data for comparison in the WHERE clause<br>      (SELECT column_name FROM table_name WHERE condition);</pre><h3>Execution order</h3><p>The execution order for subqueries depends on whether they are correlated or non-correlated.</p><h4>Non-correlated subqueries</h4><p>Non-correlated subqueries are independent of the outer query and execute first. The subquery’s result is then passed to the outer query. Non-correlated subqueries are commonly used for scalar or column-level calculations and filters.</p><p>The query below follows the execution order:</p><ul><li>The subquery (SELECT AVG(salary) FROM employees) runs first and calculates the average salary.</li><li>The outer query then retrieves employees whose salary is greater than this average.</li></ul><pre>-- Retrieves names of employees with above-average salary<br>SELECT employee_name  <br>FROM employees<br>-- Subquery: calculates average salary across all employees<br>WHERE salary &gt; (SELECT AVG(salary) FROM employees);</pre><h4>Correlated subqueries</h4><p>Correlated subqueries depend on the outer query for some of their data, so they are re-evaluated for each row processed by the outer query.</p><p>The following query executes in this order:</p><ul><li>For each row in employees (aliased as e1), the subquery (SELECT AVG(e2.salary) FROM employees e2 WHERE e2.department_id = e1.department_id) calculates the average salary for that specific department.</li><li>The outer query then compares each employee’s salary with the department’s average salary and includes only those who earn more.</li></ul><pre>-- Retrieves names of employees with above-average salary in their department<br>SELECT e1.employee_name  <br>FROM employees e1<br> -- Subquery: calculates average salary for each department<br>WHERE e1.salary &gt; (SELECT AVG(e2.salary) FROM employees e2 WHERE e2.department_id = e1.department_id);</pre><h3>Applications of the SQL Subquery</h3><p>SQL subqueries are important for data retrieval and transformation, allowing you to write complex queries and handle advanced data analysis tasks. The following are real-world applications of subqueries in database management.</p><h3>Filtering data</h3><p>Subqueries are useful when filtering data based on dynamic conditions, especially when filtering requires comparing values across multiple tables or performing calculations.</p><p>The following subquery retrieves the category_id of &quot;Product A,&quot; and the main query finds all products in that category.</p><pre>-- Retrieves names of products in the same category as &#39;Product A&#39;<br>SELECT product_name  <br>FROM products<br> -- Subquery: finds category ID of &#39;Product A&#39;<br>WHERE category_id = (SELECT category_id FROM products WHERE product_name = &#39;Product A&#39;);</pre><h3>Data aggregation</h3><p>Subqueries are also used for data aggregation, especially when generating summary statistics or insights for reporting and analysis. The subquery (SELECT department_id, AVG(sales) AS avg_sales FROM sales GROUP BY department_id) calculates the average sales per department. The outer query then filters departments with an average sales above 50,000.</p><pre>-- Retrieves department IDs and their average sales<br>-- Filters for departments with average sales over 50,000<br>SELECT department_id, avg_sales  <br>FROM (SELECT department_id, AVG(sales) AS avg_sales FROM sales GROUP BY department_id) AS dept_sales  -- Subquery: calculates average sales per department<br>WHERE avg_sales &gt; 50000;</pre><h3>Performance Considerations and Best Practices</h3><p>Although subqueries are powerful when writing complex queries, they may impact performance, especially when working with large datasets. It is important to consider the common pitfalls and best practices for improved performance.</p><h3>Optimizing subquery performance</h3><p>Optimizing subquery performance ensures improved query execution time and database responsiveness. The following are ways to optimize the subquery.</p><ul><li><strong>Index Relevant Columns:</strong> To speed up data retrieval, ensure that columns used in WHERE and JOIN clauses and comparison operations are indexed.</li><li><strong>Limit the Use of Correlated Subqueries:</strong> Where possible, use JOIN operations or CTEs instead of correlated subqueries, as they can often process data faster by using set operations rather than row-by-row processing.</li><li><strong>Limit the Number of Columns in Subqueries:</strong> Select only the columns you need in subqueries to minimize data retrieval, reduce memory usage, and allow the database to optimize execution.</li><li><strong>Use EXISTS instead of IN: </strong>If a subquery returns a large dataset, using EXISTS rather than IN can improve performance. The EXISTS operator will stop query processing when it finds a matching row, while the IN operator continues to evaluate the entire subquery result.</li></ul><h3>Avoiding common pitfalls</h3><p>When you write subqueries incorrectly, you may encounter problems with executing them. Let us look at how to avoid these pitfalls.</p><ul><li><strong>Avoid Unnecessary Correlated Subqueries:</strong> Correlated subqueries are resource-intensive, so avoid using them when the result can be achieved with a non-correlated subquery or a join.</li><li><strong>Be Mindful of NULL Values in Subqueries:</strong> NULL values can lead to unexpected results, especially in subqueries that use comparison operators like IN or =. To avoid errors, consider using COALESCE to handle nulls or ensuring that columns are not nullable if used for comparisons.</li><li><strong>Avoid Using SELECT * in Subqueries: </strong>Using SELECT * can lead to inefficiencies, as it retrieves all columns, even if you don’t need them. This increases memory usage and can slow query execution, especially with large datasets.</li><li><strong>Use Meaningful Aliases:</strong> Clearly name your tables and subqueries to improve readability.</li></ul><h3>More Advanced SQL Subquery Techniques</h3><p>While subqueries offer an efficient way to write complex queries, advanced methods for handling hierarchical data exist. Let’s examine the advanced techniques and strategies for applying SQL subqueries.</p><h3>Recursive subqueries</h3><p>Recursive subqueries (also known as recursive common table expressions or CTEs) allow you to retrieve hierarchical data, such as organizational structures, product categories, or graph-based relationships, where each item in the data is linked to another.</p><p>Suppose you have a table employees with employee_id, manager_id, and employee_name. You want to retrieve the hierarchy of employees under a specific manager.</p><pre>WITH RECURSIVE EmployeeHierarchy AS (<br>    -- Anchor Query: Start with the specified manager<br>    SELECT employee_id, manager_id, employee_name, 1 AS level<br>    FROM employees<br> -- Assuming the top-level manager has NULL as manager_id<br>    WHERE manager_id IS NULL <br>    <br>    UNION ALL<br>    <br>    -- Recursive Query: Find employees who report to those in the previous level<br>    SELECT e.employee_id, e.manager_id, e.employee_name, eh.level + 1<br>    FROM employees e<br>    INNER JOIN EmployeeHierarchy eh ON e.manager_id = eh.employee_id<br>)<br>SELECT * FROM EmployeeHierarchy;</pre><p>In the above query:</p><ul><li>What I call the Anchor Query selects the top-level manager (where manager_id is NULL).</li><li>The Recursive Query joins employees with the CTE itself (EmployeeHierarchy), finding employees who report to each previously retrieved employee.</li><li>The recursion continues until no more employees are reporting to the ones found.</li></ul><h3>Combining subqueries with other SQL features</h3><p>You can integrate subqueries with other SQL features like <strong>window functions</strong>, CASE statements, and grouping functions. These combinations allow for advanced data manipulation and more comprehensive reporting.</p><h4>Combining subqueries with window functions</h4><p>Subqueries can be used to refine the dataset that window functions act on, making them useful for ranking, cumulative totals, and moving averages. Suppose you want to rank products by sales within each region. You can use a subquery to select the relevant data and then apply a window function for ranking.</p><pre>-- Ranks products by sales within each region<br>SELECT region, product_id, sales, <br>       RANK() OVER (PARTITION BY region ORDER BY sales DESC) AS sales_rank <br>-- Subquery: calculates total sales per product in each region<br>FROM (SELECT region, product_id, SUM(sales) AS sales  <br>      FROM sales_data<br>      GROUP BY region, product_id) AS regional_sales;</pre><h4>Using subqueries with CASE statements</h4><p>Combining subqueries with CASE statements can help you apply complex conditions based on dynamic calculations. The following query classifies products as “High”, “Medium”, or “Low” performers based on their sales relative to the average sales for their category.</p><pre>-- Categorize above-average sales, average sales, and below-average sales<br>SELECT product_id, category_id, sales,<br>       CASE <br>           WHEN sales &gt; (SELECT AVG(sales) FROM products WHERE category_id = p.category_id) THEN &#39;High&#39; <br>           WHEN sales = (SELECT AVG(sales) FROM products WHERE category_id = p.category_id) THEN &#39;Medium&#39; <br>           ELSE &#39;Low&#39;<br>       END AS performance<br>FROM products AS p;</pre><h4>Subqueries with aggregate functions for conditional aggregation</h4><p>You can also calculate conditional aggregates using subqueries within aggregate functions. Suppose you want to calculate the total revenue generated only by active customers. In the example below, the subquery retrieves all active customers. The main query then filters orders to include only those placed by active customers, calculating the total revenue from this group.</p><pre>-- Calculates total revenue from active customers<br>SELECT SUM(order_total) AS active_customer_revenue <br>FROM orders<br>  -- Subquery: retrieves IDs of active customers<br>WHERE customer_id IN (<br>    SELECT customer_id<br>    FROM customers<br>    WHERE status = &#39;Active&#39;<br>);</pre><h3>When SQL Subqueries are Used</h3><p>SQL subqueries offer versatile real-world applications for data analysis, which is why they are used so frequently. The following are some industry-specific or mathematical applications of SQL subqueries. To come up with these ideas, I tried to think about data analysis or data engineering jobs that require multiple steps, which is, in my opinion, where subqueries really help.</p><h3>Industry-specific examples</h3><p>Subqueries can offer useful solutions in finance, healthcare, and retail industries. Here are some ideas:</p><ul><li><strong>Risk Assessment for Loan Approvals (Finance):</strong> I picture banks juggling metrics like debt-to-income ratios and credit scores. By nesting these metrics in subqueries, analysts can make better sense of complicated financial metrics. Maybe, a subquery can calculate the average loan amount for customers within specific income brackets.</li><li><strong>Identifying Patterns in Patient Diagnoses (Healthcare):</strong> In healthcare, managing patient data can be a big job. Subqueries could help break down this complexity. I imagine using subqueries to track diagnosis frequencies across different age groups or risk factors.</li><li><strong>Optimizing Product Placement Based on Purchase History (Retail):</strong> Retailers thrive on understanding purchasing patterns. Subqueries can show nested purchase data to identify which products are often bought together. This could help in strategically placing complementary items and boosting sales.</li></ul><h3>Mathematical connections</h3><p>Subqueries are also used to identify data patterns and trends in mathematical and logical connections. The following are some scenarios where subqueries are applied in mathematics.</p><ul><li><strong>Moving Averages for Time-Series Analysis:</strong> When analyzing trends over time, subqueries simplify calculating moving averages. I see them defining specific time windows within nested queries, making it easier to smooth data and spot trends.</li><li><strong>Detecting Outliers Using Standard Deviations:</strong> Spotting outliers is importing for lots of things, including things like fraud detection. Subqueries make it straightforward to compute computed metrics like standard deviations within nested queries.</li><li><strong>Using Set Theory Concepts:</strong> I find it interesting how subqueries mirror set theory operations like UNION and INTERSECT. This capability is perfect for tasks like customer retention analysis, where understanding overlaps and differences between customer groups can drive smarter marketing strategies.</li></ul><h3>Conclusion</h3><p>Mastering SQL subqueries can significantly enhance your ability to manage and analyze data efficiently. By understanding their structure, applications, and best practices, you can optimize your SQL queries for better performance. Also, I want to say that mastering subqueries just makes writing SQL easier, so it’s worth learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cbdc95dd44a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use the SQL REPLACE() Function]]></title>
            <link>https://medium.com/@akoudadmehdi01/how-to-use-the-sql-replace-function-8d1940c2882c?source=rss-ba63759cdaca------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d1940c2882c</guid>
            <category><![CDATA[database-management]]></category>
            <category><![CDATA[text-manipulation]]></category>
            <category><![CDATA[data-transformation]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <dc:creator><![CDATA[Mehdi Akoudad]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 12:38:49 GMT</pubDate>
            <atom:updated>2025-08-01T12:38:49.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6_f9OL4ky0mEThoD4PdhA.png" /></figure><blockquote>Learn the application of the SQL REPLACE() function in text manipulation. Understand the use of the REPLACE() function in data cleaning and database management.</blockquote><p>The SQL REPLACE() function is useful for text manipulation. The REPLACE()function changes a part of a string with another specified substring. In most cases, the SQL REPLACE() function is used to modify all the substring occurrences within a string in a given dataset.</p><p>Text manipulation is important in SQL as it helps clean data for efficient analysis. The technique also helps in data transformation and optimization for improved performance.</p><h3>The Quick Answer: How to Use SQL REPLACE()</h3><p>The SQL REPLACE() function alters or substitutes all string occurrences with a specified substring or string. In the example below, the REPLACE() function in SQL has replaced the value old with new in the description column. The query will execute each row to replace the old string with a new one.</p><pre>-- Select the description column from the products table,<br>-- replacing occurrences of &#39;old&#39; with &#39;new&#39;<br>SELECT <br>    REPLACE(description, &#39;old&#39;, &#39;new&#39;) AS updated_description<br>FROM <br>    Products;</pre><p><strong>Note:</strong> MySQL, PostgreSQL, Oracle, and SQL Server databases all support the REPLACE() function.</p><h3>Understanding the SQL REPLACE() Function</h3><p>The REPLACE() function in SQL searches for the specified substring or string in a column and replaces it with another given string. The example below shows the basic use of the REPLACE() function. The arguments in the function include:</p><ul><li><strong>string:</strong> The original string where you are supposed to make the replacement.</li><li><strong>old_substring:</strong> The substring to be replaced.</li><li><strong>new_substring:</strong> The substring to replace the old one.</li></ul><pre>REPLACE(string, old_substring, new_substring)</pre><p>When using the REPLACE() function to alter the strings in a table, the query will have the following syntax where:</p><ul><li><strong>column_name:</strong> The column used to search the substring occurrences.</li><li><strong>old_substring:</strong> The substring to be replaced.</li><li><strong>new_substring:</strong> The substring to replace the old one.</li></ul><pre>-- Select the description column from the products table,<br>-- replacing occurrences of &#39;old&#39; with &#39;new&#39;<br>SELECT <br>    REPLACE(column_name, &#39;old_substring&#39;, &#39;new_substring&#39;) AS updated_column<br>FROM <br>    Products;</pre><h3>Detailed Examples and Use Cases</h3><p>There are many important use cases of the SQL REPLACE() function in text manipulation and data transformation. They include the following:</p><h3>Basic replacement</h3><p>You can use the SQL REPLACE() function to perform a basic replacement. Let&#39;s assume we have the following table in our SQL Server database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/0*kb7u9iuF-qMQl8se.png" /></figure><p><em>Products table example.</em></p><p>Using the following SQL query, you can use the REPLACE() function to change the old status to new.</p><pre>SELECT <br>    product_id,<br>    product_name,<br>    price,<br>    REPLACE(status, &#39;old&#39;, &#39;new&#39;) AS updated_status<br>FROM Products;</pre><p>The resulting table will look like the one shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/0*hirOHZrhp70ulY1d.png" /></figure><p><em>Table updated with SQL REPLACE().</em></p><h3>Replacing multiple substrings</h3><p>If you want to replace multiple substrings, use chained multiple REPLACE()functions. Here, we are updating the value old with outdated, and new with fresh.</p><pre>-- Chain multiple REPLACE() functions to replace &#39;old&#39; with &#39;outdated&#39; and &#39;new&#39; with &#39;fresh&#39;<br>SELECT <br>    product_id,<br>    product_name,<br>    price,<br>    REPLACE(REPLACE(status, &#39;old&#39;, &#39;outdated&#39;), &#39;new&#39;, &#39;fresh&#39;) AS updated_status<br>FROM Products;</pre><p>The resulting table is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/0*mnY8JUeQLcrHabkp.png" /></figure><p><em>Table updated using multiple substrings. Image by Author.</em></p><h3>Handling case sensitivity</h3><p>Since the REPLACE() function transforms string data types, it is case-sensitive and will only modify the substrings that match the exact case of old_substring. Therefore, it is important to note the original case values before using the REPLACE() function.</p><p>When you want to replace values that are not case-sensitive, you should use the UPPER() or LOWER() functions to convert the text before replacement. This technique ensures consitency.</p><pre>-- Replace &#39;OLD&#39; with &#39;OUTDATED&#39;, handling case sensitivity by converting to upper case<br>SELECT <br>    product_id,<br>    product_name,<br>    price,<br>    REPLACE(UPPER(status), &#39;OLD&#39;, &#39;OUTDATED&#39;) AS updated_status<br>FROM Products;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/0*rJyY9lqF8BTWVMUw.png" /></figure><p><em>Table updated using the REPLACE() and UPPER() functions.</em></p><pre>-- Replace &#39;old&#39; with &#39;outdated&#39;, handling case sensitivity by converting to lowercase<br>SELECT <br>    product_id,<br>    product_name,<br>    price,<br>    REPLACE(LOWER(status), &#39;old&#39;, &#39;outdated&#39;) AS updated_status<br>FROM Products;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/0*T1HV8WHNX1F_ef6Y.png" /></figure><p><em>Table updated using the SQL REPLACE() and LOWER() functions.</em></p><h3>Advanced Techniques</h3><p>Let’s now take a look at some even more advanced techniques involving REPLACE().</p><h3>Replacing with dynamic values</h3><p>The REPLACE() function can be used to perform dynamic replacements by using a combination of other SQL functions. For example, using the REPLACE()function, you can use the value of another column to replace the substring. In the example below, the REPLACE() function replaces each old product with the actual value from product_name.</p><pre>-- Replace &#39;old&#39; with the value from product_name column<br>SELECT <br>    product_id,<br>    product_name,<br>    price,<br>    REPLACE(status, &#39;old&#39;, product_name) AS updated_status<br>FROM Products;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*lLkjyVfGfpkXByTx.png" /></figure><p><em>Table updated using REPLACE() function and dynamic values.</em></p><h3>Using REPLACE() in UPDATE statements</h3><p>The SQL REPLACE() function is used within the UPDATE function to modify the values in a table. The UPDATE function mainly changes a table&#39;s columns or values. For example, the query below will update the value old with outdated in the column status.</p><pre>-- Update the status column to replace &#39;old&#39; with &#39;outdated&#39;<br>UPDATE Products<br>SET status = REPLACE(status, &#39;old&#39;, &#39;outdated&#39;)<br>WHERE status LIKE &#39;%old%&#39;;</pre><h3>Combining REPLACE() with other string functions</h3><p>One advanced technique for using the REPLACE() function is combining other string functions, such as CHARINDEX() or SUBSTRING(), when replacing string values.</p><p>We can enhance the REPLACE() function by combining it with other string functions, such as CHARINDEX() or SUBSTRING(), for more effective string manipulation.</p><pre>-- Replace part of the product name starting from the first space with &#39;Updated&#39;<br>SELECT <br>    product_id,<br>    product_name,<br>    price,<br>    -- Extract the substring of product_name starting from the first space to the end<br>    REPLACE(product_name, SUBSTRING(product_name, CHARINDEX(&#39; &#39;, product_name), LEN(product_name)), &#39; Updated&#39;) AS updated_product_name<br>FROM Products;</pre><p>The resulting table from the above query is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/0*8ckPI1kvEcgh9Kz8.png" /></figure><p><em>Table updated using REPLACE() and other string functions.</em></p><h3>Replacing NULL with 0</h3><p>You can use the COALESCE() function to replace the NULL value with 0, as you can see in the query below.</p><pre>-- Replace NULL with &#39;new&#39; in the status column<br>SELECT <br>    product_id,<br>    product_name,<br>    price,<br>    REPLACE(COALESCE(status, &#39;NULL&#39;), &#39;NULL&#39;, 0) AS updated_status<br>FROM Products;</pre><h3>Practical Applications of the SQL REPLACE() Function</h3><p>Now that we have explored how to use REPLACE(), let’s consider some of the practical applications.</p><ul><li><strong>Data Cleaning:</strong> The REPLACE() function is useful for data cleaning, removing, and replacing unwanted characters or spaces in strings within a dataset.</li><li><strong>Data Transformation:</strong> The REPLACE() function is used in data transformation to change values into different formats and replace outdated values with new values.</li><li><strong>Handling User Inputs:</strong> The REPLACE() function is important in adjusting and converting user input data to a uniform standard acceptable in a specific database. This technique helps in ensuring uniformity in the database.</li><li><strong>Text Standardization:</strong> The REPLACE() function standardizes values in string columns to ensure uniformity, such as abbreviations in lowercase or uppercase formats.</li><li><strong>Conditional Replacement:</strong> The REPLACE() function is also useful for easy database management practices to replace values according to specific rules.</li></ul><h3>Database-Specific Implementations and Considerations</h3><p>MySQL, PostgreSQL, Oracle, and SQL Server databases all support the REPLACE() function in SQL, which has a similar syntax in these databases.</p><pre>-- Replace &#39;old&#39; with &#39;new&#39; in the status column<br>SELECT <br>    product_id,<br>    product_name,<br>    price,<br>    REPLACE(status, &#39;old&#39;, &#39;new&#39;) AS updated_status<br>FROM Products;</pre><h3>Performance Considerations and Best Practices</h3><p>When using the REPLACE() function, it is important to note the following performance considerations and best practices.</p><h3>Impact on query performance</h3><p>The REPLACE() function may impact query performance, especially when handling large datasets. This issue occurs since the function updates the table by each row and may take a while for the query to execute.</p><h3>Indexing considerations</h3><p>It is important to ensure proper indexing of the columns for optimal performance.</p><h3>Monitoring and resolving performance bottlenecks</h3><p>To resolve the issues involved with query performance, it is important to consider the following best practices:</p><ul><li>Use database profiling tools to monitor query performance and optimize when handling large datasets.</li><li>When using REPLACE() to modify the string values, maintain the indexes regularly to ensure they match.</li><li>Initiate batch processing to reduce query execution time when handling large datasets.</li></ul><h3>Conclusion and Further Learning</h3><p>As we have seen, the REPLACE() function in SQL changes a part of a string with another one. Applying the REPLACE() function is important for different data cleaning and transformation practices. It is important to continue practicing the use and different scenarios where you can apply the REPLACE() function to manipulate and update string data types.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d1940c2882c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>