<?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 Alexandra Petra Berger on Medium]]></title>
        <description><![CDATA[Stories by Alexandra Petra Berger on Medium]]></description>
        <link>https://medium.com/@alexandra.petra.berger?source=rss-1e137cf52e2c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r5oIq30XBfjfFNzSAqw9CQ.png</url>
            <title>Stories by Alexandra Petra Berger on Medium</title>
            <link>https://medium.com/@alexandra.petra.berger?source=rss-1e137cf52e2c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:16:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexandra.petra.berger/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[ “Poyekhali!”: What 1961 Soviet Space Tech Teaches Us About Modern Data Engineering]]></title>
            <link>https://medium.com/towards-data-engineering/poyekhali-what-1961-soviet-space-tech-teaches-us-about-modern-data-engineering-1549445a054f?source=rss-1e137cf52e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1549445a054f</guid>
            <category><![CDATA[history]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[space-exploration]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[clickhouse]]></category>
            <dc:creator><![CDATA[Alexandra Petra Berger]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 05:21:09 GMT</pubDate>
            <atom:updated>2026-04-13T05:21:09.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVNPziGZU7V1uF3Vpqo_TQ.png" /><figcaption>the image is AI generated, neglect the inaccuracies</figcaption></figure><h4>April 12th is a date ordinary for many, but special for post-USSR space: April 12th, 1961 was a day when a man called Yuri Gagarin said “Poyekhali!” (“Let’s go!”) and became the first human in history to take off from the earth in an automatically piloted rocket R-7 and went out to space for the first time. Whereas in 1961 “fuel” was kerosene and liquid oxygen, in this day and age it is data. Both piercing a space with a rocker and governing data with data engineering principles serve to solve the same problem: safe delivery of a valuable cargo from A to B through an aggressive environment. We look closely at several parallels of the Soviet spaceship design approaches to borrow some key principles to modern data engineering in 2026. We take a look through the lens of “The Chief Designer’s” (Sergei Korolev) philosophy: <strong><em>Simplicity is the ultimate sophistication.</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*c75KpKjjTmWuaNm2h74roQ.jpeg" /><figcaption>Gagarin and Korolev</figcaption></figure><p>With petabytes of data flowing through modern enterprises, key engineers find themselves in a large data swamp: too many different data, systems, principles and purposes. Compared to past era, where lack of resources presented a problem, now DE are yet fighting the same battles as the Chief Designer (Sergei Korolev): Latency, Bandwidth, and Reliability. Even thinking we are very “high-tech” today.</p><p>Computing power in 1961 was negligible, whilst the stakes were extremely high. The limitations gave the birth of the genius <strong>Vostok-1 </strong>“Systems Engineering” mindset: Engineers had to write code as efficiently and concisely as possible.</p><h4><strong>Why Data Engineers Should Care</strong></h4><p>With the rising cost of cloud computing (Snowflake, BigQuery), query optimization is back in vogue: a good data engineer doesn’t just “add RAM”; they optimize partitioning and resource usage to avoid burning through the company’s budget.</p><h3>1: The Modular Rocket Architecture</h3><blockquote><strong>Just as the R-7 drops its side boosters to gain speed, our data sheds its ‘noise’ as it moves toward the final Gold layer.</strong></blockquote><p>The R-7 was an engineering marvel because of its modularity: the side boosters were designed to be discarded once their fuel was spent, reducing weight. In Data Engineering, this is our <strong>Medallion Architecture.</strong></p><h4>Why Data Engineers Should Care: “<strong>Natural Deorbit” principle</strong></h4><p>Many of Vostok 1’s systems were backed up. For example, if the braking system had failed, the spacecraft would have deorbited naturally through atmospheric braking (it had provisions for 10 days). The idea that the physical environment (atmospheric drag) serves as a passive, “free” backup for an active system (the braking engine) could be represented in the <strong>decoupling of Storage and Compute</strong>. If your <strong>Spark</strong> cluster on EMR or Databricks spot instances terminates abruptly, your data “naturally deorbits” into <strong>S3 or GCS</strong>. Because the storage is persistent and independent, the “mission” (the data) isn’t lost; it just waits for a new compute “engine” to be “ignited” to resume processing.</p><p><strong>Applying the Vostok Principle to your Stack</strong></p><blockquote><strong>1. Stateless Compute &amp; Continuous Persistence</strong></blockquote><p><strong>The Logic: “Write-Ahead” Persistence</strong>. Make S3 the <strong>landing pad</strong> for every single stage. In the Vostok analogy: the “Atmosphere” (S3) is always there; the ship is always inside it.</p><ul><li><strong>The Rule:</strong> Your “Compute” (Spark/Flink) should be <strong>stateless</strong>.</li><li><strong>The Flow:</strong> Data is streamed directly into S3 in small “parts.” If the Spark job dies, the parts already written to S3 remain there. They don’t “disappear” with the RAM of the crashed cluster.</li></ul><pre># Spark Configuration for &quot;Natural Deorbit&quot; (Persistence)<br>from pyspark.sql import SparkSession<br><br>spark = SparkSession.builder \<br>    .config(&quot;spark.sql.catalog.glue_catalog&quot;, &quot;org.apache.iceberg.spark.SparkCatalog&quot;) \<br>    .config(&quot;spark.sql.catalog.glue_catalog.warehouse&quot;, &quot;s3://my-vostok-data-lake/gold/&quot;) \<br>    .get_builder()<br><br># Step 1: Read the &quot;Bronze&quot; (Raw) data<br># Step 2: Transform<br>transformed_df = df.filter(&quot;sensor_status = &#39;OK&#39;&quot;).withColumn(...)<br><br># Step 3: Atomic Write to &quot;Silver&quot;<br># If this fails mid-way, Iceberg ensures the &#39;Silver&#39; table <br># is NOT corrupted. The &#39;Sun&#39; (S3) keeps the data safe.<br>transformed_df.writeTo(&quot;glue_catalog.silver.telemetry_clean&quot;).append()</pre><blockquote><strong>2. HOW TO: The “Manifest” or “Metadata” Trigger</strong></blockquote><p>At petabyte scale, use <strong>Table Formats</strong> (like <strong>Apache Iceberg</strong>, <strong>Delta Lake</strong>, or <strong>Hudi</strong>) to manage this. The “Natural Deorbit” happens because of <strong>Atomic Commits</strong>:</p><ul><li>Spark writes 100GB of data to S3 (the “physical” files).</li><li><strong>Only after</strong> the write is successful, Spark sends a tiny 1KB signal to the <strong>Metadata Store</strong> (the “Command Bus”) saying: <em>“These files are now part of the table.”</em></li><li>If Spark crashes during the write, the files are in S3, but the Metadata Store never “sees” them. The system remains clean (no corruption).</li></ul><p>Airflow retry dag example:</p><pre>task_spark_transform = SparkSubmitOperator(<br>    task_id=&#39;transform_telemetry&#39;,<br>    application=&#39;s3://scripts/vostok_transform.py&#39;,<br>    retries=3,  # If it fails, try again<br>    retry_delay=timedelta(minutes=5),<br>    # The &#39;Natural Deorbit&#39; means we don&#39;t need to &#39;clean up&#39; <br>    # S3 manually; the next run will just overwrite or append correctly.<br>    dag=dag,<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfp0skrTXz4rXp2XSDgx2A.png" /><figcaption>“Natural Deorbit” principle in Data Engineering</figcaption></figure><h3>2: Spacecraft and Resilient Data Pipelines</h3><blockquote><em>Using Vostok with ‘diverse redundancy’ for data-backup</em></blockquote><p>When Soviet engineers designed the <em>Vostok,</em> they didn’t just build a backup system; they built a <strong><em>differently-principled</em></strong> one. The Vostok’s primary orientation system used <strong>Infrared sensors</strong> to track the Earth’s horizon. It was cutting-edge and precise. But space is unpredictable; what if a specific thermal anomaly blinded the IR sensors? Instead of just adding a second IR sensor, they installed a “Solar” backup. This secondary system used a completely different physical mechanism — the Sun — to orient the craft.</p><blockquote><em>In your stack, the ‘Infrared’ (Streaming) is your high-precision tool. But when it fails, you don’t need a second sensor; you need the ‘Sun’ (Batch) to find your location in the data swamp</em></blockquote><h4>Why Data Engineers Should Care</h4><p>Too often, we think of “High Availability” as simply running two instances of the same Airflow DAG or mirroring a Kafka cluster. But if your logic has a bug, both instances will fail. You haven’t built a backup; you’ve just doubled your surface area for the same error.</p><p><strong>Applying the Vostok Principle to your Stack</strong></p><ul><li><strong>Avoid “Mono-Logic”:</strong> If you have a mission-critical streaming pipeline (your “Infrared”), back it up with a simple, robust Batch process (your “Sun”).</li><li><strong>Diversify the Principle:</strong> If your primary pipeline is a complex Spark job, use a different tool — like dbt or even a different cloud provider — for your reconciliation checks.</li><li><strong>Resilience &gt; Redundancy:</strong> True resilience isn’t about having <em>two</em> of everything; it’s about having an alternative way to reach the same truth when your primary logic goes dark.</li></ul><h3>3: Data Telemetry: from Monolith to Orbit (Event-Driven)</h3><blockquote><em>To reach orbit, you need real-time telemetry (the ‘Tral’ system): jump from Batch to Event-Driven.</em></blockquote><p>Telemetry was a thread between space and earth, providing connection about the space shuttle + cosmonaut system conditions to the earth. Radiotelemetry consisted of a set of sensors recording parameters: pressure in the tanks, rocket skin temperature, engine vibrations, the cosmonaut’s pulse and pressure, readings from onboard systems, etc., converting it into electrical signals, which was followed by conversion into a radio signal and sent to a transmitter, which, in its turn, sent the signal, which antennas tried to locate. And it was done real-time! Without telemetry from a remote measurement system for flight parameters and the state of onboard systems, a spacecraft is an expensive toy: <em>if the Vostok-1 had only sent data back to Earth once a day (Batch), Gagarin would never have made it. They needed Real-Time Telemetry to adjust the flight in seconds. The Soviet ‘Tral’ system didn’t just store data; it broadcasted a </em><strong><em>continuous pulse of truth</em></strong><em>.</em></p><blockquote>The multichannel soviet ‘Tral’ telemetry system was <strong>Kafka</strong> of 1961.</blockquote><p>In the DE world, this reflects as a transition from <strong>“We’ll check the data tomorrow”</strong> (Batch) to <strong>“The data tells us what’s happening NOW”</strong> (Event-Driven). Every time a user clicks a button or a sale happens, an <strong>“Event”</strong> is emitted (via Kafka or AWS Kinesis):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TKAMD1EPW3lk9eCukSkK8A.png" /><figcaption>Soviet Telemetry principle in Data Engineering</figcaption></figure><blockquote><strong><em>These are some Tral-system — Data Engineering parallels and principles</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vuGjN5vtixfdrOiDijXgiw.png" /></figure><p>And some table of the soviet data telemetry principles and their DE analogy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cUeMbK6d9O4Q-PX86d2KTw.png" /><figcaption>soviet data telemetry principles and their DE analogies</figcaption></figure><h3>4: The Art of the “Deviation” (Optimization)</h3><blockquote><strong>Transmitting only changes in sensor data to save precious radio bandwidth.</strong></blockquote><p>However, In the “Tral” system, transmitting a constant “pressure is 760mmHg” every second was a waste of radio bandwidth. Instead, they only sent a signal if it changed to 761 or 759. In ClickHouse, this is implemented through <strong>Specialized Codecs</strong>. Instead of generic compression (like Zstd or LZ4), these codecs look at the <em>mathematical relationship</em> between consecutive data points.</p><p>The “Soviet Telemetry” Codecs in ClickHouse:</p><p><strong>1. Delta Codec (The “Deviation” Principle)</strong></p><p>Instead of storing the actual values, ClickHouse stores the <strong>difference</strong> between the current value and the previous one. If your data is a sequence of timestamps or slowly increasing counters (like a rocket’s altitude), the “deltas” are tiny numbers (mostly 1s or 0s), which compress into almost nothing.</p><pre>CREATE TABLE rocket_telemetry (<br>    timestamp DateTime64(3) CODEC(Delta, LZ4),<br>    altitude Float64 CODEC(Delta, LZ4)<br>) ENGINE = MergeTree()<br>ORDER BY timestamp;</pre><p><strong>2. DoubleDelta Codec (The “Trajectory” Principle)</strong></p><p>If the “Delta” itself is constant (e.g., a sensor reporting exactly every 100ms), the <em>Delta of the Delta</em> is zero. This is the ultimate optimization for time-series data.</p><pre>CREATE TABLE engine_sensors (<br>    event_time UInt64 CODEC(DoubleDelta, ZSTD),<br>    temperature Float32 CODEC(Gorilla, ZSTD)<br>) ENGINE = MergeTree()<br>ORDER BY event_time;</pre><p><strong>Note on Gorilla:</strong> This is another famous codec used in ClickHouse (originally from Facebook) designed specifically for floating-point numbers (like temperature or fuel levels) that don’t change much. It’s the digital version of a “smooth flight” sensor.</p><blockquote>Optimization isn’t about buying more “fuel” (Cloud Spend); it’s about reducing the “weight” of the data through mathematical precision.</blockquote><h3>5: The “Red Button” (Governance &amp; Quality)</h3><blockquote>Gagarin’s sealed envelope (Manual Override) and the “Military Acceptance” of every bolt.</blockquote><p>The process of creating an aircraft was massively complicated: more than 100 group and many side organisations were involved. That requires engineering and design thinking principles of edge effectiveness. The entire development process Korolev has developed into three parts: “design — manufacturing — debugging,” — <em>the latter being the most critical.</em></p><p>Thus, Korolev advocated the creation of a system that would help detect malfunctions early. To prevent individual errors from being overlooked, an organizational system must be created that eliminates these errors, a system that would allow for their prompt detection and correction. “And this system must be created by you, as testers, and it must guarantee us against errors.” Doesn’t it sound like a CI/CD chain? Moreover, Korolev implemented the strictest GOST standards and testing procedures before launch. Every component underwent “military acceptance.”</p><p><strong>Why Data Engineers Should Care</strong></p><p>These are Data Contracts or Data Quality Checks. You don’t accept raw data into the system until it’s validated according to the schema. This prevents a “garbage in, garbage out” situation.</p><blockquote><em>Military Acceptance is your </em><strong><em>Data Contract</em></strong><em>. If a bolt (a row of data) is shaky, the whole mission stays on the ground. You don’t ignite the engines with ‘garbage’ in the fuel tanks.</em></blockquote><h3>6: Conclusion: The Space Engineering in Data Engineering</h3><p>As you see, the higher the risks, the tighter the constraints, the closer to zero room for error, the more elaboration is required. If something seems redundant, higher chance it is. If one element of a system is a linchpin holding the massive system from breaking apart, think the architecture twice. We are all “Chief Designers” of our own digital space programs: let’s implement Korolev’s precision and scrupulousness to triple-check what the system is fed, before multiplied fault is backfired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*gaO-5LwGxr71QlNKfnsPkw.png" /></figure><blockquote>Simplicity is the ultimate sophistication.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1549445a054f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/poyekhali-what-1961-soviet-space-tech-teaches-us-about-modern-data-engineering-1549445a054f">🚀 “Poyekhali!”: What 1961 Soviet Space Tech Teaches Us About Modern Data Engineering</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulating the Database Engine in Your Head: The Reality of the SQL Engine]]></title>
            <link>https://medium.com/towards-data-engineering/simulating-the-database-engine-in-your-head-the-reality-of-the-sql-engine-c06e3c82c2b1?source=rss-1e137cf52e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c06e3c82c2b1</guid>
            <category><![CDATA[sqlerror]]></category>
            <category><![CDATA[sql-engine]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Alexandra Petra Berger]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 05:49:50 GMT</pubDate>
            <atom:updated>2026-02-19T05:49:50.269Z</atom:updated>
            <content:encoded><![CDATA[<h4>This is Part 2 of the Series “The Reality of the SQL Engine”. The first one is ready <a href="https://medium.com/p/7fc12ef7a2b5">here.</a> In this article we speak about SQL Engine execution steps — and your ability to anticipate them. Enjoy the read and the fast application.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNP5ArYxElv0CvF7ZF5-_w.png" /></figure><h3><strong>1. Core Idea:</strong></h3><blockquote>If you can’t simulate what the database engine does, you don’t actually understand your query.</blockquote><p>This part builds on Part 1 (“<a href="https://medium.com/p/7fc12ef7a2b5"><em>What you mean vs what SQL reads</em></a>”) and moves from <strong><em>syntax awareness</em></strong> to <strong><em>execution awareness</em>.</strong></p><h3>2. The execution order myth</h3><p>Most people learn SQL in this order:</p><pre>SELECT …<br>FROM …<br>WHERE …<br>GROUP BY …<br>HAVING …<br>ORDER BY …</pre><p>And then they assume the database executes it the same way. It doesn’t.</p><p>One note I just ought to add here about SQL being declarative language and about the difference of declarative vs imperative languages:</p><blockquote><strong>SQL, being a declarative language, is based on principle: “you are given a command, execute it using your tools, in the most efficient way. The way is up to you”, while imperative languages scan and execute code line by line AS IS, i.e as it is given.</strong></blockquote><p>Important note:</p><blockquote>SQL is <strong>declarative</strong> in syntax, <strong>procedural</strong> in effect.</blockquote><blockquote><strong>Even though you write SQL declaratively, the database must execute it procedurally — and you must mentally follow that procedure to understand the result.</strong></blockquote><p>This mismatch about the assumption of how SQL works vs how it actually proceeds scripts is the root cause of:</p><ul><li>“Why doesn’t this work?”</li><li>“Why does this return fewer rows?”</li><li>“Why is this query slow?”</li><li>“Why does adding one condition break everything?”</li></ul><p>The database engine does not care about how readable your query looks.<br>It cares about <strong>what transformations it must apply to rows, and in what order</strong>.</p><blockquote>If you don’t know that order, you are guessing.</blockquote><h3>3. The real execution order (simplified)</h3><p>A simplified (but mentally accurate) execution order looks like this:</p><pre>FROM - identify source relations<br>JOIN / ON - combine rows<br>WHERE - remove rows<br>GROUP BY - collapse rows into groups<br>SUM(), COUNT(), AVG(), MAX(), MIN() - compute values per group<br>HAVING - remove groups<br>SELECT - dislay columns / expressions aka show what has been processed<br>ORDER BY - sort final rows<br>LIMIT / OFFSET - trim result set</pre><p>Important:</p><blockquote>👉 <strong>At each step, something is destroyed.</strong></blockquote><p>Rows disappear. Granularity changes. Information is lost. Once lost, it <strong>cannot be recovered</strong> later.</p><h3>4. Step-by-step mental simulation</h3><p>To understand a query, you must be able to answer, at each step:</p><ul><li>What is a <em>row</em> right now?</li><li>How many rows exist at this stage?</li><li>What information is still available?</li><li>What information is already gone?</li></ul><p>If you can’t answer these questions without running the query — you don’t understand it yet. Let’s reproduce the steps SQL takes to pave its engine’s path in your head:<br><strong>Table used:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*vwSDgn2RtjXdWXmJBthl6w.png" /></figure><p>Example SQL-query we simulate in our head:</p><pre>SELECT user_id<br>FROM orders<br>GROUP BY user_id<br>HAVING COUNT(*) &gt; 1;</pre><p><strong>Step 1 — FROM</strong></p><p><strong>The question to ask:</strong> what does the row represent<em> now</em>? <br><strong>Answer:</strong> each row = one order</p><p><strong>Step 2 — GROUP BY user_id, aka ZOOMING OUT</strong></p><p><strong>Questions to ask 1:</strong> What do rows do at this stage?<br><strong>Answer:</strong> Rows collapse.<br><strong>Question 2:</strong> what does the row represent<em> now</em>? <br><strong>Answer:</strong> Now each row = <strong>one user_id group</strong>.</p><p>Resulting table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EHysgRcNYlSTnQfqDr8ykA.png" /></figure><p>As we answered above, rows collapse: here, <em>the original</em> rows are gone. In other words, the <strong>granularity level</strong> has changed. Now <strong>the grain</strong> got bigger, i.e. we zoomed out. And it’s <strong>irreversible</strong>.</p><p><strong>Step 3 — COUNT(*)</strong></p><p><strong>Questions to ask 1</strong>: What doesCOUNT(*)actually count here?<br><strong>Answer:</strong> COUNT(*)counts rows that survived into the group</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TuWGRIcg67C5xyQJB3j4Q.png" /></figure><p>In other words, COUNT(*)shows how many rows there are in each grain of user_id.</p><p><strong>Step 4 — HAVING COUNT(*) &gt; 1</strong></p><p><strong>The question to ask: </strong>what process do the groups undergo?<br><strong>Answer: </strong>Groups are filtered.<br><strong>Question 2</strong>: What survives after filtration?<br><strong>Answer:</strong> Only this survives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*My6gn9WhF9Ip3IaHEEB_cg.png" /></figure><p><strong>Step 5 — SELECT</strong></p><p>We project user_id.Final result:<br><strong>Users with more than one order.</strong></p><h3>4. <strong>Where bugs are born</strong></h3><p><strong>1) Changing COUNT() argument</strong></p><p>Now consider we want:</p><pre>SELECT user_id<br>FROM orders<br>GROUP BY user_id<br>HAVING COUNT(user_id) &gt; 1;</pre><p>Many would argue: “Isn’t this the same thing?”<br>Sometimes yes.<br>Sometimes catastrophically no.</p><p><strong>Why?</strong></p><ul><li>COUNT(*) → counts <strong>rows</strong></li><li>COUNT(column)→ counts <strong>non-NULL values</strong></li></ul><p>If user_idcan be NULL:</p><ul><li>the group still exists<br><strong>but</strong></li><li>rows withNULLare not counted</li></ul><p>So now the question 2 transforms to: “<strong><em>How many non-NULL user_id values survived grouping?</em></strong>”</p><blockquote>That is a <strong>different question</strong>.</blockquote><p>The bug is not in SQL.<br>The bug is in the mental model.</p><p><strong>2. Another trap: wrong question</strong></p><p>Consider the following SQL-query:</p><pre>SELECT user_id, COUNT(*)<br>FROM orders<br>WHERE created_at &gt;= &#39;2024-01-01&#39;<br>GROUP BY user_id;</pre><p><strong>Question: </strong>which <strong><em>question</em></strong> does the query answer?</p><p>❌ <strong>Wrong (but common) answer:</strong></p><p><em>“For each user, how many orders do they have? Include only users who have at least one order in 2024”</em></p><p>✅ <strong>Correct interpretation:</strong></p><p><em>“Among orders created in 2024, how many orders does each user have?”</em></p><blockquote>WHY:</blockquote><p>the trick lies in order of execution. The rows were removed before grouping, becauseWHEREhas a higher order priority than GROUP BY (see <strong>The real execution order </strong>part): users who placed orders before 2024 but none during 2024, will <strong>disappear</strong> entirely. Because you are not filtering users— you are filteringorders.</p><p>If the business question is:</p><blockquote>“For each user, count all their orders — but only include users who had at least one order in 2024”</blockquote><p>Then the query must preserve all orders orders, and filtergroups, notrows:</p><pre>SELECT user_id, COUNT(*)<br>FROM orders<br>GROUP BY user_id<br>HAVING COUNT(<br>  CASE <br>    WHEN created_at &gt;= &#39;2024-01-01&#39; THEN 1 <br>  END<br>) &gt; 0;</pre><p>Now the logic is different:</p><ul><li>All orders survive grouping</li><li>Users are filtered based on group-level conditions</li><li>Historical data is preserved</li></ul><p>Same tables. Same columns. Different execution reality.</p><h4><strong>One takeaway sentence from Where the bigs are born:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*LJNFFSvhZ50t2z9ZMTqTLg.png" /><figcaption>WHERE vs HAVING key difference</figcaption></figure><p>Confusing the two changes the population, not just the count.</p><h3>5. How to practice this skill</h3><p>When reading or writing a query:</p><ol><li>Pause after each clause</li><li>Say out loud:</li></ol><ul><li><strong><em>“What is a row now?”</em></strong></li><li><strong><em>“What is gone forever?”</em></strong></li></ul><p>3. Only then move to the next clause</p><p>At first, this feels slow. Then it becomes automatic.</p><h3>6. Closing</h3><p>SQL feels intuitive right up until it doesn’t. At that moment, syntax stops helping — and mental execution begins.</p><blockquote>You don’t need to memorize optimizer internals.<br>You don’t need to memorize execution plans.</blockquote><p>You need one skill:</p><blockquote><strong>The ability to simulate, step by step, what the database engine does to your data.</strong></blockquote><p>If you can’t simulate it, you’re guessing. And guessing is where bugs, performance issues, and silent logic errors are born.</p><p>SQL mastery is not about writing queries. It’s about understanding the <strong><em>transformations</em></strong> they cause.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c06e3c82c2b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/simulating-the-database-engine-in-your-head-the-reality-of-the-sql-engine-c06e3c82c2b1">Simulating the Database Engine in Your Head: The Reality of the SQL Engine</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Is Precise, Not Poetic: The Reality of the SQL Engine]]></title>
            <link>https://medium.com/towards-data-engineering/sql-is-precise-not-poetic-the-reality-of-the-sql-engine-7fc12ef7a2b5?source=rss-1e137cf52e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fc12ef7a2b5</guid>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[sql-mistake]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-hidden-rules]]></category>
            <dc:creator><![CDATA[Alexandra Petra Berger]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 05:02:20 GMT</pubDate>
            <atom:updated>2026-02-12T05:02:20.042Z</atom:updated>
            <content:encoded><![CDATA[<h3>This three-part series explains how SQL actually works — so you can stop debugging symptoms and start understanding the engine.<br> The first part explains how SQL does exactly what you ask — not what you mean.<br> The second shows how to simulate a database engine in your head.<br> The third explores the relational logic behind joins.<br> Enjoy the read — and the fast application.</h3><h3>PART 1 — SQL: The Big Misunderstanding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mxh2mFzNB2Vskx0fRR33SA.png" /></figure><h3>1. Core Idea</h3><blockquote>“Why did this query return so many — or so few — rows?”<br> This is a frustrating question that arises more often than even mid-level engineers like to admit.</blockquote><p>Which is especially frustrating when working with Big Data. The reason is SQL is not a reasoning partner. It does not infer intent, nor does it “understand” business questions. SQL executes <strong>instructions on rows.</strong><br>Let’s lay it out with an examples. Our base tabels are<br>usersand orders:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nOgx9IJVqJUzYaVSemiDkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IzPrHx_s0eowJNvIABgBRA.png" /></figure><p>📝 Note before diving deeper:</p><ul><li><strong>users.user_id is not unique</strong></li><li>Joining these tables can silently multiply rows</li><li>SQL will happily count them</li></ul><p>This is where most analytical bugs are born.</p><blockquote><strong>Most SQL bugs in production are not caused by complex logic — they’re caused by incorrect assumptions about grain.</strong></blockquote><h3>2. Where Users Get It Wrong</h3><h3><strong><em>Rows produced</em> vs <em>entities surviving</em></strong></h3><p><strong><em>— </em></strong>This is the distinction! This distinction is <strong>foundational.</strong> SQL never counts <strong><em>users</em></strong>. SQL counts <strong><em>rows</em></strong><em>.</em> You are the one assigning <strong><em>this meaning</em></strong> to the rows. If one user appears in 5 rows, SQL sees 5 things — not 1 user.</p><h3>Natural Language Trap</h3><h4><strong>Example 1</strong></h4><blockquote>“How many users made at least one order?”</blockquote><p>If row-thinking, or rushing to writing and executing without pausing and giving it a thought, we write something like:</p><pre>SELECT COUNT(*)<br>FROM users u<br>JOIN orders o<br>  ON u.order_id = o.order_id;</pre><p>And end up with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*sbY0wvPqV8Qlt1xHfu51Xw.png" /></figure><p>SQL answers: <em>“4 rows survived the join.” </em>But the spoken question was about <strong>users</strong> — not rows.</p><p><strong>Hidden assumptions:</strong></p><blockquote>What is a “user”?<br>What defines “made an order”?<br>One order or many?<br>Over what time window?</blockquote><p>SQL will not resolve this for you. The correct version will look like:</p><pre>SELECT COUNT(DISTINCT u.user_id)<br>FROM users u<br>JOIN orders o<br>  ON u.order_id = o.order_id;</pre><p>No magic here — but in more complex examples, it still boils down to these core ideas.</p><h4>Example 2</h4><blockquote>“How many orders did we have?”</blockquote><pre>SELECT COUNT(*)<br>FROM orders;</pre><p>Now it’s about orders. Here, a row represents an order. Why? Because the orders table’s grain — its most granular entity — is the order itself.</p><h4>Example 3</h4><blockquote>“How many users with more than one order?”</blockquote><p>The wrong instinct is to immediately filter out users with only one order. Here’s why it’s wrong: the table grain (entity) is not a user. To make it so we ought to aggregate rows per users. Once we fix the grouping step, we must decide what we are actually going to count. Is it</p><blockquote>“How many rows exist for this user_id?”</blockquote><p>or</p><blockquote>“how many <strong>rows survived</strong> into this group?”</blockquote><p>In other words, is this a row-survival question, or a value-existence question, and why? We want rows, even if a row has an empty or unknown value in orders.</p><p>This way, we are speaking of rows. We want to keep only users for whom <strong>more than one row</strong> exists in orders. So we group by user_id and apply a condition: the number of rows per user must be greater than 1:</p><pre>SELECT user_id<br>FROM orders<br>GROUP BY user_id<br>HAVING COUNT(*) &gt; 1;</pre><blockquote>When using <em>COUNT()</em>always ask yourself before running the engine what exactly do you expect to count: <strong>rows</strong> or <strong>values</strong>? <strong>Users</strong> who satisfy condition, or <strong>event</strong> (online shopping sessions)? COUNT()always answers the meta-question “<strong>how many rows survived this step?</strong>”</blockquote><p>When in doubt, keep this essential table with you:</p><ul><li>COUNT(*) → <strong>How many things happened? Counts rows</strong></li><li>COUNT(column) → <strong>How many times did this thing exist? Counts non-NULL values</strong></li><li>COUNT(DISTINCT(column)) → <strong>How many distinct values?</strong></li></ul><h3>3. A Mental Model That Prevents 80% Of SQL Bugs</h3><p>Before writing a query, force yourself to answer <strong>three questions</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Rpe13oNjAqbpNBQYke3Fw.png" /><figcaption>3 questions to ask self before writing SQL query</figcaption></figure><blockquote>If you cannot answer these <strong>in words</strong>, SQL will not save you.</blockquote><h3>One sentence to take away</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qanBAMD3XJm0-D8eF2wP9A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fc12ef7a2b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/sql-is-precise-not-poetic-the-reality-of-the-sql-engine-7fc12ef7a2b5">SQL Is Precise, Not Poetic: The Reality of the SQL Engine</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL interview question at T-Systems]]></title>
            <link>https://medium.com/@alexandra.petra.berger/sql-interview-question-at-t-systems-34479cb0e6bf?source=rss-1e137cf52e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/34479cb0e6bf</guid>
            <category><![CDATA[sqlinterviewtips]]></category>
            <category><![CDATA[telecom]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Alexandra Petra Berger]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 08:22:03 GMT</pubDate>
            <atom:updated>2025-01-10T08:22:03.478Z</atom:updated>
            <content:encoded><![CDATA[<h4>This one is a hard SQL question asked of a data analyst candidate at a huge telecom company.</h4><p><strong>Task</strong></p><p>Find the day with when the feature performed the best. Telecom company has introduced a new service, and wants to test its performance. The service displays something else instead of a calling number, so the called party decides whether to pick up the call or to ignore it. When the service was intact during the call, the feature_code is marked with ´LABELB´.</p><p>Write a query which calculates the the ratio of (in percent) answered calls to the total number of calls without the service and with it, as well as the ratio of the ignored calls to the total number of calls with the service and without it.</p><p>feature_code is responsible for “the service has been displayed”,<br>talk_duration = 0 signifies that the call was ignored.</p><p>Your output should include date, ratio of answered without the service (2 digits), ratio of answered when the service was intact (2 digits), ratio of ignored without the service (2 digits) and the ratio of ignored when the service was intact (2 digits).</p><p><strong>Data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*b_rCjf6EzRm7-kIa6NSv6Q.jpeg" /></figure><p><strong>Solution</strong></p><pre>SELECT <br>    date,<br>    ROUND(<br>        SUM(<br>            CASE <br>                WHEN (talk_duration &gt; 0 AND feature_code != &#39;LABELB&#39;) THEN 1 <br>                ELSE 0 <br>            END<br>        ) / SUM(<br>            CASE <br>                WHEN feature_code != &#39;LABELB&#39; THEN 1 <br>                ELSE 0 <br>            END<br>        ), 4<br>    ) * 100 AS ratio_answered_no_lbl,<br><br>    ROUND(<br>        SUM(<br>            CASE <br>                WHEN feature_code = &#39;LABELB&#39; AND talk_duration &gt; 0 THEN 1 <br>                ELSE 0 <br>            END<br>        ) / SUM(<br>            CASE <br>                WHEN feature_code = &#39;LABELB&#39; THEN 1 <br>                ELSE 0 <br>            END<br>        ), 4<br>    ) * 100 AS ratio_answered_lbl,<br><br>    ROUND(<br>        SUM(<br>            CASE <br>                WHEN (talk_duration = 0 AND feature_code != &#39;LABELB&#39;) THEN 1 <br>                ELSE 0 <br>            END<br>        ) / SUM(<br>            CASE <br>                WHEN feature_code != &#39;LABELB&#39; THEN 1 <br>                ELSE 0 <br>            END<br>        ), 4<br>    ) * 100 AS ratio_ignored_no_lbl,<br><br>    ROUND(<br>        SUM(<br>            CASE <br>                WHEN feature_code = &#39;LABELB&#39; AND talk_duration = 0 THEN 1 <br>                ELSE 0 <br>            END<br>        ) / SUM(<br>            CASE <br>                WHEN feature_code = &#39;LABELB&#39; THEN 1 <br>                ELSE 0 <br>            END<br>        ), 4<br>    ) * 100 AS ratio_ignored_lbl<br><br>FROM <br>    call_details</pre><p><strong>Answer</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*v8kT39LUIIWMDI_7qCnJJw.jpeg" /><figcaption>answered + ignored calls with no LABELB sum up to 100, as well as answered + ignored calls without LABELB</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34479cb0e6bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to understand SQL Union, Intersection, and Joins without Venn Diagrams]]></title>
            <link>https://medium.com/@alexandra.petra.berger/better-way-to-imagine-union-intersection-and-joins-than-venn-diagram-3cc547821ffb?source=rss-1e137cf52e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cc547821ffb</guid>
            <category><![CDATA[joins-diagram]]></category>
            <category><![CDATA[innerjoin-vs-intersection]]></category>
            <category><![CDATA[not-venn-diagram]]></category>
            <category><![CDATA[sql-joins]]></category>
            <category><![CDATA[math-notes]]></category>
            <dc:creator><![CDATA[Alexandra Petra Berger]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 15:33:58 GMT</pubDate>
            <atom:updated>2025-01-08T14:37:41.762Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Going through my old </strong><a href="http://www.staff.ttu.ee/~lembit.pallas/function.pdf"><strong>University lectures on Mathematical Analysis</strong></a><strong> I realised the first notes on function are the concepts being used in SQL, namely the union and the intersection. Why not matching the SQL concepts with mathematical notation, illustrating them with table values instead of Venn Diagram?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*2Oh_5ruMqU1ARLefk5Y6RA.jpeg" /><figcaption>The same concept as Venn Diagram</figcaption></figure><p><strong>Union</strong></p><p>The union of two given sets A and B is denoted A ∪ B and is defined as the set of elements that are the elements of A or the elements of B or elements of both sets A and B:</p><p><strong>A ∪ B = {x|x ∈ A or x ∈ B}</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AmedFWncJkRAk8QVEsJYAw.png" /><figcaption>Union: <strong>A ∪ B</strong></figcaption></figure><p><strong>Intersection</strong></p><p><strong>The intersection </strong>of two given sets A and B denoted A ∩ B and is defined as the set of elements that are the elements of A and the elements of B:</p><p><strong>A ∩ B = {x|x ∈ A and x ∈ B}</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GKbNDZ0U13GgFpMA_wEUA.png" /><figcaption>Intersection:<strong> A ∩ B</strong></figcaption></figure><p><strong>Inner Join</strong></p><p>The inner join is the intersection of the two sets AAA and BBB, filtered by a condition:</p><p><strong>A⋈B = {x ∪ y | x ∈ A, y ∈ B, cond(x, y)}</strong></p><p>Here:</p><ul><li><strong><em>x ∪ y</em></strong> represents the combination of rows <strong><em>x</em> </strong>(from A) and <strong><em>y</em></strong> (from B).</li><li>cond(<strong><em>x, y</em></strong>) ensures the rows satisfy the JOIN condition.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRcBPOy-xVnUgTVb3WxiGA.png" /></figure><blockquote>Mind the difference between Intersection and Inner Join: inner join namely <strong>joins</strong> the table based on condition, while intersection just finds the subsets which do belong to both set A and set B (aka table A and table B) simultaneously. More on Intersect vs Inner Join <a href="https://medium.com/p/39f5b58e4a37">is here</a>.</blockquote><p>This is the part I always was wrong with inner join, expecting it to behave like intersection.</p><p><strong>Left Join</strong></p><p>The best way to think of left join correctly is to break it down into two steps (actualy, as per an execution plan of left join executes the left join): 1) performing inner join, 2) Fill the rows from A that do not match, with NULLs for columns from B to perform the outer part of the left join.</p><p>A<strong>\leftouterjoin</strong> B = {x <strong>∪ </strong>y <strong>| </strong>x ∈ A, y ∈ B, cond(x,y)} ∪ {x <strong>∪ </strong>NULL <strong>| </strong>x ∈ A, ∄ y ∈ B: cond(x,y)}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cGR3IHpeyWuQEDYbXqpj0A.png" /><figcaption>Left Join</figcaption></figure><p><strong>Cross Join</strong></p><p>Cartesian Product as a product of combination every row from <strong>A</strong> with every row from <strong>B:</strong></p><p>A × B = {x <strong>∪</strong> y <strong>| </strong>x ∈ A, y ∈ B}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ljn69QuGmBMRP55UrnqIIA.png" /><figcaption>Cross Join <strong>A x B</strong></figcaption></figure><p><em>Did any of these basics gave you a new perspective to look at the joins, intersection or union from? Has it always been clear as day the difference between intersection and inner join? Let me hear!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cc547821ffb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[INNER JOIN vs INTERSECT key differences]]></title>
            <link>https://medium.com/@alexandra.petra.berger/inner-join-vs-intersect-key-differences-39f5b58e4a37?source=rss-1e137cf52e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/39f5b58e4a37</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[innerjoin]]></category>
            <category><![CDATA[intersect]]></category>
            <category><![CDATA[sql-functions]]></category>
            <dc:creator><![CDATA[Alexandra Petra Berger]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 08:06:38 GMT</pubDate>
            <atom:updated>2024-12-02T08:06:38.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiaZiL9OsOx9S4MwkbjkLQ.png" /></figure><h4>Imagine we got two tables with revenues and we want to find common values of rev_oats in both tables, revenue_2023and revenue_2024:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*mevGEEHoZ72uTIL741QWcg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*NSZsEMA8u7BVxOfNl2SSHQ.jpeg" /></figure><h4>And we would want to find values of column rev_oats which belong to both of the tables.</h4><p>My instant go-to always was INNER JOIN, until I learned about INTERSECT. Before, I would write something like this:</p><pre>SELECT r23.rev_oats<br>FROM revenue_2023 AS r23<br>INNER JOIN revenue_2024 AS r24<br>ON r23.inn_a = r24.inn_a;</pre><p>And would wonder, why the result is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*6aK_ZgXX-wjk3VL2xPFolw.jpeg" /></figure><p>Meanwhile, the result of</p><pre>SELECT rev_oats<br>FROM revenue_2023<br><br>INTERSECT <br><br>SELECT rev_oats <br>FROM revenue_2024</pre><p>Would return the desired output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*cFzy373m2jrTG5LGOURquA.jpeg" /></figure><p>To figue things out let’s firstly dive into how both INTERSECT and INNER JOIN work.</p><ul><li>INTERSECT compares only the values in the rev_oats column between the two tables.</li><li>It finds common values independent of other columns in the tables.</li><li>HereINTERSECTidentifies all rev_oats values that exist in both tables, ignoring rows where other columns like inn_a, rev_mk, or year don’t match.</li></ul><p><strong>As a result, </strong>we get the rev_oats values that exist in both tables, regardless of the rows or associated data. In the meantime, INNER JOIN does as follows:</p><ul><li>it matches rows between two tables based on the condition specified in the ON clause.</li><li>In this case, it compares the inn_a column in both tables. If a value of inn_a in revenue_2023 matches a value of inn_a in revenue_2024, those rows are joined.</li><li>Once a match is found, it selects rev_oats from revenue_2023.</li></ul><blockquote><strong><em>This way, the Key differences would be: INTERSECT takes only 1 column specified in SELECT (given the column title in both tables is the same), compares it between tables, looks for intersections, outputs the unique values in output. INNER JOIN firstly combines the tables based on the column specified in ON clause, and, if no intersection is found, it doesn’t combine the tables and doesn’t compare them. For correct comparison INNER JOIN column in ON clause and in SELECT should be the same.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLBNm4qpQJ_xeLKub0SuVw.png" /><figcaption>key differences betwen INTERSECT and INNER JOIN</figcaption></figure><p>So what we need to do is to fix the connecting columns provided in ON clause for INNER JOIN:</p><pre>SELECT r23.rev_oats<br>FROM revenue_2023 AS r23<br>INNER JOIN revenue_2024 AS r24<br>ON r23.rev_oats = r24.rev_oats </pre><p>Which would give</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*yzmsCoIbXGixhUkqVM2-fA.jpeg" /></figure><p>Which is one DISTINCT away from the desired output:</p><pre>SELECT DISTINCT r23.rev_oats<br>FROM revenue_2023 AS r23<br>INNER JOIN revenue_2024 AS r24<br>ON r23.rev_oats = r24.rev_oats  </pre><p>and the desired output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*cFzy373m2jrTG5LGOURquA.jpeg" /></figure><h3>Performance comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*6Ythl5iN1_xQR6agr2xoTA.jpeg" /></figure><p>It is always curious to compare the execution time for queries. Here, for one column compared query, the query with INNER JOIN has been executing for 81 sec, while the query with INTERSECT returned the result in 31 sec. Given that both tables are relatively small, this is almost a 50% win. Decide for yourself 😝✍️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39f5b58e4a37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling NULLs in SQL: ISNULL(), IFNULL(), COALESCE()]]></title>
            <link>https://medium.com/@alexandra.petra.berger/handling-nulls-in-sql-isnull-ifnull-coalesce-a480c3584c32?source=rss-1e137cf52e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a480c3584c32</guid>
            <category><![CDATA[isnull]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[handling-missing-values]]></category>
            <category><![CDATA[handling-zeros]]></category>
            <category><![CDATA[null-value]]></category>
            <dc:creator><![CDATA[Alexandra Petra Berger]]></dc:creator>
            <pubDate>Sat, 30 Nov 2024 13:21:25 GMT</pubDate>
            <atom:updated>2024-11-30T13:21:25.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kDz_uAZe_iwfpdhxer6AuQ.png" /><figcaption>typical functions for handling NULL values in different databases</figcaption></figure><h4>When you got reasonably big data it is quite common to have some values missing. To handle nulls or simply speaking, empty values, there are three main functions: ISNULL(), IFNULL() and COALESCE(). The key difference between first two in the nutshell:</h4><h3>Differences between ISNULL() and IFNULL()</h3><ol><li>ISNULL():</li></ol><ul><li><strong>Checks</strong> whether a value is NULL and returns TRUE or FALSE.</li><li>Commonly used in filtering conditions (WHERE, HAVING).</li><li>Applicable in SQL Server, MySQL, Hive.</li></ul><p>2. IFNULL():</p><ul><li><strong>Replaces </strong>a NULL value with a specified value and returns the substituted value.</li><li>Commonly used to handle NULL values in result sets.</li><li>Applicable in MySQL and Hive.</li></ul><h3>Usage Examples</h3><h4><strong>Hive / MySQL</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nE7hIKtD0uKAAShffrMjtw.png" /><figcaption>table we work with</figcaption></figure><p><strong>ISNULL() MySQL</strong></p><pre>SELECT * FROM employees <br>WHERE ISNULL(salary);</pre><p><em>Returns rows where salary is NULL:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r9d03v3sHxbrdysJJJ1VGg.png" /><figcaption>v</figcaption></figure><p><strong>IFNULL()</strong> <strong>in Hive / MySQL:</strong></p><p>If we want to return everything with NULL values, replacing NULL with 0, we go as:</p><pre>SELECT employee_name, IFNULL(salary, 0) AS salary<br>FROM employees<br>WHERE ISNULL(salary) </pre><p>which gives exactly this — the line with 0 value for salary, which used to be empty:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NM1WySUTEr59GZDwYFp8CA.png" /></figure><p><strong>COALESCE() in Hive:</strong></p><p>Hive uses the IF function to handle null values, but for comparison with Oracle, we’ll also use the IFNULL() equivalent, which is COALESCE():</p><pre>SELECT employee_name, COALESCE(salary, 0) AS salary<br>FROM employees<br>WHERE ISNULL(salary);</pre><p>Again, we received the line with 0 value for salary, which used to be empty:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NM1WySUTEr59GZDwYFp8CA.png" /></figure><h4><strong>Oracle</strong></h4><p>ISNULL() and IFNULL() functions are not available in Oracle. Instead, there is NVL() function to replace empty cells with 0. And you always can use IS NULL in WHERE clause.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftKd08R6L4vBg65aGL0osw.png" /><figcaption>table we work with</figcaption></figure><p><strong>NVL() in Oracle:</strong></p><pre><br>SELECT employee_name, NVL(salary, 0) AS salary<br>FROM employees<br>WHERE salary IS NULL;</pre><p>Returns the 1 liner with employee who’s salary used to be empty, and now replaced with 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NM1WySUTEr59GZDwYFp8CA.png" /></figure><p>I hope you learned from this short comparison article. Feel free to use this article as a cheatsheet to handle your empty values. Happy handling!</p><p><em>Resources used:</em> <a href="https://sqlfiddle.com/">https://sqlfiddle.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a480c3584c32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Analyst Job Interview question #1]]></title>
            <link>https://medium.com/@alexandra.petra.berger/data-analyst-job-interview-question-1-dc6f08335d96?source=rss-1e137cf52e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc6f08335d96</guid>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[job-interview-preparation]]></category>
            <category><![CDATA[job-interview-questions]]></category>
            <category><![CDATA[job-interview]]></category>
            <dc:creator><![CDATA[Alexandra Petra Berger]]></dc:creator>
            <pubDate>Wed, 06 Nov 2024 15:37:46 GMT</pubDate>
            <atom:updated>2024-11-06T15:37:46.633Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>When it comes to job interviews, where you have to live-code without compiler (sometimes a pen and a paper is all you’ve got), one gets righteously confused. Here I want to save some questions from job interviews, and the ways not only to answer them, but also to get to this answer, which is the most important part, to me. I never shine at live coding, but I work on my mistakes afterwards and learn from them.</strong></h4><p><em>The first question, considered in this article, is as follows: there is a list of numbers. Find the indexes of the two numbers, which sum up to a given number.</em></p><p>Example:</p><pre>nums = [2, 7, 11, 15]<br>target = 9<br>output = [0, 1]</pre><p>imagine, we want target number to be flexible, so as the list of numbers. Thus, we going to have nums and target as the arguments of our function.</p><h4><strong>Approach 1, the most straightforward</strong></h4><p>The first and the most straightforward take on the task would be to use nested loop: outer one for the first number, and inner loop for the second number, two of which give target in total. Let’s look closer the nested cycles.</p><p>When we go for</p><pre>for i in range(len(nums)):<br>    for j in range(len(nums))</pre><p>then we iterate through each of values in nums:<br> | A | B | C | D |<br>+––––––––––+<br> | A | B | C | D |</p><p>Meaning, we pair each value from the first row (aka the outer loop for i in range(len(nums))) with each value from the nested loop (aka the outer loop for j in range(len(nums))), and we get: AA, AB, AC, AD, then BA, BB, BC, BD, then CA, CB, CC, CD, and, finally, DA, DB, DC, DD:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*h9aq09Drcd1p5Z3DzAmExw.png" /><figcaption>iteration through A and B in the outer cycle as an example</figcaption></figure><p>In the context of our task AB and BA are the same thing, so let us try accomplish combinations like AB, AC, AD, BC, BD, CD, in other words, unique combinations. This could be achieved, if the range of values the nested loop iterates through is not the same is in the range of the outer loop, but smaller. How exactly smaller? What we need to achieve here is A) exclude combining A with A, B with B etc. B) B from the outer loop should not be combined with A from the inner loop, which is “behind” B. This way, the start of the inner loop should be shifted. Looking at the pattern I draw below we can notice that the start of the inner loop is always 1 step shifted from the outer loop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*IkhVHZliBZf0DbWCLijQmw.png" /></figure><p>This way, we come to:</p><pre>for i in range(len(nums)):<br>    for j in range(i+1, len(nums))</pre><p>Second thing to take care of is to sum up the elements and return their indexes. It’s quite easy: parameter i or whatever notation you use is responsible for index, starting from 0, if not noted otherwise, and nums[i] is responsible for the element, corresponding to the index of i. This way, to “summa” (total) goes the summation of the elements, corresponding to i and j:</p><pre>for i in range(len(nums)):<br>        for j in range(i + 1, len(nums)):  <br>            summa = nums[i] + nums[j]</pre><p>The last thing to take care of is to think of what to return, if we do not find a match by checking the total of all the elements. This is how it’s done:</p><pre>def function(params):<br>  if condition is met:<br>    return  one thing<br>  return another thing</pre><p>So, we are going to return the indices as soon as a match is found, and return None if nothing is found.</p><p>▎<strong>Let’s combine all we’ve discussed together:</strong></p><p>1) Starting the inner loop with a shift of 1 element<br>2) summing up the elements<br>3) returning the indexes of the elements once the sum is equal to target:</p><pre><br>def two_sum(nums, target):<br>    for i in range(len(nums)):<br>        for j in range(i + 1, len(nums)):  <br>            summa = nums[i] + nums[j] <br>            if summa == target:  <br>                return i, j <br><br>    return None  <br><br>#nums = [2, 7, 11, 15]<br>#target = 9</pre><h4>Approach 2, thinking from backwards</h4><p>Is there a way to avoid nested cycles and iterate only inside one loop? We iterated over two loops to find first and second element. Is there a way to find second element once we found the first one? What if to think of the second element as of a difference between target and the first element?</p><pre>for i in range(len(nums)):<br>    complement = target - nums[i]</pre><p>Is there a function, which would give us both element and its corresponding index? There is! enumerate() does exactly this:</p><pre>for i, v in enumerate([&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]):<br>    print(i, v)<br><br># output:<br><br># 0 a<br># 1 b<br># 2 c</pre><p>In our case it will be:</p><pre>for i, num in enumerate(nums):<br>        complement = target - num</pre><p>So far we get to use both index and number, and we arrived at a point where we need to store both. What’s the structure which stores both index and a value? It seems everything is hinting on a <em>dictionary.</em></p><p>Let’s recall how do we iterate over a dictionary to get both key and a value.</p><pre>num_dict = {11: 0, 15: 1, 2: 2, 7: 3}<br><br>for i in num_dict:<br>    print(&quot;key: &quot;, i)<br>    print(&quot;value: &quot;, num_dict[i])</pre><p>following this logic, we can store numbers and their indexes, iterating over a list of numbers:</p><pre>for i, num in enumerate(nums):<br>        num_dict[num] = i</pre><p>The rest is a matter of technique: we loop over a list, retrieving both an element and its corresponding index, and populating a dictionary with them.</p><p>▎This way, we got at here:</p><p>— created an empty dictionary<br> — iterated over the list of numbers, retrieving both their value and index<br> — calculated the delta between the given number and target value, storing it in complement value.</p><pre>num_dict = {}<br>        <br>nums = [2, 7, 11, 15]<br>target = 9    <br>    <br>for i, num in enumerate(nums):<br>    complement = target - num<br>    num_dict[num] = i<br>    print(&quot;num_dict&quot;, i)<br>    print(&quot;complement&quot;, complement)</pre><p>While we’re iterating through the list, it comes in handy to check, whether the complementing value is in the dictionary already. The cycle doesn’t need to be finished before we check that. It could be done on the go!</p><pre>if complement in num_dict:<br>    result = [num_dict[complement], i]<br>    break</pre><p>If the number is found, we do not need to keep iterating, if it is known in advance that there’s only one pair. This way we avoid nested loops and use resources more efficiently.</p><p>The final function looks as follows:</p><pre>num_dict = {}<br><br>def two_sum():<br>    for i, num in enumerate(nums):<br>        complement = target - num<br>        num_dict[num] = i<br>        <br>        if complement in num_dict:<br>            result = [num_dict[complement], i]<br>            break<br><br>    return result<br><br>nums = [2, 7, 11, 15]<br>target = 9</pre><p><em>Thanks for giving it a read !</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc6f08335d96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mini plots (aka sparklines) using Seaborn and Pandas]]></title>
            <link>https://medium.com/@alexandra.petra.berger/mini-plots-aka-sparklines-using-seaborn-and-pandas-6141765d49f1?source=rss-1e137cf52e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6141765d49f1</guid>
            <category><![CDATA[seaborn]]></category>
            <category><![CDATA[pandas-spark-lines]]></category>
            <category><![CDATA[excel-sparkline-charts]]></category>
            <category><![CDATA[seaborn-spark-lines]]></category>
            <category><![CDATA[sparklines]]></category>
            <dc:creator><![CDATA[Alexandra Petra Berger]]></dc:creator>
            <pubDate>Wed, 14 Aug 2024 11:17:18 GMT</pubDate>
            <atom:updated>2024-08-14T11:22:46.551Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*DWkBAevOiRs5nO_2Scof8A.png" /><figcaption>picture from <a href="https://datavizproject.com/data-type/sparkline/">https://datavizproject.com/data-type/sparkline/</a></figcaption></figure><h4>Have you ever used sparklines, the powerful tool to show data trend, in Excel? If not, you are missing out and you should! However, it has crossed my mind, whether it is possible to use the same sparklines in python? There ought to be a way, oughtn’t it? When a colleague of mine had pandas spark lines in her presentation on ML model, I had to dive in and figure everything out. So I did so you don’t have to.</h4><h3><strong>Preparing dataset</strong></h3><p><strong>1.</strong> <strong>importing necessary modules and libs</strong></p><pre>import numpy as np<br>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>from io import BytesIO<br>import base64<br>from IPython.core.display import HTML</pre><p><strong>2.</strong> <strong>Generating a dataframe</strong></p><p>Lets generate a dataframe to work with, with a random state = 4 using<br>np.repeat— numpy.<strong>repeat</strong>(<em>a</em>, <em>repeats</em>, <em>axis=None</em>)<br>basically, multiplies needed part along the same axes given amount of times. More examples <a href="https://www.geeksforgeeks.org/numpy-repeat-python/">here</a>.</p><p>np.c_ concatenates along the <strong><em>Second </em></strong>axis i.e. concatenation id taking place along columns (see example <a href="https://brijesh0808.medium.com/what-is-np-c-and-np-r-in-numpy-5c69b01927df">here</a>).</p><pre>rs = np.random.RandomState(4)<br>pos = rs.randint(-1, 2, (20, 5)).cumsum(axis=1)<br>pos -= pos[:, 0, np.newaxis]<br>step = np.tile(range(5), 20)<br>walk = np.repeat(range(20), 5)<br>df = pd.DataFrame(np.c_[walk,<br>                        pos.flat, <br>                        step <br>                        ],<br>                  columns=[&quot;walk&quot;, &quot;position&quot;, &quot;step&quot;])</pre><p>This way we achieve a dataframe consisting of 100 rows and 3 columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*IAfWiiIOxfuZVdvLNKvRgw.png" /></figure><h3>Sparklines in Excel</h3><p>to give an idea what sparklines are, and how do they look, let’s take the recently generated dataset and visualize position depending on the walk number, then go Insert — Sparklines — Line, you’ll get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*HXIX8mUwMmX46--2cCI86w.png" /><figcaption>sparklines</figcaption></figure><p>where in E there are positions B visualized depending on walk A: highlighed sparkline is a small representation of walk 0, the next sparkline below highlighted is a viz rep for walk 1, and so on up till walk 5. I used them in an Excel dashboard <a href="https://medium.com/@alexandra.petra.berger/pulkovo-led-airport-passenger-traffic-viz-7c67ecea358">here</a>, just in case :D Now let’s see how would it translate into using seaborn:</p><h3>Sparklines using SEABORN</h3><ol><li><strong>sns.FacetGrid()</strong> — initializing a a grid of plots with an axes for each walk. When assigning column and/or row variables, more more subplots are added to the figure: grid = sns.FacedGrid(df, color = &#39;color&#39;, palette=&#39;palette_name&#39;, height=&#39;height&#39;)<br>Later, we add modules to the object:</li><li><strong>refline </strong>— allows to add a baseline, vertical lines, color, line styling. We draw a horizontal line to show the starting point:<br>grid.refline(y=&#39;value_for_y&#39;, x=&#39;value_for_x&#39;, linestyle=&#39;style&#39;)</li><li><strong>.map</strong> — allows to assign a plotting function to each facet’s subset of the data. We will draw a line plot to show the trajectory of each random walk, hence plt.plot is the first param:<br>grid.map(plt.plot, column_1, column_2, marker=&#39;marker&#39;)</li><li>Ticks positions for x and y axis, labels and the limits of the subplots’ axes are tweaked by using <strong>.set:<br></strong>grid.set(xticks = np.arrange(how_many), yticks=[from, to], xlim(from, to, step)</li></ol><pre>sns.set_theme(style=&quot;ticks&quot;)<br><br>grid = sns.FacetGrid(df, <br>                     col=&quot;walk&quot;, <br>                     hue=&quot;walk&quot;, <br>                     palette=&quot;tab20c&quot;,<br>                     col_wrap=4, <br>                     height=1.5)<br><br>grid.refline(y=0, linestyle=&quot;:&quot;)<br><br>grid.map(plt.plot, <br>         &quot;step&quot;, <br>         &quot;position&quot;, <br>         marker=&quot;o&quot;)<br><br>grid.set(xticks=np.arange(5), <br>         yticks=[-3, 3],<br>         xlim=(-.5, 4.5), <br>         ylim=(-3.5, 3.5)<br>        )<br><br>grid.fig.tight_layout(w_pad=1)</pre><p>which outputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ZuwvYl_BaMD-bdUrLc9RNQ.png" /><figcaption>mini-plots (sparklines) in Seaborn</figcaption></figure><p>if you look at the first row of the subplots, and compare it with Excel sparklines, you’ll spot the same trend:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*QFcWq_wm6HQqBfrX0QaKFw.png" /><figcaption>sparklines in Excel vs. sparklines in Seaborn</figcaption></figure><h3>Sparklines using PANDAS</h3><ol><li>First off, initialization of subplots is needed: <strong>plt.subplots()</strong>, iside the params for size could be set.</li><li><strong>.set_axis_off</strong>is quite self-explaining: turns off the axis to save the space.</li><li><strong>.plot(np.argmax(data))</strong>plots the min/max points by accessing their indexes: the argmax() function returns the indices of the maximum values along a specified axis, while the max() function returns the maximum values. More on the difference between numpy.max vs numpy.argmax you can read <a href="https://www.sharpsightlabs.com/blog/numpy-argmax/">here</a>.</li><li><strong>df.groupby(&#39;walk&#39;)</strong>does the same as it did in excel: preparing data for the sparkline to be created depending on a walk number.</li><li><strong>.map</strong> does the same as it did in Seaborn: extrapolates plots for all the walks.</li></ol><pre>def sparkline(data):<br>    fig, ax = plt.subplots(1, 1, figsize=(4, 0.25))<br>    ax.plot(data)<br>    <br>    ax.set_axis_off()<br>    ax.plot(np.argmax(data), data[np.argmax(data)], &#39;r.&#39;)<br>    ax.plot(np.argmin(data), data[np.argmin(data)], &#39;m.&#39;)<br><br>    img = BytesIO()<br>    plt.savefig(img)<br>    img.seek(0)<br>    plt.close()<br>    <br>    return &#39;&lt;img src=&quot;data:image/png;base64,{}&quot;/&gt;&#39;.format(base64.b64encode(img.read()).decode())<br><br># Group by &#39;walk&#39; and aggregate &#39;position&#39; into lists for sparklines<br>agg_df = df.groupby(&#39;walk&#39;, as_index=False)[&#39;position&#39;].agg(list)<br>agg_df[&#39;sparkline&#39;] = agg_df[&#39;position&#39;].map(sparkline)</pre><p>To display all the sparklines I used the cycle to avoid the restrictions of Jupyter notebook:</p><pre>for i in range(0, len(agg_df), 5):  # Adjust the batch size as needed<br>    display(HTML(agg_df[[&#39;walk&#39;, &#39;sparkline&#39;]].iloc[i:i+5].to_html(escape=False)))</pre><p>You are free to use</p><pre>HTML(agg_df[[&#39;walk&#39;, &#39;sparkline&#39;]][-10:].to_html(escape=False))</pre><p>to display all the sparklines at once when working on VS Code or other IDE.</p><p>Anyways, the output should be something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*6dxk0OOb26-Ja3kPTWQwEw.png" /><figcaption>sparklines in Pandas</figcaption></figure><p>Again, when comparing with the initial sparkline in Excel, one should spot similarities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*I0n6AAtH4zpsNO1enUfqjw.png" /><figcaption>sparklines in Excel vs. sparklines in Pandas</figcaption></figure><p>Feel free to incorporate this into your work!</p><p><strong><em>Links used:</em></strong></p><ul><li><a href="https://www.geeksforgeeks.org/numpy-repeat-python/"><em>https://www.geeksforgeeks.org/numpy-repeat-python/</em></a></li><li><a href="https://medium.com/r?url=https%3A%2F%2Fbrijesh0808.medium.com%2Fwhat-is-np-c-and-np-r-in-numpy-5c69b01927df"><em>https://medium.com/r?url=https%3A%2F%2Fbrijesh0808.medium.com%2Fwhat-is-np-c-and-np-r-in-numpy-5c69b01927df</em></a></li><li><a href="https://medium.com/@alexandra.petra.berger/pulkovo-led-airport-passenger-traffic-viz-7c67ecea358"><em>https://medium.com/@alexandra.petra.berger/pulkovo-led-airport-passenger-traffic-viz-7c67ecea358</em></a></li><li><a href="https://www.analyticsvidhya.com/blog/2023/12/all-you-need-to-know-about-numpys-argmax-function/"><em>https://www.analyticsvidhya.com/blog/2023/12/all-you-need-to-know-about-numpys-argmax-function/</em></a></li><li><a href="https://www.sharpsightlabs.com/blog/numpy-argmax/"><em>https://www.sharpsightlabs.com/blog/numpy-argmax/</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6141765d49f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Interview Questions]]></title>
            <link>https://medium.com/@alexandra.petra.berger/trivial-but-tricky-sql-tasks-d1463592625f?source=rss-1e137cf52e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1463592625f</guid>
            <category><![CDATA[test-task]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[job-interview-questions]]></category>
            <category><![CDATA[sql-interview-questions]]></category>
            <dc:creator><![CDATA[Alexandra Petra Berger]]></dc:creator>
            <pubDate>Wed, 07 Aug 2024 20:22:55 GMT</pubDate>
            <atom:updated>2024-12-02T07:56:14.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRga1-lSIJhUWjIU9SdeFg.png" /></figure><h3>Here are samples of 2 test tasks I was asked on a tech interview. Even though there must be tons of similar posts on the similar topic aka “How to crack Leetcode tasks”, let me add my 5 pennies, believing the more examples the better.</h3><p>Tricky part was I had to solve it without compiler, so I had to imagine the outcomes of the compilation in my head. Which I don’t shine at :D There are the tasks:</p><ol><li><strong>Given two column table with Id and email addresses, show emails, which have duplicates:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*COGRcCzhcPcvbIB_iv3icA.png" /><figcaption>id + emails table</figcaption></figure><p>Have dupes! Not unique, but <em>with dupes! <br></em>Instinctively I tried:</p><pre>SELECT NOT DISTINCT (id)<br>FROM clients</pre><p>Of course, that doesn’t work since there’s no such function as NOT DISTINCT(), and we technically cannot negate a function :)</p><p>Then I tried:</p><pre>SELECT email<br>FROM clients<br>WHERE COUNT(id) != 1<br>GROUP BY email</pre><p>Warmer, but not exactly it! Firstly I even suspected cunstruction COUNT(id) != 1 as one to blame for issues, but that’s not it. Here the thing lies in that aggregate functions are not allowed in WHERE, so it’s a hint we need HAVING() instead (not forget about order of the commands! HAVING always follows GROUP BY, while WHERE preceds):</p><pre>SELECT email <br>FROM clients<br>GROUP BY email<br>HAVING COUNT(id) != 1</pre><p>Thinking of task later, I came up with more quirky solution. We need to work with duplicates, right? What if we multiply the table to be able to join it on itself by id?</p><p>If we run</p><pre>SELECT a.id, a.email<br>FROM clients a<br>JOIN clients b ON a.email = b.email</pre><p>We are left with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*GyWU55a1YFx2IxM-FQselw.png" /></figure><p>In other words, only an email, which is unique in the table, row 5, has not joined with anything. Counterfactually, we need to filter this unique email out by finding same emails, but with different id-s. For instance, row 1 and row 6. Hence we need to add a condition that id in first table not paired with the second table:</p><pre>----<br>JOIN clients b ON a.email = b.email<br>WHERE a.id &lt;&gt; b.id;</pre><p>We just have to keep in mind that we need only emails column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*wJGfxX7qo0kSgsFpLkN1SQ.png" /></figure><p>And not to forget to use DISTINCT, of course:</p><pre>SELECT a.email<br>FROM clients a<br>JOIN clients b ON a.email = b.email<br>WHERE a.id &lt;&gt; b.id;</pre><p>Try yourself and see if it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*-lxJdhxBr8SYQIYYb--aRw.png" /><figcaption>the result of emails which have duplicates</figcaption></figure><p><strong>2. Given a table with the following structure: id | name | salary, you need to find id of an employee, which has the salary second from maximal one.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*iY2ZVis47IYn5LiKWKjpRg.png" /><figcaption>table with employee id and salary</figcaption></figure><p>So, we need our script to return Ada’s id, which is 5 or Elajah id, which is 3. By the way, in the task it is not said what do we do in such case, so we leave it for us to decide.</p><p>Initially I was thinking of something like ordering employees by</p><pre>SELECT id, name, MAX(salary)<br>FROM employees<br>GROUP BY id, name<br>ORDER BY MAX(salary) DESC</pre><p>which would leave me with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*KMMTAXdqj0Zgu3M7-Xh1uw.png" /></figure><p>and then extracting a second row… Which I consider of doing either by assigning an ordinal number, which corresponds to the maximum salary, and then subtracting 1 from the that ordinal number, and getting the corresponding id for the resulting ordinal number. Which is a way to use window functions (where I do not shine, again 😀)</p><p>… or OFFSETS! The following script would do exactly this: create an offset of 1 row:</p><pre>SELECT id, name, MAX(salary)<br>FROM employees<br>GROUP BY id, name<br>ORDER BY MAX(salary) DESC<br>OFFSET 1 ROWS</pre><p>— this would retrieve the data starting from the next after first row:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*HWNck5PEWDp-XJtuxgFrgg.png" /></figure><p>So to cut the sample off at the second row we need to fetch 1 row only, literally:</p><pre>SELECT id, name, MAX(salary)<br>FROM employees<br>GROUP BY id, name<br>ORDER BY MAX(salary) DESC<br>OFFSET 1 ROWS   <br>FETCH NEXT 1 ROWS ONLY</pre><p>Which would return 1 row only:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*nobCWqhrP55ibw_UKgyHfg.png" /></figure><p>However, how does it decide, whether it should be Elajah or Ada? :D</p><p><strong>Second way </strong>to tackle this would be to think of similar concept: LIMIT. If we LIMIT simple sorted sample by 1, we are left with the MAX salary. In the meantime, we need second TOP salary, which implies LIMIT 2:</p><pre>SELECT DISTINCT salary<br>FROM employees<br>ORDER BY salary DESC<br>LIMIT 2</pre><p>Which yields:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*D03gu3vxh2blCRnjnp2-XQ.png" /></figure><p>Why not looking into direction of MIN this time? MIN of the set of 2, hm?</p><pre>SELECT MIN(salary) AS second_max_salary<br>FROM (<br>    SELECT DISTINCT salary<br>    FROM employees<br>    ORDER BY salary DESC<br>    LIMIT 2<br>) AS top_salaries;</pre><p><strong>A third way,</strong> employing both LIMIT and OFFSET, could be:</p><pre>SELECT salary<br>FROM employees<br>LIMIT 1<br>OFFSET 2</pre><p>As easy as that!</p><p>And<strong> the fourth</strong>, and the last one, is based on two sets, like sets in maths. Let’s think of MAX(salary) is a set of 1 salary, and this set is a subset of … what set? Of all salaries. What else does comprise this set? Other salaries! Hard to imagine? Check this out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*emL0LjWIl3_rRn1dNYOdeA.png" /><figcaption>all salaries “sets”</figcaption></figure><p>Translating this diagram into SQL will give us:</p><pre>SELECT MAX(salary)<br>FROM employees<br>WHERE salary NOT IN (SELECT MAX(salary) <br>                  FROM employees) </pre><p><em>Which task and which logic did you enjoy the best?</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1463592625f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>