<?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 Alisa Aylward on Medium]]></title>
        <description><![CDATA[Stories by Alisa Aylward on Medium]]></description>
        <link>https://medium.com/@alisa.aylward?source=rss-d62574a9c178------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JjEkxIINBsJOXe1KkGaOCg.png</url>
            <title>Stories by Alisa Aylward on Medium</title>
            <link>https://medium.com/@alisa.aylward?source=rss-d62574a9c178------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:04:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alisa.aylward/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[Things I Sometimes Do in Snowflake/SQL That You Should Not Do]]></title>
            <link>https://medium.com/@alisa.aylward/things-i-sometimes-do-in-snowflake-sql-that-you-should-not-do-50319fdc37d6?source=rss-d62574a9c178------2</link>
            <guid isPermaLink="false">https://medium.com/p/50319fdc37d6</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[snowflake-computing]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <dc:creator><![CDATA[Alisa Aylward]]></dc:creator>
            <pubDate>Sat, 14 Nov 2020 04:12:11 GMT</pubDate>
            <atom:updated>2020-11-15T02:56:20.094Z</atom:updated>
            <content:encoded><![CDATA[<p>I have turned into a typical old school parent in that I find myself saying “Do what I say, not what I do.” This is usually when I’m sharing my screen, and under the perceived time pressure and awkwardness that comes from people watching you work, I take some SQL shortcuts. These shortcuts help me produce a result quickly, but aren’t scalable, flexible, or readable enough for production. In this post, I’ll explain what the shortcuts are, why they can be dangerous, and how they can be replaced for production ready code.</p><h3>$1</h3><p>In Snowflake, you can refer to columns in a WHERE clause with a reference to their ordinal position. For example:</p><pre>SELECT * FROM cat_table WHERE $1 = &#39;Mac&#39;</pre><p>In this case, if I know that the first column in ordinal position is cat_name, then this will give me info about Mac. This seems great, until it doesn’t.</p><p>What would happen if you added this to your ETL or analytical scripts and someone added a cat_id in the first ordinal to cat_table? Nothing. Nothing would break. Nothing would be returned. The query would just simply give no results since there is no cat_id = ‘Mac’.</p><p>And that is scary.</p><p>The other scary thing about $1 is that it always refers to the underlying table, not the fields listed in your SELECT statement (as opposed to GROUP BY 1). For example:</p><pre>SELECT cat_name, cat_id FROM cat_table WHERE $1 = &#39;Mac&#39;</pre><p>In this case, if cat_id is the first field in cat_table than this will translate to:</p><pre>SELECT cat_name, cat_id FROM cat_table WHERE cat_id = &#39;Mac&#39;</pre><p>which will give no results.</p><p>So not only is the code not scalable in the case of a DDL update, you are also forcing the reader to know that your WHERE clause refers to the underlying table, and not the columns you’ve listed. It’s unclear and dangerous and Mac does not like it. What more convincing do you need?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wB2hjQYCaJbpuGg9.png" /></figure><h3>Division with /</h3><p>This is a simple one: division can be scary. If you are adding a field that is a division of two or more fields, consider if the denominator can ever be zero and if so, how do you want your field to react. When writing the query to do some scratch work, we may write:</p><pre>SELECT color, SUM(cat_cuteness) / SUM(cat_count) AS avg_cuteness FROM cat_table GROUP BY color;</pre><p>That is okay for now, but what happens once you check in this code, go about your life, and someone upstream enters a record like this:</p><p>Why would someone add this record? Not sure, but it will happen, trust me. As soon as it does, you will get an error to the effect of:</p><p>DIVISION BY 0 NOT POSSIBLE, STOP IT. YOU WILL RIP A HOLE IN THE SPACE TIME CONTINUUM.</p><p>Not sure if that’s the exact error, but you get the point. So what’s the workaround? <strong>Always use </strong><a href="https://docs.snowflake.com/en/sql-reference/functions/div0.html"><strong>DIV0</strong></a><strong> when you want to do division that gives 0 in case of a 0 denominator, otherwise use a specific </strong><strong>CASE WHEN</strong> For instance, if I wanted avg_cuteness to zero out if there are no cats:</p><pre>SELECT color, DIV0(SUM(cat_cuteness), SUM(cat_count)) AS avg_cuteness FROM cat_table GROUP BY color;</pre><p>Otherwise, if I want a specific result in case of zero, I may do:</p><pre>SELECT color, CASE WHEN cat_count = 0 THEN NULL ELSE DIV0(SUM(cat_cuteness), SUM(cat_count)) END AS avg_cuteness FROM cat_table GROUP BY color;</pre><p>In either case, your code is more robust. Over time, this will decrease the number of errors you wake up to in the morning, and Itzy appreciates that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M3E8ZGwwp-04wOJ1.png" /></figure><h3>Group by 1,2,4</h3><p>If I’m rapidly adding to a query and trying to get a result I may end up with aggregate fields and non-aggregate fields living amongst each other, for example:</p><pre>SELECT cat_id, cat_name, avg(cat_cuteness), cat_color <br>FROM cat_info<br>GROUP BY 1,2,4;</pre><p>Hypothetically, I could have written this after being asked for average cuteness by cat, and, at the last minute, someone on the Zoom said “oh we also need to see it by color.” To get results quickly, I would have added cat_color last in the query and added a 4 to the group by, but this is not best practice.</p><p>A lot of people ask why they have to explicitly group by all non-aggregate fields when there is no option (in Snowflake) to *not* group by them. I think it’s just convention to ensure the aggregation is intentional; in MySQL, you do not have to do group by all non-aggregated fields, so there is a precedent for more flexibility in aggregation that one day Snowflake may offer. In the interim, you just have to be explicit about your grouping.</p><p>But do it in order and with the names of columns, because this improves readability of the code:</p><pre>SELECT cat_id, cat_name, cat_color, AVG(cat_cuteness) <br>FROM cat_info <br>GROUP BY cat_id, cat_name, cat_color</pre><p>Notice that all non-aggregate fields appear before the aggregate field and that the group by explicitly names the non-aggregate fields. There is no improvement here in performance or error prevention; this is merely a matter of readability. In the future, people will read your code and if the group by uses column names, they can determine the grain of your query at a glance. Additionally, they can easily deduce the aggregate fields if they are all together at the end of the query.</p><p>And this is less scary to Cheesie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*ZAYCNADuui0yFv2Y.png" /></figure><p><em>Originally published at </em><a href="https://www.alisa-in.tech/post/2020-11-14-things-i-do-not-to-do/"><em>https://www.alisa-in.tech</em></a><em> on November 14, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50319fdc37d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common Excel Functions in SQL]]></title>
            <link>https://medium.com/@alisa.aylward/common-excel-functions-in-sql-bde6541aa1ba?source=rss-d62574a9c178------2</link>
            <guid isPermaLink="false">https://medium.com/p/bde6541aa1ba</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Alisa Aylward]]></dc:creator>
            <pubDate>Sun, 01 Nov 2020 04:12:11 GMT</pubDate>
            <atom:updated>2020-11-15T00:05:03.745Z</atom:updated>
            <content:encoded><![CDATA[<p>My first job out of college was in insurance analytics. I learned a lot about insurance and a <em>lot</em> about Excel. Excel, and now Google Sheets, is a pivotal tool in analytical and operational jobs, but it’s not as popular for data engineers. The way you think in databases and Excel are different, and tool switching can be just as bad for productivity as context switching, so I do everything in SQL/Snowflake when I can. I export to Google Sheets as a last result (usually when the stakeholder requests it).</p><p>For that same reason, I often have stakeholders who, when they have to do something in Snowflake, “speak” Excel to me; they want to know how to do a <em>vlookup</em>, get <em>subtotals</em>, or do an <em>if</em> statement. This guide attempts to bridge the communication gap between analysts and data engineers by translating Excel to SQL. Now perhaps we will have more to discuss than just the fact that people think we’re all data scientists. Not everyone who works with data is a data scientist. I’m talking to you, LinkedIn recruiters and non-technical friends.</p><h3>IF Statement (and other IFs)</h3><h3>IF</h3><p>An IF statement is powerful; it helps you do everything from fix typos to group data. In the example below, I create a “Mac?” column that is True when the cat is Mac.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*_Zv7Gx6qoJ_V9QjI.png" /></figure><p>The formula for this is:<br>=if(C2=&quot;Mac&quot;, True, False)<br> If we imagine we had the same cat table in Snowflake, the equivalent formula would be:</p><pre>SELECT <br>*,<br>IFF(cat_name = &#39;Mac&#39;, True, False) AS is_mac<br>FROM cat_table;</pre><p>In a database, double quotes (“) also denotes a database object, such as a column name. A literal string (Mac) is put in single quotes. Other than that, the function is quite similar.</p><p>Snowflake reference for <a href="https://docs.snowflake.com/en/sql-reference/functions/iff.html">IFF</a></p><h3>IFS</h3><p>The complexity comes in once we there are multiple IF statements to evaluate. To determine whether the cat is one of the twins, I have to allow that the cat could be either Mac or Cheese (they actually had another litter mate who we could not adopt). I also want to label them Twin1 (Mac) and Twin2 (Cheese). In Excel, the function is:</p><p>=if(C2=&quot;Mac&quot;, &quot;Twin1&quot;, if(C2=&quot;Cheese&quot;, &quot;Twin2&quot;, &quot;Not Twin&quot;))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*awivQSwXYP9NqRSL.png" /></figure><p>Notice how in order to have more than two outcomes (True/False versus Twin1/Twin2/Not Twin), we need to embed another IF statement into the false_value. This gets unreadable really quickly. Luckily, in SQL you can do what’s called a case statement or a case when statement. A case statement for this would be:</p><pre>SELECT <br>*, <br>CASE <br>WHEN cat_name = &#39;Mac&#39; <br>   THEN &#39;Twin1&#39; <br>WHEN cat_name = &#39;Cheese&#39; <br>THEN &#39;Twin2&#39; <br>ELSE &#39;Not Twin&#39; <br>END AS twin_number<br>FROM cat_table;</pre><p>Maybe it is the spacing or the lack of parenthesis, but I find this more readable and intuitive. Notice the single quotes again. The ELSE clause is optional; without explicitly giving a value to those that do not fall in a category, they will be NULL. I often write “ELSE NULL END” to be explicit, but this is technically redundant. Similar to Excel, the resulting value of the CASE WHEN is whichever evaluates as true first. In our example, a cat cannot be named Mac and Cheese, so let’s say we had this statement:</p><pre>SELECT <br>*, <br>CASE WHEN cat_name = &#39;Mac&#39; THEN &#39;Twin1&#39; WHEN cat_color = &#39;Black&#39; THEN &#39;Twin2&#39; ELSE &#39;Not Twin&#39; END AS twin_number <br>FROM cat_table;</pre><p>Although Mac is black, he will have twin_number of Twin1 since cat_name = &#39;Mac&#39; evaluates to true first.</p><p>Note: I tried to use the Excel function IFS but I couldn’t figure out how to include a default value (“Not Twin”):<br>=ifs(C2=&quot;Mac&quot;, &quot;Twin1&quot;, F2=&quot;Black&quot;, &quot;Twin2&quot;)</p><h3>SUMIF</h3><p>Now that we know who the twins are, we can sum only the twins’ weights. In Excel, we would do: =sumif(I2:I4,True,G2:G4)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6GI-ZRETtoVtwBCh.png" /></figure><p>The twins total weight is almost 20 pounds!</p><pre>SELECT <br>CASE WHEN cat_name = &#39;Mac&#39; OR cat_name = &#39;Cheese&#39; THEN TRUE ELSE FALSE END AS is_twin, SUM(weight) AS total_weight <br>FROM cat_table <br>GROUP BY is_twin;</pre><p>This requires a bit of explanation. First we are using a case statement to label whether a cat is a twin or not. Then we sum the weights of cats grouped by is_twin. This will give us:</p><p>The results are not formatted the same as a SUMIF since we also get the non-twins weights, but we get the data we need: 19.8 pounds of mini demon panthers sent here to ruin my couch.</p><p>This query can also be written as</p><pre>SELECT SUM(weight) AS total_weight <br>FROM cat_table <br>WHERE cat_name = &#39;Mac&#39; OR cat_name = &#39;Cheese&#39; ;</pre><p>This will simply give you 19.8.</p><h3>COUNTIF</h3><p>If we want to count the number of female and male kittens we have, in Excel, we would do:<br>=countif(M1:M4, &quot;Female&quot;) and<br>=countif(M1:M4, &quot;Male&quot;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O5Ke8GCKPgXKWA9H.png" /></figure><p>Similar to the total_weight calculation above, this can be accomplished in SQL by:</p><pre>SELECT <br>  gender, <br>  COUNT(*) AS count <br>FROM cat_table GROUP BY gender</pre><p>This will give us</p><p>Note that Snowflake actually does have a count if: <a href="https://docs.snowflake.com/en/sql-reference/functions/count_if.html">https://docs.snowflake.com/en/sql-reference/functions/count_if.html</a></p><pre>SELECT <br>   COUNTIF(gender = &#39;Female&#39;) AS female_count <br>FROM cat_table</pre><p>I never use that function but maybe I’ll remember to now.</p><h3>SUBSTITUTE</h3><p>Let’s say we got user entered info for our cat named and they appeared like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*ox88Mt9Nh3--ryyK.png" /></figure><p>We would want to clean it up by removing the _, essentially replacing it with a blank string. We would do a substitute like this:<br>=substitute(B2, &quot;_&quot;, &quot;&quot;)</p><p>In Snowflake, we do a <a href="https://docs.snowflake.com/en/sql-reference/functions/replace.html">replace function</a>. With replace, if we want to eliminate, we can enter only two arguments if we want to replace the substring with the empty string:</p><pre>SELECT REPLACE(user_entered_cat_name, &#39;_&#39;) AS cat_name FROM cat_table</pre><p>Similar to in Excel, if you want to replace multiple strings, you have to embed the REPLACE function:</p><pre>SELECT <br>   REPLACE(REPLACE(user_entered_cat_name, &#39;_&#39;), &#39;!&#39;) AS cat_name<br>FROM cat_table</pre><p>It can end up being a really nasty line of code.</p><h3>CONCATENATE</h3><p>To conCATenate in Excel (ha, get it), you use &amp;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*-YD5atWwdhQHIpM7.png" /></figure><p>In Snowflake, you use || or the <a href="https://docs.snowflake.com/en/sql-reference/functions/concat.html">CONCAT function</a></p><p>No matter which one you do, remember the spaces:</p><pre>SELECT <br>cat_name || &#39; &#39; || cat_id, CONCAT(cat_name, &#39; &#39;, cat_id) <br>FROM cat_table</pre><h3>VLOOKUP / HLOOKUP</h3><p>I know often in Excel, in order to combine data from multiple tabs, people do a VLOOKUP or an HLOOKUP. In databases, a VLOOKUP is basically a JOIN. An HLOOKUP is not really a thing. I’ll explain why.</p><h3>VLOOKUP</h3><p>Let’s say someone gave us the cats cuteness levels</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*n1QXSKqBgqe4Tr4S.png" /></figure><p>To find the cats cuteness level, we do a VLOOKUP on Cat ID</p><p>=VLOOKUP(A2,Cuteness!A:B,2,True)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3oG7M2jQuIlXxrz-.png" /></figure><p>Perfect, the cats are all top level cuteness. Notice that the vlookup is “on” a certain field. This is the field that the two datasets have in common; more specifically, the field that has to be equal in order for the data to be relevant for the row. To do this in databases, we join:</p><pre>SELECT <br>* FROM cat_info <br>LEFT JOIN cat_cuteness <br>ON cat_info.cat_id = cat_cuteness.cat_id</pre><p>Notice that we are joining “on” cat_id. In SQL, you can join on multiple fields (or none! don’t do that!). It’s most common to join on an ID field though.</p><p>Notice also that I used a LEFT join. Unlike in a VLOOKUP, we can choose what to include in the final data set. Had I used INNER JOIN, any cat_info without a cat_id in cat_cuteness would not have shown up in the data set. A RIGHT join would be the reverse of this; it would be like doing the VLOOKUP on the cat_cuteness tab.</p><h3>HLOOKUP</h3><p>To be honest I haven’t used Excel in so long I couldn’t find a reason why you would need an HLOOKUP, except that someone who hates you gave you data. That’s okay. It happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*urxQ7tME9qlr4Ew1.png" /></figure><p>Let’s say someone gave you that. In order to get the info on to the main tab, we have to do:<br>=hlookup(A2,&#39;Cuteness, but someone who hates us gave it to us&#39;!$A$1:$D$3,2,false)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZLw4F0HRhp4-N710.png" /></figure><p>There is no real hlookup in databases, because in databases, all tables and entities have to be formatted in the same way (with the column names being the first row).</p><p>If you can think of an example of HLOOKUP that you would be able to do in a database, let me know.</p><p><em>Originally published at </em><a href="https://www.alisa-in.tech/post/2020-11-02-excel/"><em>https://www.alisa-in.tech</em></a><em> on November 1, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bde6541aa1ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Good Day to Delete Hard]]></title>
            <link>https://medium.com/analytics-vidhya/a-good-day-to-delete-hard-22b8be83b622?source=rss-d62574a9c178------2</link>
            <guid isPermaLink="false">https://medium.com/p/22b8be83b622</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[snowflake-computing]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Alisa Aylward]]></dc:creator>
            <pubDate>Sun, 05 Jan 2020 00:23:23 GMT</pubDate>
            <atom:updated>2020-01-15T12:25:54.636Z</atom:updated>
            <content:encoded><![CDATA[<p>Deletion method is an important data warehousing concept, one you’d ideally master before an interview. It is not a matter of memorizing the definitions of the two main methods (which I copy from the internet for you below), but rather understanding the consequences of choosing one over the other.</p><h3>What are the types of deletes?</h3><p>The deletion methods describe how a database (or a specific table) changes when a record is set to be deleted.</p><p><strong>Hard Deletes</strong> — The entire record is deleted from the table. After the delete, users will not be able to see that the record ever existed.<br><strong>Soft Deletes</strong> — The record is not removed from the table, but a field on the table indicates that it is deleted. The field can be a boolean such as is_deleted or a timestamp such as deleted_timestamp. It&#39;s usually best if this field name is consistent across all tables so users can readily and dynamically find the non-deleted data set. ( <a href="https://www.stitchdata.com/docs/replication/deleted-record-handling">Source</a>)</p><h3>When should we use hard deletes?</h3><p>Soft deletes are not a good idea in an analytic data warehouse. Stakeholders expect to see a table with only relevant records; for analytical data warehouse users, cats_dim means &quot;a list of cats who are currently active.&quot; See the table below as a counter example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*9d1jN8n1UAKt659NxSRpVQ.png" /><figcaption>cats_dim</figcaption></figure><p>An analyst (who likely hasn’t read all the field names, because there’s probably more than just the three provided) may quickly try to find the count of current cats with select count(*) from cats_dim</p><p>This would give her three cats, instead of the real answer of two (of course we couldn’t adopt Sushi, although he was <a href="https://www.instagram.com/p/B6QpTtNpniF/">cute</a>. Our hearts are already full).</p><p>This isn’t the worst mistake in the world, but imagine instead of count(*) it was sum(revenue). Now imagine that metric was reported to an executive. You see where I&#39;m going with this.</p><p>So by convention, in a data warehouse, we do hard deletes. But that doesn’t mean we do them everywhere.</p><h3>When should we use soft deletes?</h3><p>We know that hard deletes are helpful when users are expecting only current data, but there are other types of users out there. For example, the team that writes the ETL from source databases — us!</p><p>As part of the ETL, we retrieve datasets from a source database either as a full extraction or incremental extraction. In a full extraction, we pull the entire dataset every time we need more data (the dataset is usually a table, but it can be a report at an API endpoint). This is the most computationally expensive way to get data, but the easiest to code.</p><p>In the case of an incremental extraction, we only query for the data we have not seen yet from the source. We may write this query using a metadata field that represents the last time that record was modified in the source database (I like to call this field last_modified_timestamp, but often you’ll see it called systimestamp or sysmodtimestamp by convention). In our extraction query, we effectively say “yesterday I got data up until 2019–01–01, please give me the data that has been updated since then.” This allows us to extract and load fewer rows, saving compute and possibly storage.</p><p>So what happens if a source database does hard deletes? Let’s say we extract data a table called cat_hospitalization_fact in the source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oCyQpPwwYGfHv0w5N2Ur8g.png" /><figcaption>cat_hospitalization_fact</figcaption></figure><p>If we incrementally extracted from this table on 2019–12–19, we received all three of those rows. Now let’s say we revisit the table on 2019–12–20, when it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8GU3-lcRqM2-fPA1qvicpQ.png" /></figure><p>When we extract, we will get one new row about Tuna. Our table in our database will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NPi9kEpvKpe0JTQACcRefg.png" /><figcaption>cat_hospitalization_fact</figcaption></figure><p>When compared to the source, this is wrong because it still has Sushi’s hospitalization. For whatever reason, Sushi’s hospitalization was deleted. In order to have known this, we would have had to set the extraction date back to 2019–12–18, but, since we have no way of knowing which records will be deleted when, we’d actually have to set the extraction date back to the beginning of time to account for hard deletes. This would just be a full load.</p><p>When a source database has hard deletes, we have to do a full extraction to ensure we don’t misrepresent the data. This is expensive, especially as the data grows. If the source database had used soft deletes, it would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otm4q7wM7Sqe773rlhilVA.png" /><figcaption>cat_hospitalization_fact</figcaption></figure><p>When we extracted the data for the second time (on 2019–12–20), we would have received:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xRDt8z6TlVDiadRmuaCHw.png" /><figcaption>cat_hospitalization_fact</figcaption></figure><p>This would have indicated to us that Sushi’s record was deleted without having to pull the entire dataset. We can keep our incremental loads but not overstate data.</p><p>Looking at it from the perspective of the source database owners, another advantage of soft deletes is that they are easier to undelete.</p><p>So what do we do once we have this soft delete? It’s easy, we can use it in the merge statement (this example is <a href="https://docs.snowflake.net/manuals/sql-reference/sql/merge.html">Snowflake specific</a>).</p><p>Our merge statement would look like this:</p><pre>MERGE INTO cat_hospitalization_fact as t<br>USING source_data as s<br>ON t.cat_id = s.cat id<br>AND t.hospitalization_date = s.hospitalization_date<br>WHEN MATCHED THEN UPDATE SET<br>t.cat_name  = s.cat_name,<br>t.hospitalization_reason = s.hospitalization_reason,<br>WHEN NOT MATCHED THEN INSERT<br>(cat_id, cat_name, hospitalization_reason, hospitalization_date)<br>VALUES <br>(s.cat_id, s.cat_name, s.hospitalization_reason, s.hospitalization_date)<br>WHEN MATCHED AND s.is_delete = ‘Y’ THEN DELETE</pre><p>Notice the last line- we can use the soft delete from the source database to delete the record from our table. With hard deletes, we cannot do this; the absence of a row can’t create a delete in a merge, only a field indicating its deletion. In the case of hard deletes, we have to do a separate <a href="https://docs.snowflake.net/manuals/sql-reference/sql/delete.html">DELETE statement</a>.</p><h3>Conclusion</h3><p>There is no clear winner between soft deletes and hard deletes; each has its own usage and advantages. That being said, and I can’t stress this enough, do not let your cats eat thread. Also, can I borrow some money? Cat surgery is expensive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*UzLyTrDDktg3mJuQ" /></figure><p>My little cone head cat after surgery to get thread removed from his intestines</p><p><em>Originally published at </em><a href="http://www.alisa-in.tech/sql/2019/10/12/deletes.html"><em>http://www.alisa-in.tech</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22b8be83b622" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/a-good-day-to-delete-hard-22b8be83b622">A Good Day to Delete Hard</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Much Ado About NULL Things]]></title>
            <link>https://medium.com/@alisa.aylward/much-ado-about-null-things-222d1850aa32?source=rss-d62574a9c178------2</link>
            <guid isPermaLink="false">https://medium.com/p/222d1850aa32</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <dc:creator><![CDATA[Alisa Aylward]]></dc:creator>
            <pubDate>Sun, 13 Oct 2019 13:00:00 GMT</pubDate>
            <atom:updated>2019-10-13T13:00:00.130Z</atom:updated>
            <content:encoded><![CDATA[<p>We have to talk about NULLs.</p><p>This post won’t include anything revolutionary, but rather just a summary of what NULLs are, what they aren’t, and why they are important in data warehousing. It’s based on my own experience, not anything academic.</p><h3>What is NULL?</h3><p>NULL means nothing, but NULL is not “Nothing.” NULL means that “a data value does not exist in the database” ( <a href="https://en.wikipedia.org/wiki/Null_(SQL)">Source</a>). The value simply isn’t there; the value is <strong>not</strong> 0, N/A, or False. N/A, for all its ambiguity, is a value. Resisting the temptation to create a default value for a field may be counter-intuitive, but using NULL correctly can benefit both the end user and you.</p><h3>Why does using NULL help the end users?</h3><h3>Correct Aggregated Results</h3><p>Let’s say you have a table that includes both dates and names, like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zEvam0vqNuHNTG3nBwmO-Q.png" /><figcaption>cat_adoption_fact</figcaption></figure><p>If we want to add a future cat but we don’t use NULL, we may put in an entry such as the following to communicate that I don’t yet have a cat:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Os23XJwfAQmHiv7uCBZiw.png" /><figcaption>cat_adoption_fact</figcaption></figure><p>If you use intuition, the results of a select * will make it clear that I adopted two cats. However, this is a small table; in bigger tables we are unable to view all records at once. As a result, users often use aggregates such as:</p><pre>SELECT COUNT(*) FROM cat_adoption_fact;</pre><p>or</p><pre>SELECT <br>	MONTH(adopted_date) AS adopted_month, <br>	COUNT(*)  AS cat_count<br>FROM cat_adoption_fact<br>GROUP BY adopted_month</pre><p>The former query gives 3 results, which may indicate to the stakeholders that I have three cats when, unfortunately, I do not. The latter query is more of an issue though. The results are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JrW3jgIpfWD-qn5Upe2PMQ.png" /><figcaption>Result set for cats per adopted month</figcaption></figure><p>This table clearly tells the end user that I adopted two cats in October and one in December. I wish.</p><h3>Easier Querying</h3><p>Since a default is automatically different depending on the data type, using NULL is the only way to gain consistency across fields and data sets.</p><p>For instance, from the above cat_adoption_fact table, in order to correctly get the results expected from the above query, a user would have to write:</p><pre>SELECT <br>	MONTH(adopted_date) AS adopted_month, <br>	SUM(CASE WHEN cat_name = &#39;No Name&#39; then 0 ELSE 1 END) as count_cat<br>FROM cat_adoption_fact<br>WHERE adopted_date != &#39;2099-12-31&#39;<br>GROUP BY adopted_month</pre><p>This would tell the user I only have two cats (sigh), both adopted in October, but notice how much more domain knowledge the user has to have. Not only does this require more functions (more about that below), but it also requires the user to know that the default value for cat_name is “No Name”, while the default value for adopted_date is 2099–12–31. These choices were not totally mine; since the adopted_date field has data type Date, it can only contain a Date value or a NULL. So we cannot fill both fields with “Not Applicable.” This would also be true of a Boolean, which can only be True, False or Null. “Unknown” or “Not Applicable” are not valid Boolean fields. <br>Since a table (not to mention a data mart) are likely to have multiple data types, the onus will always be on the user to know the value of the default for each type. Additionally, since these default values look the same to the database as any other value, there is nothing ensuring that the default value is consistent across fields with the same data type. So we may see the following in the data warehouse, in addition to the cat_adoption_fact table we may have a cat_color_dim table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPi0PYxwGCHO4fY_salkVw.png" /><figcaption>cat_color_dim</figcaption></figure><p>The end user, who may now feel that they have the hang of “No Name”, will now have to manually inspect this table in order to write this query in order to find the count of cats for each color:</p><pre>SELECT <br>	cat_color_name,<br>	SUM(CASE WHEN cat_name = &#39;No Name&#39; then 0 ELSE 1 END) as count_cat<br>FROM cat_adoption_fact<br>WHERE cat_color_name != &#39;Unknown&#39;<br>GROUP BY cat_color_name</pre><p>Notice that, within this one query, the user has to know two distinct default values. This is asking a lot of the user and setting them up for potential incorrect results.</p><h3>Cleaner Code</h3><p>Database management systems have built in functions and default behavior that only apply to NULL. Leveraging out of the box functions keep your code cleaner for easier understanding and incrementing.</p><p>I will be focusing on Snowflake to keep the explanations concise, but know that another RDMS may have an equivalent function.</p><h4>Default Behavior</h4><p>Assume our table was contained NULLs, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7ehLbIpr6278jTjCx0amA.png" /><figcaption>cat_adoption_fact</figcaption></figure><p>If we rerun our first two queries, they get different results.</p><pre>SELECT COUNT(*) FROM cat_adoption_fact;</pre><p>By default, Snowflake will not count any NULL values (<a href="https://docs.snowflake.net/manuals/sql-reference/functions/count.html">source</a>), so this will return 2. I only have 2 cats. Stop rubbing it in.</p><pre>SELECT <br>	MONTH(adopted_date) AS adopted_month, <br>	COUNT(*)  AS cat_count<br>FROM cat_adoption_fact<br>GROUP BY adopted_month</pre><p>This query results actually will include NULLs, but as its own line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QIB6UK0bRE7HHy_RzeOznQ.png" /><figcaption>Result set for cats per adopted month</figcaption></figure><p>This makes it clear to the user that the third cat has not been adopted. <br>The following functions also only aggregate non-NULL values:</p><ul><li>AVG</li><li>STTDEV</li><li>SUM</li></ul><p>Using 0, -1, or any other numeric value to indicate NULL will impact these functions.</p><p><strong>Note</strong>: You can combine the default behavior of COUNT with the grouping to create the following query:</p><pre>SELECT <br>	MONTH(adopted_date) AS adopted_month, <br>	COUNT(cat_name)  AS cat_count<br>FROM cat_adoption_fact<br>GROUP BY adopted_month</pre><p>This would result in the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rA907OcNHX7o61GzXEIr_Q.png" /><figcaption>Result set for cats per adopted month</figcaption></figure><p>Some may prefer that result set to indicate that there is no third cat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*5Ye3g9koRwy0s6ce" /></figure><p>Plenty of space for a third cat</p><h4>Built in Functions</h4><p>Snowflake’s built in functions that handle NULLs are:</p><ul><li><a href="https://docs.snowflake.net/manuals/sql-reference/functions/coalesce.html">COALESCE</a></li><li><a href="https://docs.snowflake.net/manuals/sql-reference/functions/nullif.html">NULLIF</a></li><li><a href="https://docs.snowflake.net/manuals/sql-reference/functions/zeroifnull.html">ZEROIFNULL</a></li><li><a href="https://docs.snowflake.net/manuals/sql-reference/functions/ifnull.html">IFNULL</a></li></ul><p>Without these built in functions, a query as simple as:</p><pre>SELECT <br>	COALESCE(cat_nickname, cat_name) AS cat_name<br>FROM cat_dim;</pre><p>May have to be written as:</p><pre>SELECT <br>	CASE WHEN cat_nickname = &#39;No Nickname&#39;  THEN  cat_name ELSE cat_nickname END AS cat_name<br>FROM cat_dim;</pre><p>Notice how less concise the second query is despite the fact that this is simple logic. In more complicated queries, functions such as COALESCE can help readability and therefore productivity.</p><h4>But what about ORDER BY?</h4><p>An argument for default values such as 2099–12–31 is that this would allow adopted cats to always precede not-yet-adopted cats in an order by. However, by default, NULLs come last in an ordering of dates anyways, but if you wanted the default date to come first in this case you could do:</p><pre>SELECT <br>*<br>FROM cat_adoption_fact<br>ORDER BY adopted_date DESC</pre><p>This is actually easy to replicate with NULLs and the query is more explicit:</p><pre>SELECT <br>*<br>FROM cat_adoption_fact<br>ORDER BY adopted_date NULLS FIRST</pre><p>Using NULL actually gives you more control over <a href="https://docs.snowflake.net/manuals/sql-reference/constructs/order-by.html">ORDER BY</a>. Window functions even have a feature to IGNORE NULLs (<a href="https://docs.snowflake.net/manuals/sql-reference/functions/lag.html">See an example here</a>).</p><h3>But are there gotchas?</h3><p>Yes. NULL does not equal NULL. So if you try to join two tables, if both values in your join are NULL, those two record will not be considered a match. However, the workaround to this is the built in <a href="https://docs.snowflake.net/manuals/sql-reference/functions/equal_null.html">EQUAL_NULL</a> function in Snowflake.</p><h3>TL;DR</h3><p>NULL has its own meaning; it cannot be replaced with a default value. It may feel counterintuitive, but using NULL will actually create cleaner, more explicit code and data sets that are easier for end users to consume.</p><p><em>Originally published at </em><a href="http://www.alisa-in.tech/sql/2019/10/12/nulls.html"><em>http://www.alisa-in.tech</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=222d1850aa32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Normal Forms for Normal People]]></title>
            <link>https://medium.com/@alisa.aylward/normal-forms-for-normal-people-2f25e44ea80b?source=rss-d62574a9c178------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f25e44ea80b</guid>
            <category><![CDATA[data-warehousing]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <dc:creator><![CDATA[Alisa Aylward]]></dc:creator>
            <pubDate>Sat, 07 Sep 2019 22:23:13 GMT</pubDate>
            <atom:updated>2019-09-07T22:23:13.792Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is for my friend Mitch, who, despite his persistent belief that he annoys me with his questions, has reminded me why it’s important that we stay hungry for theoretical knowledge even as we get caught up in our day-to-day work.</p><h3>What are normal forms?</h3><p>Normal forms are properties one can apply to a database to normalize it. Does that not help? I felt like it helped but then I re-read it and I realized it was meaningless. Okay, Wikipedia said database normalization “is the process of structuring a relational database [. . .] in order to reduce data redundancy and improve data integrity.” (<a href="https://en.wikipedia.org/wiki/Database_normalization">source</a>). This process is a collection of steps you can take. These steps are called normal forms. They go in order. This is a significantly better definition. Basically, you want the design of your database to allow for easy inserts and updates that don’t cause duplicates and break everything over time, and, to do this, you walk through the normal forms and apply them to your database.</p><p>There are ten normal forms; each time a database adheres to an increasingly normalized form, it is said to “satisfy” that form. So, in the process of normalizing your database, you satisfy first normal form (1NF), second normal form (2NF), third normal form (3NF), then Boyce-Codd normal form. Yeah, that is where it gets weird. The forms are in order in the sense that if a database schema satisfies 3NF, that means it satisfies 2NF and 1NF. We are going to focus on only the first three normal forms, as those are by far the most commonly satisfied because, as we will see, the forms get increasingly hard to satisfy and they correct for increasingly rare potential bugs.</p><h3>Are normal forms still relevant?</h3><p>Normal forms hold a special part in my heart; like others who have taken a database class, I lived and died by them for an entire semester. I read Kimball’s book. I memorized the definition and an example and counterexample for each form. I learned then and I still believe now that Kimball’s work on data warehouses, including normalization, revolutionized data warehousing and paved the way for the rise of big data and data science.</p><p>However, I treat the topic differently in a professional setting. Who has time to talk about normal forms when things are breaking? Who has time to explain a normal form to a stakeholder who doesn’t want to do 10 joins? Just add the column to the table!</p><p>It is a contradiction that I firmly hold the following two beliefs: normal forms are one of the most important concepts of data warehousing and that normal forms are interview questions unrelated to our “real” job. I have to reconcile these two beliefs.</p><h3>What can I add to the conversation about normal forms?</h3><p>I have to sort out my contradictory feelings on normal forms. To do this, I’m going to walk through the normal forms, not for a five year old (Rhys is six now, by the way, he didn’t get a gift from you), but for normal people; for people who talk to stakeholders every day; for people who don’t have infinite time to consider the impact of database design; for people who read the blog posts on this site. So, in short, very, very few people.</p><p>My fear in writing a post is that I will simply rewrite the Wikipedia page in a lower grade level. I don’t want to do that. I know you can read Wikipedia. But can I write a post for Mitch who wants to know the theory but only as he can apply it to his job?</p><h3>How can I memorize the forms?</h3><p>You can’t, that’s crazy. Lower your ambitions in life, jeez. I can only help you remember the first three. I’ve heard this phrase in a few different ways but Wikipedia attributes the following to William Kent: “[every] non-key [attribute] must provide a fact about the key, the whole key, and nothing but the key”. (<a href="https://en.wikipedia.org/wiki/Third_normal_form#cite_note-Kent-7">source</a>). You say this in the same cadence as “the truth, the whole truth, and nothing but the truth.” This has helped me keep the forms straight in stressful situations like interviews or tests (“the key, the whole key, and nothing but the key”). We will walk through what this means.</p><p>If you need to brush up on primary keys, please see the post <a href="http://www.alisa-in.tech/eli5/2018/08/15/pks.html">here</a> before continuing.</p><blockquote>The key, the whole key, and nothing but the key</blockquote><h3>First Normal Form</h3><h3>What is 1NF?</h3><p>The key. The table must have a key, all other fields must depend on that key, and each field value must be atomic. The concept of fields depending on the primary key may be a little vague, but Wikipedia has a great <a href="https://en.wikipedia.org/wiki/Functional_dependency">page</a> on functionality dependency. For now, I think it’s sufficient to say that the table has a primary key and this primary key is unique.</p><h3>What does violating 1NF look like?</h3><p>A table in first normal form will look like a table with a primary key that each of the non-primary key fields depend on in some way, meaning they will describe the primary key field and contain one value each. A <em>violation</em> of first normal form looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kvFsGNVCCipBnnBBhbDpsg.png" /><figcaption>not_first_normal_form_cat_table</figcaption></figure><p>An additional violation would be if the table simply did not have a primary key or it had a bunch of unrelated fields, but that is harder to represent visually, and, in my opinion, less likely to happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iw04xJrsoJbJk6jk" /><figcaption>The day we adopted Mac and Cheese</figcaption></figure><h3>What happens if I violate 1NF?</h3><p>The cat table above has an obvious drawback: it’s extremely hard to filter for the cats that Alisa owns. For instance, you can’t get the right results from:</p><pre>SELECT cat_name FROM not_first_normal_form_cat_table<br>WHERE parents = &#39;Alisa&#39;</pre><p>This will actually result in 1 row returned. In order to get the correct answer, you will have to do something like this:</p><pre>SELECT cat_name FROM not_first_normal_form_cat_table<br>WHERE parents ilike &#39;Alisa&#39;</pre><p>Which is less performant and less intuitive. Stakeholders may forget to use this syntax and incorrectly report metrics.</p><p>If you go back to the original reasoning for why we normalize our databases, you’ll see our concern was redundancy and data integrity. How is that impacted by first normal form?</p><p>Well, let’s try to make an update to not_first_normal_form_cat_table. Let’s say I changed my name to Alisa In-Tech. If this table satisfied 1NF we could do:</p><pre>UPDATE not_first_normal_form_cat_table<br>SET parents = ‘Alisa In-Tech’’<br>WHERE parents = ‘Alisa’</pre><p>But in this case, that would not work; this would only change the parent of Sleepy. We would have to do something like:</p><pre>DELETE FROM not_first_normal_form_cat_table<br>WHERE parents ilike ‘%Alisa%’;<br><br>INSERT INTO not_first_normal_form_cat_table<br>SELECT  * FROM source_data<br>WHERE parents ilike ‘%Alisa In-Tech%’;</pre><p>This works for the sample data I provided, but what if I had a sister named Analisa? I don’t, but I could if my parents were weird. All the Analisa owned cats would be deleted in the DELETE statement, then not inserted in the INSERT statement. So we have killed off Analisa’s cats. Great job. Hope you feel good about what you did, cat killer.</p><h3>Are there any benefits of violating 1NF?</h3><p>The last section was to bring awareness about the dangers of violating first normal form, but once you know the risks of making a choice, you are then prepared to know when to make that choice. One common violation I see a lot is putting the entire semi-structured source data into a field.</p><p>Now that database systems including <a href="https://docs.snowflake.net/manuals/user-guide/semistructured-concepts.html">Snowflake</a> have gotten better at ingesting semi-structured data such as JSON and Parquet, it has become trivial to store the entire record in one field. Unlike CSV ingestion, JSON ingestion will not break if there are missing keys, a key name change, or field values that change types. With less sensitive ingestion into the write schema, it becomes tempting to just provide this record of the complete data set in the read schema. Since Snowflake also makes it easy for end users to parse JSON (if you know what you are looking for), this cuts down on column add requests when a new key is set to the source. Is this a good idea for every data source? No. This can cause havoc and JSON blobs are large, making returning results take even longer. I only recommend it when:</p><ul><li>You know you will never do an update, insert, or delete based on the values in the JSON field</li><li>You have a data set that does not change shape much between the source and the production data (so it’s easy to just tack on the JSON field to the end of each record without doing much transformation on it)</li><li>The underlying data set has frequently changing field and keys values and types that stakeholders want to access shortly after a change. If the key names and field data types don’t change often, why not just parse them?</li></ul><h3>Second Normal Form</h3><h3>What is 2NF?</h3><p>The whole key. This means that every non-key attribute (every field that isn’t the primary key) depends on all the parts of the key. If a table has only one primary key and satisfies 1NF then the table automatically satisfies 2NF. This is the best case scenario for a test question. It saves so much time for that answer. <br> But let’s say we have a composite <a href="https://en.wikipedia.org/wiki/Compound_key">primary key</a> which, despite what a candidate once told me during an interview, is possible. 2NF says we should be sure that no non-key field depends on only part of our composite key.</p><h3>What does violating 2NF look like?</h3><p>Without loss of generality, let’s assume our composite key has two fields in our table that tracks cat weights: bad_2nf_cat_weight</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxHRS2l61dfqIudYZA_xYA.png" /><figcaption>bad_2nf_cat_weight</figcaption></figure><p>Technically, the names Mac and Cheese can be determined by (depend on) the primary key {Cat ID, Weigh in Date}. However, Mac and Cheese can also be unique determined by Cat ID (see not_first_normal_form_cat_table). So this is partial dependency; it violates 2NF.</p><p>Note: In this case, we would say that the cat’s name is “denormalized” on to the weight table. If there is a lot of instances of this, we may say that the database schema is “heavily denormalized.”</p><h3>What happens if I violate 2NF?</h3><p>So is this really bad? Don’t people who want who use the cat table want to know which cat we are weighing? The true 2NF form would be two tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kA9aN-9-408B9ElIZmrTiA.png" /><figcaption>cat_weight_fact</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kA9aN-9-408B9ElIZmrTiA.png" /><figcaption>cat_dim</figcaption></figure><p>We would expect the stakeholder to join cat_weight_fact to cat_dim on cat_id in order to find the name. <br> Why are two tables better than one? Well, let’s say we want to change Mac’s name to Macaroni (that is his full name, by the way, Macaroni In-Tech). To update the violation of 2NF, we would need to update 2 records, while in the 2NF example, we would only need to update one record in cat_dim.<br> Updating two records versus one is not that big of a deal, but data tends to grow, with fact tables growing much faster than dimension tables. So do you want to continue to update larger and larger tables with table scans? Or do you want to update one record and put the onus on stakeholders to do the join?</p><h3>Are there any benefits of violating 2NF?</h3><p>So when we do we make a calculated decision to disregard 2NF? There’s no hard and fast rule but in general, the following may make you consider violating 2NF:</p><ul><li>When you know the stakeholders will virtually always make this join</li><li>When the join to get the additional information will be expensive for stakeholders (post on expensive joins it forthcoming)</li><li>When the cat’s name (the denormalized field) will rarely if ever be updated</li></ul><h3>Third Normal Form</h3><h3>What is 3NF?</h3><p>And nothing but the key. We know all non-key fields already depend on the whole key, so how could the fields depend on anything other than the key? Well, we want to eliminate any instances of <a href="https://en.wikipedia.org/wiki/Transitive_dependency">transitive dependency</a>. A transitive dependency is when a non-key field depends on all parts of the key, but it could also be determined by another non-key field.</p><h3>What does violating 3NF look like?</h3><p>Let’s say we wanted to keep track of what the cats like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHU5E2cVnZirEnCFIT7OEg.png" /><figcaption>Bad_3nf_cat_favorite_food</figcaption></figure><p>Technically, every non-key attribute in this table depends on both parts of the primary key {Cat ID, Meal}, but are those two fields combined the only way we can determine each field? What I mean is- can we only determine that Mac’s favorite dinner food brand is Blue Buffalo from knowing that those two fields? Or could we determine that from the fact that his favorite food is Wilderness Indoor Chicken Recipe Grain-Free Dry Cat Food, which is only produced by Blue Buffalo? The latter, so we have a transitive dependency.<br> The solution would be, once again, to make two tables (normalization tends to create more tables and denormalization tends to collapse or combine tables):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7HB64yH01B8YxChqFXk8PQ.png" /><figcaption>cat_favorite_food</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WLRFvy7lACrbaz5jLVT0zw.png" /><figcaption>cat_food_dim</figcaption></figure><p>Note that in reality, we may use a surrogate key for Food Name since it’s so long, but I didn’t want to add additional numbers to this example lest I take away from the point.</p><p>Once again, we’re asking the stakeholders to join these two tables if they want to know the brand of Mac’s favorite dinner food.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*djJDWm4s-JZpKiG0" /><figcaption>Actually, Mac’s favorite food is pizza</figcaption></figure><h3>What happens if I violate 3NF?</h3><p>Let’s say you go with the first version of the table: bad_3nf_cat_favorite_food. This will get 2x bigger for every cat we get (assuming cats only eat dinner and snacks). So if a brand updated its brand name, it would take two times the compute to update bad_3nf_cat_favorite_food rather than cat_food_dim.</p><h3>Are there any benefits of violating 3NF?</h3><p>The benefit of violating 3NF if similar to that of 3NF: fewer joins for stakeholders. So if the join would be common, expensive, or the only way someone would view the data, consider denormalizing.</p><h3>So what did I learn?</h3><p>The normal forms have a very real business purposes, to make updates to and maintenance of a data schema easier. But there are trade offs involved. We want to use our knowledge of the data changes and stakeholder uses to make efficient decisions on when and how to normalize data.<br> And Mac and Cheese love food:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zZbV5NUVQtQIaRkm" /><figcaption>Always checking to see if there is better food for them</figcaption></figure><p><em>Originally published at </em><a href="http://www.alisa-in.tech/sql/2019/09/01/normal-forms.html"><em>http://www.alisa-in.tech</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f25e44ea80b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Language in Tech]]></title>
            <link>https://medium.com/@alisa.aylward/language-in-tech-597796c14a35?source=rss-d62574a9c178------2</link>
            <guid isPermaLink="false">https://medium.com/p/597796c14a35</guid>
            <category><![CDATA[engineering-culture]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[tech-culture]]></category>
            <dc:creator><![CDATA[Alisa Aylward]]></dc:creator>
            <pubDate>Thu, 06 Dec 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-12-10T02:22:34.256Z</atom:updated>
            <content:encoded><![CDATA[<h3>Speaking Flemish in Tech</h3><p>When I was in Belgium it was hard for me to communicate well. This is partially because I don’t speak French, partially because I don’t speak Flemish, and partially because I never knew when to not be able to speak which language. For those not in the know, it’s best to fail at French in Brussels and flounder at Flemish in Flanders. I took one year of German in college, so, equipped with this, I asked some teenagers (in what I thought was Flemish) if the next stop on the train was Bruges. They said yes and then turned away from me and laughed, mocking me in Flemish or French or a language created just for that purpose. In that moment, hearing twelve year olds make fun of me, I reprimanded my unprepared self: I should have taken German for another year; I should have learned Dutch; I should have bought a little travel phrase guide; I should have used Google translate to ask about the stop; I should have watched the Rick Steves episode on Belgium; is there a Rick Steves episode on Belgium?; please, there’s a Rick Steves episode on every country; that guy masters knowledge without arrogance; did we miss the stop?</p><p>There is tendency to put engineers on a pedestal and focus on their intelligence. You see this on the TV show Silicon Valley and The Big Bang Theory. To emphasize how much engineers exist outside of the sphere of regular intelligence, these shows focus on engineering lexicon. A quick Google search of Sheldon quotes gave me this gem: “This is a classic example of Münchhausen’s Trilemma. Either the reason is predicated on a series of sub-reasons leading to an infinite regression, or it tracks back to arbitrary axiomatic statements, or it’s ultimately circular, i.e. I’m moving out because I’m moving out.”<br>Why is that funny? It’s funny because it has long words that nobody else understands and he says them in a deadpan way. This recipe has gotten the show twelve seasons so bravo. Regardless, Sheldon isn’t saying anything that a five year old can’t understand. He’s just defining a fancy term, <a href="https://en.wikipedia.org/wiki/M%C3%BCnchhausen_trilemma">Münchhausen Trilemma</a> which is a theory that the reasoning behind any statement is either:</p><ul><li>Circular, like when your mom says she’s mad because she’s cleaning, and she’s cleaning because she’s mad</li><li>Never-ending, like dominos of truth that knock each other over but keep going forever</li><li>Already known; it relies on something else that we already know to be true</li></ul><p>Besides the name, nothing about that theory is particularly difficult. So is Sheldon a genius for responding with that answer to the question of “Why are you moving out?” It seems like he could have just said “I don’t know” or “I don’t want to explain” and he would have been more easily understood.</p><p>So what’s the point? Teenagers made fun of me and Big Bang Theory is overrated? Yes. Also, technical terms have a time and place, and using them when inappropriate can make others doubt themselves. In a relevant technical conversation, engineers need to use their jargon to be as detailed as possible. That is entirely appropriate. But, as Sheldon’s ridiculous answer indicates, some engineers may continue to use this jargon in times when it’s not necessary and it can even derail or disturb from the conversation.<br>I make this point because I have seen how some non-engineers accept without proof the fable that engineers are smarter than them. This acceptance does not help collaboration or synergy; it does not help a business to have some employees think of themselves as lesser. And it’s simply not true. There are many meetings that include engineers and non-engineers, as in an interview debrief. Does it help the conversation for engineers to use technical terms when it is not necessary? Not only does it perpetuate the stereotype that engineers speak a different language, it also creates an environment where part of the meeting participants are left out of the conversation. <br>Given all that we know about how engineers are portrayed in popular culture, do we expect the recruiters or analysts in the meeting to interrupt and say “I’m sorry, you’re using technical terms that other people don’t understand, could you explain them if they’re relevant or, if they’re not relevant, can we move on?” Is it appropriate for us to put the onus on someone else to step in and remind us when we’re being rude?<br>This behavior does not help us reach business solutions; it helps to otherize engineers and create miscommunication. In cases where we use too many technical terms at inappropriate times, we are isolating our non-technical or junior colleagues and inadvertently making them feel inferior. To be clear, not everyone feels less intelligent when they hear words they don’t understand, but it is certainly a potential response to not being able to follow a conversation. We do not want to make our colleagues doubt their intelligence.</p><p>So how can we prevent this division from happening or worsening? I have some ideas (of course I do): <br> <strong>Use technical jargon only when appropriate<br></strong>As engineers we are so used to speaking in certain terms, it may be hard to transition to layman’s terms. But remember, in a meeting with marketing analysts, use the terminology that will help everyone stay on the same page and get to the business solution. We would not appreciate if marketing analysts conducted the entire meeting with undefined acronyms that we did not understand.</p><p><strong>Ask if anyone needs terms explained<br></strong>If during a meeting or group lunch, another engineer is using some heavy technical jargon and you have a pretty good idea that others are lost, speak up. You can say something along the lines of “does everyone know what X means?” or, more to the point, “is this conversation relevant to everyone? If not, maybe we should move it to a specific meeting on that topic.”</p><p><strong>Have the Flemish conversation when people make self-deprecating jokes or comments<br></strong>At a lot of companies, I have gravitated towards recruiters since they tend to be my age and gender. I have heard them make self-deprecating remarks in response to communication with an engineer. If you hear this, consider explaining that time you were on a train in Belgium and teenagers made fun of you. Ask anyone who claims they’re not smart because they don’t know what for-loops are: was I supposed to think that I am not smart because I can’t speak Flemish? It’s not that I’m not willing to be self-deprecating when there are lessons to be learned, it’s just that I don’t consider myself less intelligent than Belgian teenagers because they know Flemish. It makes sense that they would know Flemish, they grew up learning that language. When they were drinking melk, I was drinking milk; when they were playing with kinderspeeltje, I was playing with toys. It makes sense that engineers would know what for-loops are; while engineers are writing loops, recruiters are writing job descriptions and program managers are writing requirements.</p><p>We should be careful of when and how we use technical language and how it affects those around us. We should be careful not to otherize ourselves and isolate our colleagues. And let’s remind ourselves and others and those rude teenagers that not knowing a language isn’t a reflection of our intelligence.</p><p><em>Originally published at </em><a href="http://www.alisa-in.tech/engineering/2018/12/06/language.html"><em>www.alisa-in.tech</em></a><em> on December 6, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=597796c14a35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ELI5- Slowly Changing Dimensions]]></title>
            <link>https://medium.com/@alisa.aylward/eli5-slowly-changing-dimensions-a4e2bf42cba1?source=rss-d62574a9c178------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4e2bf42cba1</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[eli5]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Alisa Aylward]]></dc:creator>
            <pubDate>Wed, 18 Jul 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-12-11T04:29:54.578Z</atom:updated>
            <content:encoded><![CDATA[<h4>I try to explain like I’m 5 (ELI5) the data engineering concept of slowly changing dimensions. Antics ensue.</h4><p>Explain like I’m 5 (ELI5) comes from the popular concept that if you really know something well, you can explain it simply, so a five year old can understand. I’ll try to do an ELI5 about Slowly Changing Dimension (SCD) to prove I know it well. Also, this post has the added benefit of preparing study material for five year olds who want to become data engineers.</p><p>SCD is a concept in data warehousing that aims to solve how to store information about a dimension as it changes over time. The rate of change is considered slow, although I don’t know if there’s a percise function for calculating its speed.</p><p>My nephew just turned five. He loves dinosaurs, so I’ll pretend I’m explaining SCDs to him. His name is Rhys (pronounced Reese).</p><p>So Rhys, a dimension is just a fancy word for a person, place, or thing. It can be a thing that you can touch or a thing you can’t touch. You can touch your stuffed animals, they’re things, but a party is also a thing, but you can’t touch it. If you aren’t sure if something is a thing, try to put an “a” in front of it: a stuffed animal, a party, a car, a house. That’s a dimension!</p><p>So a stuffed dinosaur is a dimension because it’s a thing. But we have lots of stuffed dinosaurs, so let’s say we wanted to list them. We may give them numbers (surrogate keys) like 0,1,2,3 and 4, but these don’t mean anything about the animal itself. It’s just so we can quickly identify them. Also, if we ever want to give the two dinosaurs the same name, their numbers would distinguish them1.</p><p>So we list our animals! We record their number and some stuff about them (attributes). Let’s record their name and their description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*csCq9qt_HRG0FEhP8Op6hA.png" /></figure><p>But sometimes we may want to change our list. We may get new animals as presents! Or we may rename one. We would want our list to be up to date right? Adding a new animal is easy, we can just add it to the bottom:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDkoMBdQ-wGN_rODGGMtAA.png" /></figure><p>Easy! But what if we want to rename one of our dinosaurs? That happens, doesn’t it? Well we have a few options of how to do this:</p><p><strong>Type 1</strong> <br> Let’s call this way Type 1. In this way, we make a whole new list with the updated info. So if we want to rename Brachie to Bronchy, we would pull out a new piece of paper and write:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gycKubNVFxdUjNxaBh168Q.png" /></figure><p>Awesome! Only now if someone asked us about Brachie, we might not remember which one that used to be or when we changed his name. We don’t have any of his old data. If we lost a dinosaur and made a new list, we may forget that dinosaur ever existed.</p><p><strong>Type 2<br></strong>Maybe we want to cross out the Brachie line lightly so we can still read his old name, and also write down the date that we crossed it out. That way, we can see his old name but we know it’s not real anymore. Instead of crossing it out, let’s put an end date to show where we would have crossed it out, then we can add his new information under it (with a new fake number). Let’s also record when we got them as a start date! Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgqEjOpnkMDE26RFrDKlHQ.png" /></figure><p>I know it looks like you have 5 dinosaurs when you really don’t, but that’s okay. You just have to look at all the rows where there is no “date changed” date.</p><p><strong>Type 3<br></strong>We have all the information we want recorded, but I guess it looks like you have five dinosaurs when you don’t, and if people think you have more than you really do, they might stop buying you gifts. I get that. What if we recorded both names? The old and the new? Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6IKTib1nJAutdWxqHqQIMw.png" /></figure><p>Now we have both names and we know we only have four stuffed animals! The only problem is– what if the description changes too? Do we have to make a new column for everything that changes? Also, what if we change the name again? Do we make another column or lose the first name?</p><p>I personally favor Type 2 best. Do you? I get that, but I really think your Auntie Katie will buy you stuffed animals no matter how many are on your list.</p><p>One of many sources potentially on the web for SCD: <a href="http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/10g/r2/owb/owb10gr2_gs/owb/lesson3/slowlychangingdimensions.htm">http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/10g/r2/owb/owb10gr2_gs/owb/lesson3/slowlychangingdimensions.htm</a></p><p><em>Originally published at </em><a href="http://www.alisa-in.tech/eli5/2018/07/18/eli5-scd.html"><em>www.alisa-in.tech</em></a><em> on July 18, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4e2bf42cba1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beer in Tech]]></title>
            <link>https://medium.com/@alisa.aylward/beer-in-tech-372858f0086e?source=rss-d62574a9c178------2</link>
            <guid isPermaLink="false">https://medium.com/p/372858f0086e</guid>
            <category><![CDATA[womens-health]]></category>
            <category><![CDATA[women]]></category>
            <category><![CDATA[startup-culture]]></category>
            <category><![CDATA[equality]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <dc:creator><![CDATA[Alisa Aylward]]></dc:creator>
            <pubDate>Mon, 09 Apr 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-12-08T21:48:44.091Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m wondering if beer in tech has reached its expiration date. Does beer expire? I don’t know.</p><p>Full disclosure: I hate beer. It tastes like bitter wheat, it fills me up too quickly, and the fancy craft beer places always have lines. And I hate lines almost as much as I hate beer. But I think there are bigger issues here than my colleague’s taste in drinks.</p><p>Beer culture has somehow embedded itself into tech and startup culture. How often do the number of taps or the happy hours of a company appear on the “Join Us!” page of a tech company? At $job-1, I received three bottle openers in my seven months there. The large, branded backpack they gave me at orientation had one, as though camping and drinking beer were my weekend hobbies; they gave me a branded keychain bottle opener; and finally, at one point, they just gave me a branded bottle opener. The fact that beer related items were one of the ways they chose to brand themselves is telling of the relationship between tech and beer. Branded items typically double as talent attraction tools in addition to traditional marketing tools. Listing happy hours is also a talent attraction tool. But who are these attracting? Are these tools sexist?</p><p>The obvious retort to “is beer sexist?” is simply “women like beer too!” Oh yes, some do. Some like beer a lot. Not every feminist is beer-hating like yours truly. There are beer-loving feminists, and they are great too. In fact, in college I had a beer-loving feminist as a roommate, and her rugby teammates, who helped me move their keg out of the shower at 10 am, were very nice. For follow up questions on why the keg was the in shower, please ask Lizzie.</p><p>But it’s not the beer itself. It’s beer culture. If you do not believe me, Google “beer ads women.” Do it, I’ll wait.</p><p>Now, ask yourself: Do the women in the images look like your wife, friends, mother? Do the men in the beer advertisements look like your husband, friends, father? Which gender is more realistically depicted? Do the advertisements seem to be appealing to women to drink beer, or are they appealing to men by using women as objects? <br>In researching this, I found a study (admittedly from 1994) titled ‘Women and “body-isms” in television beer commercials’ by Christine C. Iijima Hall and Matthew J. Crum. It found that beer commercials were more likely to show women’s bodies than men’s, even though men appeared more frequently than women. They were more likely to show men’s faces. Faces can display intelligence, while showing only body parts indicates a woman isn’t a full person, just a sum of parts available for men’s satisfaction. Furthermore, for some reason, women appeared in bathing suits more often than men. As you know, bathing suits are in season for only a short amount of the year and certainly not professional attire. Why can’t women in beer commercials wear jeans? Why can’t they be…normal humans?<br>Hall and Crum broached the concern that these images could be dehumanizing and I agree. When women are treated as just decorative objects to support men’s hobbies (drinking and watching football), they lose their individuality. Women are not the hip-hop backup dancers of life, and any depiction of them as such should be immediately perceived for what it is: sexist garbage. So beer advertisements are sexist garbage.</p><p>But there is one step further we can take this. I’ll introduce the next topic with a story about my Alma Mater (Lizzie was there too). At my school, as part of a larger effort to crack down on drinking, our college inexplicitly created a “Don’t be that girl” poster campaign. They put posters around the women’s dorms depicting drunk or hungover women being miserable, including of waking up in bed next a man . The posters were captioned: “You’re smart, Party smart.” <br>The response from the female students must not have been passive and sweet; we received a campus-wide email defending the posters a few days after they appeared. By then, Lizzie had already stolen and hoarded any poster she found; I’m not sure they ever printed more. Here is a picture of me with my cap and gown in front of some of the stolen posters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*wPuI3iZYMztKldlFdkqqeg.jpeg" /></figure><p>These posters had a thesis, and it was: you will be the victim of your own bad decisions if you drink too much. Women are told that in many ways, including victim-blaming for assault in high profile cases. It always come backs to how much the woman drank. This is not to say that giving me a keychain brought up all these thoughts and made me mad. No, I kept that keychain because it’s convenient. But this is women’s relationship with beer: being used as objects to sell it and then being told that, partaking in drinking it, opens you up to guilt and shame.</p><p>So you see, from women’s perspective, beer time might not be the best perk, especially if it’s after work. Women are more likely to abstain from drinking altogether if they’re trying to conceive, are pregnant, or are breastfeeding. Since women still disproportionately handle child care and domestic duties, they may have to leave right when work ends. So by putting a magnifying glass on women’s relationship with beer, we can see that there are better ways to appeal to potential and actual female employees.</p><p>I suggest:</p><ul><li>Make happy hours take place before work ends as to not exclude those who have to rush home for family responsibilities (men too!)</li><li>Supply an equal amount of wine, beer, cider, and non-alcoholic drinks</li><li>Refrain from having beer in the title; something like “social hour” is more generic</li><li>Displaying family-oriented benefits just as clearly and as often as beer-related websites, on your website and in interview conversations</li></ul><p><em>Originally published at </em><a href="http://www.alisa-in.tech/wit/2018/04/09/beer.html"><em>www.alisa-in.tech</em></a><em> on April 9, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=372858f0086e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>