<?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 Dylan Kaufman on Medium]]></title>
        <description><![CDATA[Stories by Dylan Kaufman on Medium]]></description>
        <link>https://medium.com/@dylan.kaufman?source=rss-1a3818055dd2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*X3iPHgQ9nj9z9vQ6Qe3NSg.jpeg</url>
            <title>Stories by Dylan Kaufman on Medium</title>
            <link>https://medium.com/@dylan.kaufman?source=rss-1a3818055dd2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:14:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dylan.kaufman/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[Counting Weekdays (Snowflake Tidbit of the Day)]]></title>
            <link>https://medium.com/snowflake/counting-weekdays-snowflake-tidbit-of-the-day-c6eb30f847c1?source=rss-1a3818055dd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6eb30f847c1</guid>
            <dc:creator><![CDATA[Dylan Kaufman]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 14:01:48 GMT</pubDate>
            <atom:updated>2025-06-30T04:23:18.575Z</atom:updated>
            <content:encoded><![CDATA[<h3>Snowbit of the Day: Counting Weekdays</h3><p>No Date Dimension Required</p><p>I came across a post in the Snowflake Community today that asked about how to count the number of weekdays in a random date range. The first response someone gave was that a date dim was required. I <a href="https://medium.com/snowflake/create-a-mini-time-dimension-on-the-fly-with-a-snowflake-udtf-e2fd3a3a61e9">wrote about an on-the-fly date dimension</a> with a UDTF a while back, which would help with that method if one wanted to go that way.</p><p>The rest of that first response basically follows that idea: use GENERATOR to produce a number of rows and add each row number to the start date and you have a list of the dates, which you can then analyze. The problem in that example was that you have to provide the number of rows you want from GENERATOR as a constant. If you set it to 1000, someone will try 2 June 2025 to 29 Feb 2028 (1003 days). Of course, you can set it to a million. That will cover all the way to April 30, 4763. So, probably plenty, but <strong><em>overkill</em></strong> is not my favorite way to handle things.</p><p>Another response did something complicated with the basic math (each 7-day week has 2 weekend days in it) and a CASE statement. I assume it works and it doesn’t need the GENERATOR function, but I didn’t actually take the time to understand exactly what it was doing.</p><p>I thought it would be nice to go with a cross between the two:</p><pre>SELECT<br>  TO_DATE(&#39;2025-06-01&#39;)                         start_date, <br>  TO_DATE(&#39;2025-06-07&#39;)                         end_date,<br>  DATEDIFF(day, start_date, end_date) + 1       total_days,<br>  -- count week days in the incremental partial week, if any<br>  SUM(CASE WHEN MOD(TOTAL_DAYS,7) != 0 AND<br>                DAYOFWEEKISO(                   <br>                        DATEADD(day, <br>                                gen.i - 1, <br>                                start_date)) <br>                    BETWEEN 1 AND 5<br>             THEN 1<br>             ELSE 0 END)                        extra_week_days,<br>  -- the week days in the final partial week <br>  -- + 5 week days per full week <br>  -- = total week days in the period<br>  extra_week_days + (FLOOR(total_days / 7) * 5) total_week_days,<br>  total_days - total_week_days                  total_weekend_days<br>FROM (SELECT ROW_NUMBER() OVER (ORDER BY SEQ4()) AS i<br>      FROM TABLE(GENERATOR(ROWCOUNT =&gt; 6))) gen -- generate 6 rows, the max for a partial week<br>WHERE gen.i BETWEEN 0 AND MOD(total_days, 7) OR -- always return the first day so we have a row<br>                                                -- plus however many other extra days there are<br>                                                -- after the first<br>      MOD(total_days,7) = 0                     -- and if it&#39;s a full week, return one day per week <br>GROUP BY ALL<br>;</pre><p>I like this because it has a fixed generator row count, regardless of what date inputs the user may choose, and it doesn’t have anywhere near as complex a CASE statement.</p><p>Any of these three methods could be turned into a user-defined function pretty easily.</p><p><em>Edit: </em>thanks to a couple of sharp-eyed readers, I’ve corrected the generator to make sure that the sequence consists of consecutive numbers — SEQ4 doesn’t guarantee those — and I’ve revised the logic a bit to both count correctly when the period starts on a weekend.</p><ol><li>Originally, I used SELECT SEQ4() AS i, as I have found that SEQ4 has always returned gapless sequences, but the <em>correct</em> way to do that is to use SEQ4 to provide the rows and ROW_NUMBER to ensure the sequence has no gaps. That’s even described in the <a href="https://docs.snowflake.com/en/sql-reference/functions/seq1#examples">examples</a> in the SEQ4 docs, but once you’re doing a ROW_NUMBER, it isn’t actually necessary to use SEQ4 — the generator provides the rows, and even ROW_NUMBER() OVER (ORDER BY 1) will do the trick.</li><li>Another reader pointed out that DATEADD(day, gen.i, start_date)) was not counting correctly; basically, it was shifting the start date by a day, which meant I’d have been counting either weekdays or weekend days wrong, depending on what day of the week the start date was, and how long the period. Changing that to DATEADD(day, gen.i — 1, start_date)) avoids that.</li><li>I also had to add extra checks to handle time periods that are even numbers of full weeks. You can see those in the CASE statement, where I ensure it always returns 0 days if the period is a multiple of 7 days, and in the filter, when I have a similar check to make sure we get a row in that situation as well.</li></ol><p>Here is the original code, if you’re curious:</p><pre>SELECT<br>  TO_DATE(&#39;2025-06-01&#39;)                         start_date, <br>  TO_DATE(&#39;2028-02-28&#39;)                         end_date,<br>  DATEDIFF(day, start_date, end_date) + 1       total_days,<br>  -- count week days in the last partial week<br>  SUM(CASE WHEN DAYOFWEEKISO(<br>                        DATEADD(day, <br>                                gen.i, <br>                                start_date)) <br>                    BETWEEN 1 AND 5<br>             THEN 1<br>             ELSE 0 END)                        extra_week_days,<br>  -- the week days in the final partial week <br>  -- + 5 week days per full week <br>  -- = total week days in the period<br>  extra_week_days + (FLOOR(total_days / 7) * 5) total_week_days,<br>  total_days - total_week_days                  total_weekend_days<br>FROM (SELECT SEQ4() AS i<br>      FROM TABLE(GENERATOR(ROWCOUNT =&gt; 6))) gen -- generate 6 rows, the max for a partial week<br>WHERE gen.i BETWEEN 0 AND MOD(total_days, 7)    -- always return the first day so we have a row<br>                                                -- plus however many other extra days there are<br>                                                -- after the first<br>GROUP BY ALL<br>;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6eb30f847c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/counting-weekdays-snowflake-tidbit-of-the-day-c6eb30f847c1">Counting Weekdays (Snowflake Tidbit of the Day)</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowbit of The Day: Changing a Snowflake Sequence’s Next Value]]></title>
            <link>https://medium.com/snowflake/changing-a-snowflake-sequences-next-value-snowflake-tidbit-of-the-day-325696227897?source=rss-1a3818055dd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/325696227897</guid>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Dylan Kaufman]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 20:07:50 GMT</pubDate>
            <atom:updated>2025-06-30T04:31:53.624Z</atom:updated>
            <content:encoded><![CDATA[<p>Snowflake Sequences can’t be altered directly to adjust their sequence number…</p><p>In migrating existing data from SQL Server tables with IDENTITY columns to Snowflake tables, we have to replace the IDENTITY columns with DEFAULTs set to SEQUENCES.</p><p>So, instead of this:</p><pre>CREATE TABLE TEST_TABLE (<br>  ID INT IDENTITY,<br>  &lt;other columns&gt;<br>)</pre><p>we use this:</p><pre>CREATE SEQUENCE TEST_TABLE_SEQ START WITH 1 INCREMENT BY 1 ORDER;<br>CREATE TABLE TEST_TABLE (<br>  ID INT DEFAULT TEST_TABLE_SEQ.NEXTVAL,<br>  &lt;other columns&gt;<br>);</pre><p>It took me a bit to realize (aka figure out) that since the ID column in Snowflake now has a DEFAULT value, we can actually insert the data from the SQL Server, including the ID values, and it will be perfectly happy with that.</p><p>Naturally, at that point we will have ID values that are far higher than 1, and if we just start adding new rows and letting the default take effect, we will get duplicates.</p><p>To avoid that, we have to find a way to advance the sequence to where we want it to be — the number after the max ID in the target table.</p><p>Sadly, we can’t directly ALTER the sequence to change the next value, as we could with some other SQL databases, something like ALTER SEQUENCE TEST_TABLE_SEQ START WITH 316;</p><p>My first try was to use an anonymous stored proc to get the next value in a loop until the next value is the desired value:</p><pre>EXECUTE IMMEDIATE $$<br>DECLARE<br>    max_id_cur CURSOR FOR SELECT COALESCE(MAX(ID), 0) MAX_ID FROM TEST_TABLE;<br>    max_id INT;<br>    cur_id INT DEFAULT 0;<br>BEGIN<br>    OPEN max_id_cur;<br>    FETCH max_id_cur INTO max_id;<br>    CLOSE max_id_cur;<br>   <br>    WHILE (cur_id &lt; max_id) DO<br>        LET r1 RESULTSET := (SELECT TEST_TABLE_SEQ.NEXTVAL NV);<br>        LET c1 CURSOR FOR r1;<br>        OPEN c1;<br>        FETCH c1 INTO cur_id;<br>        CLOSE c1;<br>    END WHILE;<br><br>    RETURN cur_id;<br>END;<br>$$;</pre><p>This works fine, in that it gets the job done. It does, however, take a while. Even for only a few thousand rows it can take several minutes. Be sure to run it on an XS, since it’s single threaded.</p><p>I assume the biggest problem is that it is opening and closing the cursor repeatedly. I tried only opening the cursor before the loop, and closing it after, but that didn’t work. I might just not have figured out the syntax, but I initially decided just to accept the delay, since it doesn’t actually cost very much and it only really needs to be run a few times during testing and, ideally, only once when we move to production.</p><p>At some point, I realized that we have some tables that have IDENTITY columns and millions of rows. I’m not as keen to accept the delay on those tables, so I started looking for another solution.</p><p>What I figured out is that even though I can’t add a SEQUENCE as the default on a column that doesn’t have a default already, I can change an existing default, so that’s what I’m now doing:</p><pre>CREATE SEQUENCE TEST_TABLE_SEQ START WITH 1 INCREMENT BY 1 ORDER;<br>CREATE TABLE TEST_TABLE (<br>    id INT DEFAULT TEST_TABLE_SEQ.NEXTVAL,<br>    val INT<br>)<br>;<br><br>INSERT INTO TEST_TABLE (val) VALUES (1);<br>INSERT INTO TEST_TABLE VALUES (5, 50);<br>SELECT * FROM TEST_TABLE; -- returns 2 rows: 1/1, 5/50<br><br>-- replace the existing sequence with one that starts at 6<br>CREATE OR REPLACE SEQUENCE TEST_TABLE_SEQ START WITH 6 INCREMENT BY 1 ORDER;<br>INSERT INTO TEST_TABLE (val) VALUES (6); -- failed: Sequence used as a default value in table &#39;SANDBOX.PUBLIC.TEST_TABLE&#39; column &#39;ID&#39; was not found or could not be accessed.<br><br>-- alter the column to use the &#39;new&#39; sequence<br>ALTER TABLE TEST_TABLE ALTER COLUMN ID DEFAULT TEST_TABLE_SEQ.NEXTVAL;<br><br>INSERT INTO TEST_TABLE (val) VALUES (6);<br>SELECT * FROM TEST_TABLE; -- returns 3 rows: 1/1, 5/50, 6/6</pre><p>Since I have several tables that need this, I decided I’d rather have a stored proc to do it than copy and paste the 2 lines and plug in the right names and number, so I created one.</p><pre>CREATE OR REPLACE PROCEDURE change_sequence_value(<br>    table_name STRING,     -- Target table name<br>    col_name STRING,       -- Column to modify<br>    start_number INT       -- Starting value for the sequence<br>)<br>RETURNS STRING<br>LANGUAGE SQL<br>AS<br>$$<br>DECLARE <br>    seq_name STRING;<br>BEGIN<br>    -- Construct the sequence name<br>    seq_name := table_name || &#39;_Seq&#39;;<br><br>    -- Step 1: Create the sequence dynamically<br>    EXECUTE IMMEDIATE <br>        &#39;CREATE OR REPLACE SEQUENCE &#39; || seq_name || <br>        &#39; START WITH &#39; || start_number || &#39; INCREMENT BY 1 ORDER&#39;;<br><br>    -- Step 2: Alter the column to use the sequence for default values<br>    EXECUTE IMMEDIATE <br>        &#39;ALTER TABLE &#39; || table_name || <br>        &#39; ALTER COLUMN &#39; || col_name || <br>        &#39; SET DEFAULT &#39; || seq_name || &#39;.NEXTVAL&#39;;<br><br>    RETURN &#39;Sequence &#39; || seq_name || &#39; created and assigned to &#39; || table_name || &#39;.&#39; || col_name;<br>END;<br>$$;</pre><p>I toyed with making it look up the current max value, but don’t really feel like spending more time on this right now.</p><p>Now I just add this call after loading the legacy data into the new DW table:</p><pre>CALL change_sequence_value(&#39;TEST_TABLE&#39;, &#39;ID&#39;, (SELECT MAX(ID) + 1 FROM TEST_TABLE));</pre><p>Admittedly, I’m still putting the table name and column name in two places, as with the CREATE/ALTER sequence above, but this feels ‘better’ to me.</p><p>Anyone want to take a stab at getting the SP to pick up the max value itself? Oh, and one could also make sure that it will work even if there isn’t actually anything in the target table yet — hint: COALESCE.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=325696227897" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/changing-a-snowflake-sequences-next-value-snowflake-tidbit-of-the-day-325696227897">Snowbit of The Day: Changing a Snowflake Sequence’s Next Value</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matching Trino’s Array Functions in Snowflake]]></title>
            <link>https://medium.com/snowflake/matching-trinos-array-functions-in-snowflake-9b30a126573f?source=rss-1a3818055dd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b30a126573f</guid>
            <dc:creator><![CDATA[Dylan Kaufman]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 15:22:01 GMT</pubDate>
            <atom:updated>2024-11-10T15:22:01.486Z</atom:updated>
            <content:encoded><![CDATA[<p>Trino has a whole bunch of very capable array functions, some of which aren’t available directly in Snowflake, so…</p><p>A customer of mine does a lot of work in Athena, and is having some trouble moving their work into Snowflake directly because they use a LOT of Trino’s array functions. Some of those array functions aren’t directly available in Snowflake, so it’s been a lot of work to try to sort out how to bring all that work over.</p><p>I’ve been going through all the array functions mentioned in Trino’s <a href="https://trino.io/docs/current/functions/array.html">documentation</a> to make a map of their functions to ours, which come out in a few ways:</p><ul><li>identical, or very nearly identical — these are functions that match precisely or perhaps have a slightly different name or arguments in a different order</li><li>easily matched — these are situations where we don’t have a single function that does what the Trino function does, but we can stack two or more Snowflake functions to match</li><li>custom — these are functions that basically require a custom, user-defined function in Snowflake because we don’t have anything that can do what Trino’s function does</li><li>Snowflake-only — these are functions Snowflake has that don’t seem to have direct alternatives in Trino; please note that I’m not trying to match all of ours to Trino, so there may be “easily matched” versions on the Trino side in these cases</li></ul><p>As I have worked my way through these, I’ve tried to match the input and output of the Trino doc examples as much as I can. There are some notable differences:</p><ul><li>we don’t require describing an array using ARRAY[]; just using square brackets is sufficient</li><li>in at least one example, they just used a column name, not a sample array, while for other functions they didn’t provide an example at all</li><li>we don’t have a ROW object, so for those I would either return arrays or JSON objects</li></ul><p>Also, please note that throughout the examples below, if there are two or more array arguments, the likelihood is that in real life those will actually be references to columns, not hard-coded arrays.</p><h3>Indentical Functions (or very nearly so)</h3><p>There are a number of functions that we support that are identical or very nearly identical to their Trino counterparts. Let’s start by listing those Trino functions, with very short notes about what’s different, if anything:</p><ul><li><strong><em>Subscript Operator []: </em></strong>this is the same, except we index from 0, rather than 1, so [2, 3, 4, 5, 6][1] returns 2 in Trino and 3 in Snowflake.</li><li><strong><em>ARRAY_DISTINCT</em></strong></li><li><strong><em>ARRAY_INTERSECT:</em></strong> this differs slightly in the name — Snowflake calls it ARRAY_INTERSECTION</li><li><strong><em>ARRAY_MAX</em></strong></li><li><strong><em>ARRAY_MIN</em></strong></li><li><strong><em>ARRAY_POSITION:</em></strong> this is essentially the same, except for our indexing from 0, and having the ‘position to return’ argument first instead of second, so we would use ARRAY_POSITION(1, [2, 3, 4]) to return 3 where Trino’s version would use position 2 to get 3 as the result: ARRAY_POSITION([2, 3, 4], 2)</li><li><strong><em>ARRAY_REMOVE</em></strong></li><li><strong><em>CARDINALITY: </em></strong>identical except for the name — Snowflake calls it ARRAY_SIZE</li><li><strong><em>CONTAINS:</em></strong> Snowflake’s function is ARRAY_CONTAINS, and the arguments are swapped (value to search for first in Snowflake).</li><li><strong><em>FILTER</em></strong></li><li><strong><em>FLATTEN:</em></strong> Snowflake calls this ARRAY_FLATTEN to distinguish it from the <a href="https://docs.snowflake.com/en/sql-reference/functions/flatten">FLATTEN</a> table function</li><li><strong><em>REDUCE:</em></strong> Snowflake has recently released a REDUCE function that is very similar to Trino’s, though it doesn’t provide a separate lambda function to apply a final calculation before returning the output.</li><li><strong><em>SEQUENCE: </em></strong>Snowflake provides a function called ARRAY_GENERATE_RANGE which will return an array containing a sequence of numbers from a start to stop, incremented by some step value; Trino also supports doing this with DATE and TIMESTAMP types, which we can do either using ARRAY_GENERATE_RANGE and TRANSFORM, or with a custom UDF, which I’ll discuss later on.</li><li><strong><em>TRANSFORM: </em></strong>identical except that it may be necessary to do typecasts in the transformer lambda function to get the desired data type</li></ul><h3>Easily Matched Functions</h3><p>There are a number of functions we don’t support as individual functions in quite the same way as Trino does, but we can duplicate a lot of these either with a different function, or by stacking some functions.</p><p><strong><em>Concatenation Operator ||:</em></strong></p><p>We don’t support || as the concatenation operator for arrays, though we do for strings. I hope to get that changed, but in the meantime, we certainly do support concatenation via the ARRAY_CAT function. Trino’s || version is a little different in that you can prepend or append values into an array using the concatenation operator OR you can concatenate two arrays.</p><p>In Snowflake, we’d do that with 3 different functions; all of these 3 functions return the same array: [1, 2].</p><pre>SELECT ARRAY_PREPEND(1, [2]), -- &#39;concatenate&#39; a number at the start of an array<br><br>       ARRAY_CAT([1], [2]),   -- concatenate two arrays<br><br>       ARRAY_APPEND([1], 2);  -- &#39;concatenate&#39; a number at the end of an array</pre><p><strong><em>ALL_MATCH function:</em></strong></p><p>The ALL_MATCH function returns true if all of the values in the array match a predicate function, such as ‘x &gt; 0’. We don’t have a function for this directly, but we can stack a couple of functions to get the same result.</p><pre>SELECT ARRAY_DISTINCT(TRANSFORM([1, 2, 3], x -&gt; x &gt; 0))[0] AND ARRAY_SIZE(ARRAY_DISTINCT(TRANSFORM([1, 2, 3], x -&gt; x &gt; 0))) = 1, -- true<br><br>       ARRAY_DISTINCT(TRANSFORM([1, -2, 3], x -&gt; x &gt; 0))[0] AND ARRAY_SIZE(ARRAY_DISTINCT(TRANSFORM([1, -2, 3], x -&gt; x &gt; 0))) = 1 -- false<br>;</pre><p>In this case, I’m using our TRANSFORM function which will run the predicate function x &gt; 0 against each value in the array, returning an array of true/false values instead. Running ARRAY_DISTINCT on that will necessarily get us down to 1 or 2 elements in the array, so then we can check whether the first is true and whether there is only one. Another way to do it is with ARRAY_SORT , which eliminates the need to run the ARRAY_DISTINCT / TRANSFORMpair twice:</p><pre>SELECT ARRAY_SORT(TRANSFORM([1, 2, 3], x -&gt; x &gt; 0))[0], -- true<br><br>       ARRAY_SORT(TRANSFORM([-1, -2, -3], x -&gt; x &gt; 0))[0], -- false<br><br>       ARRAY_SORT(TRANSFORM([1, null, -2, null], x -&gt; x &gt; 0))[0] -- false<br>;</pre><p>The one thing I haven’t matched here is the Trino doc’s comment that a predicate function that returns null causes a null result. I’d need to come up with an input array and a predicate function that returned null for one or more values, and I haven’t done that yet. I could imagine using ARRAY_CONTAINS on the TRANSFORM result to see if any of the values are null; that would, again, require running TRANSFORM twice, but it may be easier and/or more efficient than using a UDF.</p><p>Another idea comes from what I did for <em>none_match</em>, below, which is using our FILTER function:</p><pre>SELECT ARRAY_SIZE(FILTER([1, 2, 3], x -&gt; x &gt; 0)) = ARRAY_SIZE([1, 2, 3]), -- true <br><br>       ARRAY_SIZE(FILTER([1, -2, 3], x -&gt; x &gt; 0)) = ARRAY_SIZE([1, 2, 3]); -- false</pre><p>It might be interesting to see how the performance of these various options compares… on small arrays and small result sets it obviously won’t matter, but the larger the arrays and the more rows these are being done to, it could.</p><p>You’ll see these themes recur with a number of the other functions.</p><p><strong><em>ANY_MATCH and NONE_MATCH functions:</em></strong></p><p>OK, I decided not to do them all in the same order they’re in the Trino doc. These two are essentially alternatives to ALL_MATCH , so it makes more sense to put them together with that one.</p><p>If we break ALL_MATCH down to ‘filters to an array the same size as the original’, or ‘only has true in the transform result’, then the logic for ANY_MATCH comes down to ‘doesn’t filter to an empty array’ and NONE_MATCH comes to ‘filters to an empty array’:</p><pre>SELECT ARRAY_SIZE(FILTER([-1, 2, -3], x -&gt; x &gt; 0)) &gt; 0, -- true (any match)<br><br>       ARRAY_SIZE(FILTER([-1, -2, -3], x -&gt; x &gt; 0)) = 0; -- true (none match)</pre><p>or</p><pre>SELECT FILTER([-1, 2, -3], x -&gt; x &gt; 0) != [], -- true (any match)<br><br>       FILTER([-1, -2, -3], x -&gt; x &gt; 0) = []; -- true (none match)</pre><p><strong><em>ARRAY_UNION and ARRAY_EXCEPT functions:</em></strong></p><p>Trino’s ARRAY_UNION function concatenates two arrays and then, unlike the ARRAY_CAT function, removes any duplicates. We can duplicate that by adding a call to ARRAY_DISTINCT:</p><pre>SELECT ARRAY_DISTINCT(ARRAY_CAT([1, 2, 3], [2, 3, 4])); --&gt; [1, 2, 3, 4]</pre><p>Similarly, Snowflake’s ARRAY_EXCEPT function is the same as Trino’s, except for the deduplication, so, again, we just add a call to ARRAY_DISTINCT:</p><pre>SELECT ARRAY_DISTINCT(ARRAY_EXCEPT([1, 1, 2, 3], [2, 3, 4])); --&gt; [1]</pre><p><strong><em>ARRAY_JOIN function:</em></strong></p><p>Trino’s ARRAY_JOIN function converts an array into a string, separating the values with a provided delimiter, and eliminating NULL values. This is almost identical to Snowflake’s ARRAY_TO_STRING function, except for the NULL elimination.</p><p>To emulate the NULL handling, we can put in a REPLACE call to replace any double delimiters with a single delimiter:</p><pre>SELECT REPLACE(ARRAY_TO_STRING([1, 2, NULL, 3], &#39;,&#39;), &#39;,,&#39;, &#39;,&#39;); --&gt; 1,2,3</pre><p>Another option is to use Snowflake’s ARRAY_COMPACT function to get rid of the null values first:</p><pre>SELECT ARRAY_TO_STRING(ARRAY_COMPACT([1, 2, NULL, 3]), &#39;,&#39;);</pre><p>It is worth noting for completeness that you might have to do the replace twice, or use REGEXP_REPLACE, if there can be more than one consecutive NULL value in the input array, like so:</p><pre>SELECT REGEXP_REPLACE(ARRAY_TO_STRING([1, 2, NULL, NULL, NULL, 3], &#39;,&#39;), &#39;,,+&#39;, &#39;,&#39;); --&gt; 1,2,3</pre><p>Trino also provides an overloaded version of ARRAY_JOIN with a third argument that can be used to replace any null values, which is essentially what our replacement is doing, so if we want, we can insert an alternate value instead of dropping the blank:</p><pre>SELECT REPLACE(ARRAY_TO_STRING([1, 2, NULL, 3], &#39;,&#39;), &#39;,,&#39;, &#39;,500,&#39;); --&gt; 1,2,500,3</pre><p>We could probably use the TRANSFORM function to do this replacement in the array, prior to generating the string, which would eliminate the need for the REPLACE call (not to say ‘replace it’). I’ll leave that as exercises for interested readers.</p><p><strong><em>ARRAY_SORT function:</em></strong></p><p>Trino’s ARRAY_SORT function comes in two flavors, one which does a simple ascending sort with NULLs at the end and one which adds a lambda function that can define the order.</p><p>Snowflake’s version is essentially identical in that without other parameters it will do a simple ascending with NULLs at the end, and displayed as ‘undefined’. Snowflake, however, also provides for up to two boolean parameters to indicate whether to sort ascending (TRUE = ascending) and one for whether NULLs should be at the beginning or end of the result (TRUE = at the front).</p><pre>SELECT ARRAY_SORT([3, 1, NULL, 2, 4]); --&gt; [1, 2, 3, 4, undefined]<br><br>SELECT ARRAY_SORT([3, 1, 2, 4], FALSE); --&gt; [4, 3, 2, 1]<br><br>SELECT ARRAY_SORT([3, 1, 2, NULL, 4], TRUE, TRUE); --&gt; [undefined, 1, 2, 3, 4]</pre><p>One thing that is nice about the Trino version with the comparator function is that it allows doing essentially any kind of sort… you could sort an array by the length of the strings it contains, for example. In Snowflake, at present, we would have to write a custom user-defined function. There are some UDF versions of functions coming up below, so I’ll leave this one as another exercise.</p><p>Here are several other examples comparing the ARRAY_SORT function in Snowflake to Trino:</p><pre>SELECT array_sort([3, 2, 5, 1, 2],<br>                  FALSE);<br>-- [5, 3, 2, 2, 1]<br><br>SELECT array_sort([&#39;bc&#39;, &#39;ab&#39;, &#39;dc&#39;],<br>                  FALSE);<br>-- [&#39;dc&#39;, &#39;bc&#39;, &#39;ab&#39;]<br><br>SELECT array_sort([3, 2, null, 5, null, 1, 2],<br>                  FALSE, TRUE);<br>-- [null, null, 5, 3, 2, 2, 1] (but nulls come as &#39;undefined&#39;)<br><br>SELECT array_sort([3, 2, null, 5, null, 1, 2],<br>                  FALSE, FALSE);<br>-- [5, 3, 2, 2, 1, null, null]</pre><p><strong><em>ARRAYS_OVERLAP function:</em></strong></p><p>Trino’s ARRAYS_OVERLAP function returns NULL if either array contains NULL, while Snowflake’s actually treats them as a point of overlap. That does, I admit, feel a little strange considering that in most languages, NULL != NULL.</p><pre>SELECT ARRAYS_OVERLAP([1, 3, 4, NULL], [2]); -- FALSE (does not return NULL in the special case described)<br><br>SELECT ARRAYS_OVERLAP([1, 2, 3], [3, 4, 5]); -- TRUE<br><br>SELECT ARRAYS_OVERLAP([1, 2, 3], [4, 5, 6]); -- FALSE<br><br>SELECT ARRAYS_OVERLAP([1, 3, 4, NULL], [2, NULL]); -- TRUE - sees NULLs as overlapping</pre><p>We can mimic the NULL behavior using a CASE statement to test the two input arrays for NULL with ARRAY_CONTAINS:</p><pre>SELECT CASE WHEN ARRAY_CONTAINS(NULL, [1, 3, 4, NULL]) OR<br>                 ARRAY_CONTAINS(NULL, [2]) <br>            THEN NULL<br>            ELSE ARRAYS_OVERLAP([1, 3, 4, NULL], [2]) END;</pre><p><strong><em>CONCAT function:</em></strong></p><p>The CONCAT function in Trino is essentially the same as the ARRAY_CAT function in Snowflake, except that Trino will accept more than two arrays to concatenate. Since Snowflake only accepts two, one would have to call ARRAY_CAT multiple times:</p><pre>SELECT ARRAY_CAT([1, 2], [3, 4]); --&gt; [1, 2, 3, 4]<br><br>SELECT ARRAY_CAT(ARRAY_CAT([1, 2], [3, 4]), [4, 5, 6]); --&gt; [1, 2, 3, 4, 4, 5, 6]<br><br>SELECT ARRAY_CAT([1, 2], [3, 4], [4, 5, 6]); --&gt; error</pre><p><strong><em>ELEMENT_AT function:</em></strong></p><p>Trino’s ELEMENT_AT function is conceptually the same as using the [] operator in Snowflake, but it has a couple of different behaviors. First, searching for an element number that doesn’t exist generates an error in Snowflake but the Trino function returns NULL. Second, using a negative number in the function will start the search at the end of the array:</p><pre>SELECT [1, 2, 3][1]; -- 2<br><br>SELECT [1, 2, 3][9]; -- error<br><br>SELECT [1, 2, 3][-1]; -- error in Snowflake, but Trino function would return 3</pre><p>In order to mirror the Trino function’s behavior exactly, I think a custom UDF would be required.</p><p><strong><em>SLICE function:</em></strong></p><p>Snowflake’s ARRAY_SLICE function is essentially the same as SLICE in Trino, but where Trino starts at the ‘from’ position and returns a number of elements, Snowflake starts at the ‘from’ position and stops immediately before the ‘to’ position. As usual in Snowflake, the array starts with position 0, not 1.</p><pre>SELECT ARRAY_SLICE([1, 2, 3, 4, 5, 6], 2, 4); --&gt; [3, 4]</pre><p><strong><em>ZIP function:</em></strong></p><p>Trino’s ZIP function takes two arrays of objects and returns a single array of ROW objects where each ROW contains two values, which are the two values at that point in the arrays. If one array is shorter than the other, Trino will add NULL values to the end to make them the same length.</p><p>Snowflake’s ARRAYS_ZIP function takes any number of arrays and returns an array of JSON objects containing a key value pair for each of the elements at any position in the array.</p><p>In Trino, SELECT ZIP(ARRAY[1, 2], ARRAY[‘1b’, null, ‘3b’]); would return [ROW(1, ‘1b’), ROW(2, null), ROW(null, ‘3b’)], while Snowflake’s ARRAYS_ZIP function returns an array of json objects:</p><pre>SELECT ARRAYS_ZIP([1, 2], [&#39;1b&#39;, null, &#39;3b&#39;]);<br>[<br>  {<br>    &quot;$1&quot;: 1,<br>    &quot;$2&quot;: &quot;1b&quot;<br>  },<br>  {<br>    &quot;$1&quot;: 2,<br>    &quot;$2&quot;: null<br>  },<br>  {<br>    &quot;$1&quot;: null,<br>    &quot;$2&quot;: &quot;3b&quot;<br>  }<br>]</pre><p>I assume that the ROW output can be dereferenced, just as an array of JSON objects can.</p><p><strong><em>ZIP_WITH function:</em></strong></p><p>Trino’s ZIP_WITH function is another that allows for a lambda function to tell it what to do when zipping two arrays, essentially allowing the output to be adjusted. For example, you could add the values in the two arrays, or swap them, etc. In Snowflake, we can do the same by applying a TRANSFORM function to the output of ARRAYS_ZIP. Following are three simple examples:</p><pre>SELECT TRANSFORM(<br>                    ARRAYS_ZIP([1, 3, 5], [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]),<br>                    x -&gt; OBJECT_CONSTRUCT(&#39;$1&#39;, x:$2, &#39;$2&#39;, x:$1)<br>                );<br>-- returns the objects as ARRAYS_ZIP would, but swapping the values between the respective keys<br><br>SELECT TRANSFORM(<br>                    ARRAYS_ZIP([1, 2], [3, 4]),<br>                    x -&gt; x:&quot;$1&quot;::INT + x:&quot;$2&quot;::INT<br>                );<br>-- adds the two values together: [4, 6]<br><br>SELECT TRANSFORM(<br>                    ARRAYS_ZIP([&#39;a&#39;, &#39;b&#39;, &#39;c&#39;], [&#39;d&#39;, &#39;e&#39;, &#39;f&#39;]),<br>                    x -&gt; x:$1 || x:$2<br>                );<br>-- concatenates the strings: [&#39;ad&#39;, &#39;be&#39;, &#39;cf&#39;]</pre><h3>Other Functions Snowflake Supports</h3><p>There are a number of functions Snowflake supports that aren’t directly available in Trino’s ARRAY function list:</p><ul><li>ARRAY_COMPACT: removes empty &amp; null values from an array</li><li>ARRAY_CONSTRUCT: given a bunch of values, returns an array</li><li>ARRAY_CONSTRUCT_COMPACT: assembles an array, leaving out null values</li><li>ARRAY_REMOVE_AT: removes an element at a specific position in an array, returning an array with one fewer value</li><li>ARRAYS_TO_OBJECT: given two arrays, using one for keys and one for values, creates an object containing all of the resulting k-v pairs</li></ul><p>Note that I’ve left out Snowflake’s array aggregation functions: ARRAY_AGG, ARRAY_UNION_AGG, and ARRAY_UNIQUE_AGG. Those behave somewhat differently, so I decided not to cover them here.</p><h3>Functions Requiring UDFs</h3><p>There are a number of Trino functions that are somewhat more complex and can’t be replicated strictly by using a combination of other built-in functions. Some of these support input functions, similar to the TRANSFORM function, but require more logic than TRANSFORM can handle. Others have specific code to them, and aren’t directly supported by Snowflake yet.</p><p><strong><em>REDUCE</em></strong></p><blockquote>Breaking News: While I’ve been working on this article, Snowflake has introduced <em>REDUCE</em> as a built-in higher-order function, as described here: <a href="https://docs.snowflake.com/en/sql-reference/functions/reduce">https://docs.snowflake.com/en/sql-reference/functions/reduce</a>. The Snowflake version is a little different, in that it applies the result of the calculation done to each input value directly to the accumulator and then returns the accumulator when finished, where Trino’s version allows adding a separate calculation to be done to the accumulator value before returning it. I am including the already written segment onREDUCE below both as an example of a UDF, and in case you want to use a UDF to better mimic Trino’s version.</blockquote><p>The first UDF I worked on was REDUCE, which applies logic to each element of the array, tracking an on-going result, and then applying another function to that before returning a final result.</p><p>Here are two relatively simple examples from the Trino doc:</p><pre>SELECT reduce(ARRAY[5, 20, NULL, 50], 0,<br>              (s, x) -&gt; s + coalesce(x, 0),<br>              s -&gt; s);<br>-- 75 (sum of the values)<br><br>SELECT reduce(ARRAY[5, 6, 10, 20],<br>              CAST(ROW(0.0, 0) AS ROW(sum DOUBLE, count INTEGER)),<br>              (s, x) -&gt; CAST(ROW(x + s.sum, s.count + 1) AS<br>                             ROW(sum DOUBLE, count INTEGER)),<br>              s -&gt; IF(s.count = 0, NULL, s.sum / s.count));<br>-- 10.25 (sum up &amp; count the values, then compute the average)</pre><p>In both cases, we pass in an array, a starting value, an ‘input function’, and an ‘output function’. The input function is passed two arguments, s &amp; x, where s is the starting value (when processing the first element) and the output of the input function for every other element and x is the value of the current element. Once the REDUCE function has stepped through all of the elements of the array, it passes the final value of s to the output function, which can either just return the value or do some additional logic.</p><p>In order to duplicate this, I created a user-defined function (UDF) in Python as shown below. The UDF is defined as using Python 3.10 and calling a handler function main, after being given an input array, an initial_value, reducer_py lambda function text, andoutput_py lambda function text. Note that because this is a UDF, the two functions are <em>strings</em>, where in Trino they are just expressions.</p><pre>CREATE OR REPLACE FUNCTION REDUCE_PY(array ARRAY, initial_value VARIANT, reducer_py STRING, output_py STRING)<br>RETURNS VARIANT<br>LANGUAGE PYTHON<br>RUNTIME_VERSION = 3.10<br>HANDLER = &#39;main&#39;<br>AS<br>$$<br>def reducer(s, x, reducer_py):<br>    print(&#39;--- reducer ---&#39;)<br>    scope = {&#39;s&#39;:s, &#39;x&#39;:x}<br>    exec(reducer_py, globals(), scope)<br>    return scope[&#39;s&#39;]<br><br># Define the output function<br>def output(s, output_py):<br>    print(&#39;--- output ---&#39;)<br>    scope = {&#39;s&#39;:s}<br>    if output_py:<br>        exec(output_py, globals(), scope)<br>        s = scope[&#39;s&#39;]<br>    return s<br><br>def main(array, initial_value, reducer_py, output_py): <br>    accumulator = initial_value<br>    for value in array:<br>        print(f&#39;  value: {value}, accumulator: {accumulator}&#39;)<br>        accumulator = reducer(accumulator, value, reducer_py)<br>    <br>    # Apply the output function to the final result<br>    return output(accumulator, output_py)<br>$$;</pre><p>Given the proper set of inputs, the main function initializes the accumulator variable to the initial_value given and then proceeds to step through all the elements in the array. For each of those elements, it calls the reducer function, passing in the current value of the accumulator, the new element value, and the reducer function text. It updates the accumulator value with the output of the reducer function so that value will be used on the next call to reducer, and, when finished with all the elements, passes that final result on to the output function.</p><p>Both of the functions called by main create a scope object that will be used by the Python string lambda function in question. The first example from Trino looks quite similar — we pass in the ARRAY of 4 values, a starting value of 0, and two strings. The first is simply a tiny Python script to replace NULL values with 0 and then add the resulting value to another value (s += &lt;something&gt;), while the second is even simpler still: s just returns the final value. This is essentially the logic “add up all the values in the array”.</p><pre>SELECT reduce_py([5, 20, NULL, 50], 0,<br>              &#39;s += (x if x is not None else 0)&#39;,<br>              &#39;s&#39;) SUM_OF_ELEMENTS;<br>-- 75</pre><p>A second example is of generating an average of the values in the array. This one is a bit more interesting: the initial value is an object containing two zero values, a sum and a count. The reducer function pulls the object apart to get the sum and count so far, adds the new element to the sum and adds one to the count. Finally, the output function returns None (NULL) if the count is 0 for an empty array, or else pulls the two values out of the object and divides the count into the sum to get and return the average.</p><pre>SELECT reduce_py([5, 6, 10, 20],<br>              {&#39;sum&#39;:0.0, &#39;count&#39;: 0},<br>              &#39;s = {\&#39;sum\&#39;: s[\&#39;sum\&#39;] + x, \&#39;count\&#39;: s[\&#39;count\&#39;] + 1}&#39;,<br>              &#39;s = None if s[\&#39;count\&#39;] == 0 else s[\&#39;sum\&#39;]/s[\&#39;count\&#39;]&#39;) AVG_OF_ELEMENTS;<br>-- 10.25</pre><p>I could probably have made this a little more efficient, by having the reducer_py and output_py strings stored as variables and referred to by the reducer and output functions, rather than being passed to them. It’s also worth noting that the variable names used in the lambda functions can be whatever you want — I used s and x because I didn’t feel like adjusting them from the original sample code in the Trino doc. Finally, we could overload this function with one that doesn’t take an output_py string and simply calls the above function with a default version of output_py, such as &#39;s=s&#39;.</p><p><strong><em>SEQUENCE function:</em></strong></p><p>Most of Snowflake’s sequence functions are things like <a href="https://docs.snowflake.com/en/sql-reference/functions/seq1">SEQ4</a>, which are meant to return sequential integers of various sizes (1, 2, 4, or 8 bytes), but not for creating arrays. For that, we have ARRAY_GENERATE_RANGE, which I mentioned earlier. Using the TRANSFORM function, we can actually mimic the versions from Trino that will generate arrays of DATE or TIMESTAMP:</p><pre>SELECT TRANSFORM(ARRAY_GENERATE_RANGE(0, 5), x -&gt; DATEADD(DAY, x, &#39;2024-09-21&#39;));</pre><p>Here what I’ve done is use ARRAY_GENERATE_RANGE to generate the number of dates I want: [0, 1, 2, 3, 4] and then in the TRANSFORM function, calling DATEADD with the interval (DAY), and the starting point. You can imagine using any interval from millisecond to year, providing a starting point from a column, as well as using date math to determine the number of intervals to put into the ARRAY_GENERATE_RANGE call.</p><p>We could also use a custom UDF to do this, which might be a little more elegant; I started with integers and wrote this function in Python that takes the start, stop &amp; step values:</p><pre>CREATE OR REPLACE FUNCTION SEQUENCE_PY(initial_value INTEGER, last_value INTEGER, step INTEGER)<br>RETURNS ARRAY<br>LANGUAGE PYTHON<br>RUNTIME_VERSION = 3.10<br>HANDLER = &#39;main&#39;<br>AS<br>$$<br>def main(initial_value, last_value, step): <br>    step = abs(step) * (1 if initial_value &lt; last_value else -1)<br>    return list(range(initial_value, last_value, step))<br>$$;</pre><p>Notice that it automatically corrects the step to be positive or negative, depending on whether the initial value is higher or lower than last value. Next, I wrote a normal SQL proc to allow the user to call it without the step argument, in which case the step is automatically 1:</p><pre>CREATE OR REPLACE FUNCTION SEQUENCE_SQL(initial_value INTEGER, last_value INTEGER)<br>RETURNS ARRAY<br>AS<br>$$<br>    SEQUENCE_PY(initial_value, last_value, 1)<br>$$<br>;</pre><p>Now, as a final exercise for the reader, I will leave the idea of providing the initial and final values as VARIANT so that they can be dates or timestamps instead of integer. One could easily have a single function that would determine the type of the input value and do the correct computation regardless.</p><p><strong><em>ARRAY_HISTOGRAM function:</em></strong></p><p>This is another fun one — it returns a histogram of the array, which is an object where the keys are the distinct values in the array and each key’s value is the count of items in the array. As it turns out, we can use the REDUCE_PY function described earlier for this:</p><pre>SELECT reduce_py([1, 1, 2, 5], {}, <br>                    &#39;s.update({x: s.get(x, 0) + 1})&#39;,<br>                    &#39;s = s&#39;);</pre><p>Naturally, the array argument could be something like an ARRAY_AGG in a larger select or a column that already contains an array. Of course, a very large number of elements in the array may take a while to compute the histogram, particularly using a multi-step process like REDUCE_PY. I also created a new function called, of all things, HISTOGRAM:</p><pre>CREATE OR REPLACE FUNCTION HISTOGRAM(array ARRAY)<br>RETURNS VARIANT<br>LANGUAGE PYTHON<br>RUNTIME_VERSION = 3.10<br>HANDLER = &#39;main&#39;<br>AS<br>$$<br>def main(array): <br>    return {x: array.count(x) for x in set(array)}<br>$$;</pre><p>I ran both of them using a small chunk of TPC-H scale factor 1, which contains 1.5 million orders, each with a customer key, to get the histogram of how many orders there were per customer (obviously, this isn’t the best way to do this particular task):</p><pre>SELECT HISTOGRAM(ARRAY_AGG(O_CUSTKEY))<br>FROM (SELECT O_CUSTKEY FROM SNOWFLAKE_SAMPLE_DATA.TPCH_SF1.ORDERS LIMIT 5000)<br>;</pre><pre>SELECT REDUCE_PY(ARRAY_AGG(O_CUSTKEY),<br>                 {},<br>                 &#39;s.update({x: s.get(x, 0) + 1})&#39;,<br>                 &#39;s = s&#39;)<br>FROM (SELECT O_CUSTKEY FROM SNOWFLAKE_SAMPLE_DATA.TPCH_SF1.ORDERS LIMIT 5000)<br>;</pre><p>The REDUCE_PY version took 6.5s while the HISTOGRAM took about 1, so on a very large array, either one will take some time, but HISTOGRAM is noticeably faster. I assume that someone could come up with an even more efficient bit of Python code for that.</p><h3>Other Functions from Trino</h3><p>There are a number of other functions in Trino for working with ARRAYs that can be interesting:</p><p><strong><em>ARRAY_SORT, with a comparator function: </em></strong>I alluded to this one earlier — the built-in sort function already allows sorting ascending or descending, and controlling whether NULL values should be at the beginning or end of the output, but it would certainly be useful to be able to supply a lambda function to determine the sort order.</p><p><strong><em>COMBINATIONS, CONTAINS_SEQUENCE, &amp; NGRAMS functions: </em></strong>these are all somewhat similar, either generating combinations of values from the array, or determining whether the array contains a specific sequence of values. I’d probably write these entirely in Python, and a more capable SLICE wouldn’t be hard this way. For that matter, the <strong><em>REVERSE</em></strong>, <strong><em>SHUFFLE, </em></strong>and <strong><em>TRIM_ARRAY </em></strong>function are all basically similar and would be pretty simple in Python.</p><p><strong><em>REPEAT function: </em></strong>this is quite similar to the SEQUENCE function described earlier.</p><p><strong><em>EUCLIDIEAN_DISTANCE, DOT_PRODUCT, and COSINE_DISTANCE functions:</em> </strong>these are all just fairly straight-forward math problems; I don’t remember how to do them off the top of my head, but if Python doesn’t have specific functions for them, I’m sure writing the calculations as lambda functions or UDFs won’t be hard.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b30a126573f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/matching-trinos-array-functions-in-snowflake-9b30a126573f">Matching Trino’s Array Functions in Snowflake</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a mini Time Dimension on the Fly with a Snowflake UDTF]]></title>
            <link>https://medium.com/snowflake/create-a-mini-time-dimension-on-the-fly-with-a-snowflake-udtf-e2fd3a3a61e9?source=rss-1a3818055dd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2fd3a3a61e9</guid>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Dylan Kaufman]]></dc:creator>
            <pubDate>Sat, 02 Dec 2023 02:02:53 GMT</pubDate>
            <atom:updated>2023-12-02T02:02:53.745Z</atom:updated>
            <content:encoded><![CDATA[<h4>How I went from wanting hourly time periods to building a function to generate them on the fly</h4><h3>The Story</h3><p>I’m working on building some queries to analyze virtual warehouse utilization based on the SNOWFLAKE.ACCOUNT_USAGE views that are shared automatically with every Snowflake account. These views provide telemetry about what objects exist and what actions have been taken in the account. I’m not going to go into a lot of detail of how I’m using those views in this article, as that isn’t central to the time dimension or UDTF discussion; perhaps another time.</p><blockquote>Note: complete code for creating and using the UDTF, with inline code notes, is linked at the end of the article.</blockquote><p>While working on one query, I realized that I need an hourly time dimension. If you aren’t very familiar with time dimensions, they are a common structure to provide a table (or tables) that have precomputed information about dates or time periods, such as day of week/month/year, start and end dates, quarter definitions, etc. Normally, the table will have a row for every date in an appropriate calendar period, such as since January 1st, 1900 through some number of years in the future. Joining the time dimension to a data table, such as query history, makes it very easy to categorize, filter or aggregate data across time periods.</p><p>The reason I need a time dimension is that I’m not just trying to see how many queries were started or finished in a given period, but how many ran at any point during each period. For example, if I’m trying to determine warehouse utilization by hour, I need to know that a query starting at 10:59:16.545 and ending at 11:59:23.364 occurred in both the 10:00 and 11:00 hours. Obviously, longer queries may cover many hours. Simply aggregating based on the hour in which it started isn’t enough; instead, we use a time dimension to connect each hour of the day to all queries that started before or during the hour and ended during or after the hour.</p><p>For my purposes, in fact, I really just need two columns, the start time and end time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*NjA0aWnko1UrocmdzyP1UQ.png" /></figure><p>This allows me to do a join where the query start time is before the end of the hour and the query end time is at or after the start of the hour, using a join key like this:</p><p>QUERY_START_TIME &lt; ENDTIME AND QUERY_END_TIME &gt;= STARTTIME</p><blockquote>Technically, the ENDTIME is the start of the next hour, so we don’t want to include any queries that happen to start at precisely that time, as unlikely as that probably is, which is why &lt; ENDTIME, rather than &lt;= ENDTIME.</blockquote><p>I commented to a friend that I might have to make a little time dimension table and he pointed me to a post in the Snowflake community about using sequence and row number functions to generate gapless series of numbers or dates. That’s pretty clever, and not needlessly complex, so I thought I could use it live at query time to generate just enough of a time dimension to cover the period I’m analyzing.</p><p>A query to generate a list of days is very easy:</p><pre>SELECT <br>    DATEADD(DAY, <br>            ROW_NUMBER() OVER (ORDER BY 1) - 1, <br>            CURRENT_DATE() - 10) startDate<br>FROM TABLE(GENERATOR(ROWCOUNT =&gt; 20));</pre><p>The <a href="https://docs.snowflake.com/en/sql-reference/functions/generator.html">GENERATOR</a> function returns 20 empty rows, given the ROWCOUNT argument, and the <a href="https://docs.snowflake.com/en/sql-reference/functions-table.html">TABLE</a> function turns that into a table that can be selected from, or joined. The resulting table has no columns, so SELECT * doesn’t work, but you can put a constant or a function in, if you want to see some output.</p><p>In this case, I used ROW_NUMBER() OVER (ORDER BY 1) — 1 to get back a list of numbers from 0 to 19, and added that to my starting date of CURRENT_DATE() — 10, or 10 days ago.</p><p>The (incomplete) output, unsurprisingly, looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*XjcXCA8NKsZU4BSf2ccg1A.png" /></figure><p>What I need to do with the dates, though, is identify those queries that were running on the day, so I really need both a start and end date. The simple addition of another column below gives me that:</p><pre>SELECT <br>    DATEADD(DAY, <br>            ROW_NUMBER() OVER (ORDER BY 1) - 1, <br>            CURRENT_DATE() - 10) startDate,<br>    DATEADD(DAY, <br>            1, <br>            startDate) endDate<br>FROM TABLE(GENERATOR(ROWCOUNT =&gt; 20));</pre><blockquote>I really like that Snowflake allows using the alias of one column in the expression in other parts of the same statement. Not all databases do that, but in this case it means I don’t have to repeat the logic for startDate in the logic for endDate.</blockquote><p>Here’s a bit of the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*2Eu3G_T9mZb0uEMhKZ9DWg.png" /></figure><p>This is pretty much the most basic time dimension you can get. I can put the above query into a <a href="https://docs.snowflake.com/en/user-guide/queries-cte">CTE</a> or use it as a sub-query and join it to the query history view where the query start date and end date overlap with the date. This will return all the queries that were running at any time on that day, whether they started the night before, finished the day after, or ran entirely within the day.</p><p>I really want to analyze the warehouse utilization per hour, so I needed to find a way to convert my single daily rows into 24 rows per day, one per hour.</p><p>But then I started thinking: What if I want to generate another mini time dimension that lets me do it at half-day intervals or something? In that case, I need to be able to change the parameters easily. Hmm… sounds like a job for a user-defined function, rather than a CTE or sub-query. Specifically, a user-defined <em>table</em> function: <a href="https://docs.snowflake.com/en/developer-guide/udf/sql/udf-sql-tabular-functions.html">UDTF</a>.</p><p>Before getting into the UDTF syntax, though, I still wanted to prove that I could generate the output I need, so after a bit of trial and error, I came up with this:</p><pre>SELECT <br>        DATEADD(HOURS, H.HOUR * 24 / 24, <br>                DATEADD(DAY, D.DAY, CURRENT_DATE())) startTime,<br>        DATEADD(HOURS, 24 / 24, startTime) endTime<br>    FROM (<br>            SELECT ROW_NUMBER() OVER (ORDER BY 1) - 1 &quot;DAY&quot;<br>            FROM TABLE(GENERATOR(ROWCOUNT =&gt; 2))<br>         ) D <br>    INNER JOIN <br>         (<br>            SELECT ROW_NUMBER() OVER (ORDER BY 1) - 1 &quot;HOUR&quot;<br>            FROM TABLE(GENERATOR(ROWCOUNT =&gt; 24))<br>         ) H ON 1=1<br>     ORDER BY 1<br>     ;</pre><p>I have two sub-queries, one returning the number of days I want, and one the number of hours per day; these are joined together and then I assemble the start and end dates from them. The start date is ‘today’ plus the number from the day table D plus a number of hours based on the number return from the hours table H. The end date is just the addition of the appropriate number of hours to the start date.</p><p>I’ll eventually add variables, but this did give me 48 records, 24 hours for each of 2 days:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*NjA0aWnko1UrocmdzyP1UQ.png" /></figure><p>And if I change the 24 in the 2nd GENERATOR and both denominators to 1, I get 2 records, 1 per day running from midnight of one day to midnight of the next:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*1Czeu5N46KpM6cXWwMYvVw.png" /></figure><h3>Bringing it all together</h3><p>Now I just need to turn it into a function (note that I’m putting the function in a UTIL database; feel free to change that as you prefer, or create your own UTIL database, if you don’t have it already):</p><pre>CREATE OR REPLACE FUNCTION UTIL.PUBLIC.DATES <br>              (startDate DATE, <br>               numDays INTEGER, <br>               segmentsPerDay INTEGER)<br>RETURNS TABLE (startTime DATETIME, <br>               endTime DATETIME)<br>AS <br>$$<br>    SELECT <br>        DATEADD(HOURS, <br>                H.HOUR * 24 / segmentsPerDay, <br>                DATEADD(DAY, <br>                        D.DAY, <br>                        startDate)) startTime,<br>        DATEADD(HOURS, <br>                24 / segmentsPerDay, <br>                startTime) endTime<br>    FROM (<br>            SELECT ROW_NUMBER() OVER (ORDER BY 1) - 1 &quot;DAY&quot;<br>            FROM TABLE(GENERATOR(ROWCOUNT =&gt; numDays))<br>         ) D <br>    INNER JOIN <br>         (<br>            SELECT ROW_NUMBER() OVER (ORDER BY 1) - 1 &quot;HOUR&quot;<br>            FROM TABLE(GENERATOR(ROWCOUNT =&gt; segmentsPerDay))<br>         ) H ON 1=1<br>$$;</pre><p>To call this function, we pass in three arguments:</p><ul><li>startDate: the date when we want our little time dimension to start (I stuck with date, forcing it to start at midnight on the date in question)</li><li>numDays: how long we want the time dimension to be; I’ll probably tend to smaller numbers like 7, 30 and 90 for the warehouse utilization analysis, but you could easily put in several years worth or more, if necessary</li><li>segmentsPerDay: this is how many segments we want; right now, this should be a divisor of 24: 1, 2, 3, 4, 6, 8, 12, or 24. You can use any other number you want, but the results may be pretty odd!</li></ul><p>The days table will generate numDays rows while the hours table generates segmentsPerDay. The calculations for how many hours to add become more interesting now — if you want 6 segments per day, we have to add 24/6 hours (4 hour segments).</p><p>Here’s how you call it, just to see the result; in this case, for 2 days of 24 hour segments starting on January 1, 2023.</p><pre>SELECT * <br>FROM TABLE(UTIL.PUBLIC.DATES(&#39;2023-01-01&#39;::DATE, 2, 24))<br>ORDER BY 1;</pre><p>Now, to use it with the query history!</p><pre>SELECT START_TIME, END_TIME, QUERY_ID<br>FROM TABLE(UTIL.PUBLIC.DATES(DATEADD(DAY, -7, CURRENT_DATE()), <br>                             7, 24)) D<br>INNER JOIN SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY Q <br>    ON Q.START_TIME &lt; D.ENDTIME AND Q.END_TIME &gt;= D.STARTTIME<br>WHERE <br>    D.STARTTIME = DATEADD(HOUR, 3, CURRENT_DATE() - 6)<br>ORDER BY 2, 3;</pre><p>This generates hourly windows for the last 7 days and joins to the query history view to get all the queries that ran at any point during that time. The D.STARTTIME filter is just there to limit the number of rows for easy validation, ensuring that we only get queries for an hour; in this case, 3am-4am 6 days ago.</p><p>Since all the start times were within the hour (and I don’t think I ran any queries the hour before), querying the query history table directly by hand got me the same number back. To do a little more validation, I was thinking I should find an hour that has queries that crossed an hour boundary.</p><pre>SELECT STARTTIME, COUNT(QUERY_ID) QUERIES, <br>       MIN(START_TIME) FIRST_START, <br>       MAX(END_TIME) LAST_END<br>FROM TABLE(UTIL.PUBLIC.DATES(&#39;2023-10-01&#39;::DATE, <br>                             31, 24)) D<br>INNER JOIN SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY Q <br>    ON Q.START_TIME &lt;= D.ENDTIME AND Q.END_TIME &gt;= D.STARTTIME<br>GROUP BY STARTTIME<br>HAVING DATEDIFF(HOUR, FIRST_START, LAST_END) != 0<br>ORDER BY 1;</pre><p>This shows me all of the hours in October when I ran queries where at least one crossed from one hour to the next:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*heloP-9a1jmgKf_Q7Ek7ug.png" /></figure><h3>What’s Next?</h3><p>There are a lot of interesting permutations to this idea, of course. This mini-time dimension only has time periods, no other data, so it’s really only good for aggregating to things that took place in the hour (join only on query start time between start and end of hour) or across the hour (as I’ve done above).</p><p>The function could be made smarter so that intervals that aren’t based on whole hours would work properly, such as 1, 5, 10, 15 or 30 minute intervals, etc. To do that, I’d probably do all the date math in milliseconds and convert the desired number of segments from ‘parts of a day’ to ‘number of milliseconds’. Actually, I’d probably change the function to take an interval length and interval type (e.g. 20 seconds), but then I’d do all the date math in the smallest interval I decide to handle in the function.</p><p>It would also be very reasonable to add code to include various common time/date dimension columns, such as month of year, day of year, day of week, etc. Time shifts, such as month-ago, year-ago, etc. wouldn’t be all that hard to add, because there’s only one per row, so it’s just another column expression using dateadd, time_slice, etc.</p><p>Time aggregations, like year-to-date, trailing-12-months, next-90-days, etc. could also be useful, but those add another complexity. My favorite way to do that is with a record for each of the included dates, so next-90-days means that there are 90 rows for each day (‘current’ date 12/1/2023 would have a row for each ‘next 90 days’ date 12/2/2023 through 2/29/2024, so you’d join the ‘next 90 days’ column to the fact table and aggregate on the ‘current’ column). Another way to do it would be to have next-90-days-start and next-90-days-end columns, very similar to what I did with the start &amp; end times for the periods. That would be simpler, for sure.</p><p>One thing to be careful of, though, is that generating a lot of these sorts of records with a lot of columns, on the fly, will probably have a negative impact on query performance. I would typically think of using the UDTF only for a <em>relatively</em> small number of rows and a relatively small number of columns. Don’t use the UDTF for many many years, or for very small time intervals. Don’t use the UDTF for lots of columns of time/date attributes.</p><p>For situations where you need more rows and or more columns, where the actual data volume starts to be a little more meaningful and the impact of the record count on the query performance can start to matter, it would likely be best to generate the data into a table with an appropriate sort order to aid the micro-partition filtering functions in the Snowflake query engine. That’ll be another article, eventually.</p><h3>The Code</h3><p>Here’s the code, with inline annotations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84eafd1b25be33d367d027df52def8f3/href">https://medium.com/media/84eafd1b25be33d367d027df52def8f3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2fd3a3a61e9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/create-a-mini-time-dimension-on-the-fly-with-a-snowflake-udtf-e2fd3a3a61e9">Create a mini Time Dimension on the Fly with a Snowflake UDTF</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reducing Costs by Doing More in Snowflake]]></title>
            <link>https://medium.com/snowflake/reducing-costs-by-doing-more-in-snowflake-79852dfc444b?source=rss-1a3818055dd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/79852dfc444b</guid>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Dylan Kaufman]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 17:11:40 GMT</pubDate>
            <atom:updated>2023-12-07T21:31:45.526Z</atom:updated>
            <content:encoded><![CDATA[<h4>Writing Parquet straight to S3 is much faster than using Spark</h4><p>A large advertising customer of mine was recently having some trouble with one of their data pipelines: they needed the entire pipeline to complete reliably in 4 hours, but it often wasn’t. Digging into the pipeline’s behavior, they noticed that one step was taking as much as three hours by itself, so that was the logical place to try to optimize.</p><p>The process in question was a Spark job that was extracting data from Snowflake, converting to Parquet format, and writing it to S3 where it could be picked up by other systems. This requires maintaining Spark code and operating it (on non-Snowflake compute resources) for something Snowflake can do itself. This is wasteful in compute costs and data processing time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lLSCMiNO3_ZyMznr" /></figure><p>Their first optimization step was to take the query already being executed against Snowflake and build that into a <a href="https://docs.snowflake.com/en/sql-reference/sql/copy-into-location">COPY INTO</a> statement pointing directly at the S3 bucket. This got them pretty significant savings — down from 3 hours to 7 minutes — and a substantial simplification of the process, as well as relieving them of the need to maintain separate compute resources for the job.</p><p>Here’s what that SQL code might look like:</p><pre>COPY INTO &#39;s3://yourbucket/yourpath/&#39; <br>    CREDENTIALS = ( AWS_KEY_ID = &#39;an-aws-key-id&#39; AWS_SECRET_KEY = &#39;an-aws-secret-key&#39; ) <br>FROM (&lt;original query&gt;)<br>FILE_FORMAT = (TYPE = PARQUET)</pre><p>The next step was to use an external stage on S3 to write the data — it’s still almost the same COPY INTO command, but because it uses an external stage, the URL and credentials aren’t required in the COPY INTO command that’s executed. This is much more secure, as one user can set up the stage and allow other users to use it, without having to give them the URL or credentials.</p><p>The reason this is the next step <strong>after</strong> writing directly to the URL is that it requires creating an additional object in Snowflake; since you can create it once and write to it repeatedly, and more securely, it is well worth it. Here is the SQL to create the <a href="https://docs.snowflake.com/en/sql-reference/sql/create-stage">EXTERNAL STAGE</a>and then write to it:</p><pre>CREATE STAGE MY_EXT_STAGE<br>    URL = &#39;s3://yourbucket/yourpath/&#39; <br>    CREDENTIALS = ( AWS_KEY_ID = &#39;an-aws-key-id&#39; AWS_SECRET_KEY = &#39;an-aws-secret-key&#39; )<br>;<br><br>COPY INTO @MY_EXT_STAGE/additional-path<br>FROM (&lt;original query&gt;)<br>FILE_FORMAT = (TYPE = PARQUET)<br>;</pre><p>Both of the direct COPY INTO versions are very well presented in this diagram from the Snowflake docs on <a href="https://docs.snowflake.com/en/user-guide/data-unload-s3">unloading data to S3</a>. The direct URL write is the COPY INTO out to the right, while the external stage write is down the middle. In both cases, the data is being queried and then delivered directly to the S3 bucket in parquet format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*KHkpinsVY0TmR3BAq-jMrQ.png" /></figure><p>So, how did they do?</p><ul><li>Spark (extract from Snowflake, write to parquet in S3): ~180 minutes</li><li>COPY INTO to S3: ~7 minutes (96% decrease)</li></ul><p>That’s as much as a 96% performance improvement, simplification of the code &amp; maintenance, removal of non-Snowflake compute resources, and a huge amount of buffer available in their regular pipeline process!</p><p>In addition to the performance and simplicity improvements, it’s also worth noting that there’s a significant reduction in security risk — the storage location that Spark uses will contain this data, if briefly, and must be secured appropriately. If the data stays in that Spark-managed location, it is also inherently out of date as soon as it is written.</p><p>In total, we see the following benefits of doing this entirely in Snowflake:</p><ul><li>Substantial decrease in total processing time</li><li>Elimination of compute resources required to run Spark, and the cost associated with them</li><li>Simplification of code</li><li>Reduction in effort and cost of code implementation &amp; maintenance</li><li>Reduced security management and risk</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79852dfc444b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/reducing-costs-by-doing-more-in-snowflake-79852dfc444b">Reducing Costs by Doing More in Snowflake</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using SQL to Parse a Large JSON Array in Snowflake]]></title>
            <link>https://medium.com/snowflake/using-sql-to-parse-a-large-json-array-in-snowflake-abe0c93c438b?source=rss-1a3818055dd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/abe0c93c438b</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Dylan Kaufman]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 23:35:27 GMT</pubDate>
            <atom:updated>2023-04-26T00:48:17.451Z</atom:updated>
            <content:encoded><![CDATA[<p>JSON is a great data transfer format, and one that is extremely easy to use in Snowflake. From time to time, we get questions from customers about dealing with JSON files that are ‘too large’ for Snowflake to handle. Usually, it turns out that it isn’t actually the file that’s too big, but some element of the file. As the documentation for the <a href="https://docs.snowflake.com/en/sql-reference/data-types-semistructured#label-data-type-variant">VARIANT</a> data type notes, the maximum size of a VARIANT object is 16MB. This is the same as the maximum size of a VARCHAR.</p><p>As I mentioned, the issue isn’t the total file size, but the size of the largest element. In the case of the problem a customer ran into recently, the entire JSON file consists of a single element called ‘Report_Entry’, which holds an array of all 22,000 active employees of the company. It looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*AaMPMCzqdmDtGvyneEPM9A.png" /></figure><p>Since the Report_Entry element can’t be over 16MB, and there are about 22k employees, that gives us about 750 characters per employee if we want the array to fit into a single element. This particular source file is running more like 1,000 characters per employee, which makes the element too big and, therefore, the file can’t be processed directly.</p><p>We were discussing using Python to convert this file into something that Snowflake could handle more easily, or to parse it directly, but since the format is extremely straight-forward, I realized there’s an easy way to do it directly in SQL.</p><p>Here’s how that works:</p><ol><li>Create a file format that will let us load the data as raw text, one row per line</li><li>Stage the data into a table, with row numbers</li><li>Dump the element name, array opener, and array closer, leaving just the employee records</li><li>Identify the first and last row for each employee record</li><li>Break the existing name/value pairs into separate strings</li><li>Aggregate the entire result back into JSON objects in a VARIANT column of a table</li></ol><p>At that point, the data will be usable using easy Snowflake SQL syntax.</p><p><em>Note: some of the snippets below make use of column or other object names that are only included in another snippet. The full SQL code is included near the end of the article.</em></p><p><strong>1. Create the File Format</strong></p><p>Snowflake’s <a href="https://docs.snowflake.com/en/sql-reference/sql/create-file-format">FILE FORMAT</a> object allows defining lots of parameters about the structure of a data file. In this particular case, we’re going to use the standard CSV format as the basis, but we’re going to generate only a single column by not using a field delimiter:</p><pre>CREATE OR REPLACE FILE FORMAT RAW_TEXT_ROWS<br>    TYPE = CSV<br>    FIELD_DELIMITER = &#39;NONE&#39; <br>    REPLACE_INVALID_CHARACTERS = TRUE;</pre><p>When we use this file format, then, every line of the data file will be turned into a single row in the target table.</p><p><strong>2. Stage the Data to a Table</strong></p><p>In this snippet, I am creating a very simple target table called JSON_ROW_INPUT, which will hold the data and line number for each line in the file. Then, I run the COPY INTO command. I staged the file to an internal stage called test and the beginning of the file name happens to be Active, as in ‘Active Employees’, so the query simply references that location and path: @test/Active.</p><pre>CREATE OR REPLACE TABLE JSON_ROW_INPUT <br>(<br>    ROW_DATA VARCHAR,<br>    ROW_NUM INTEGER<br>);<br><br>COPY INTO JSON_ROW_INPUT <br>FROM (SELECT $1, METADATA$FILE_ROW_NUMBER <br>      FROM @test/Active)<br>FILE_FORMAT = (FORMAT_NAME =&#39;RAW_TEXT_ROWS&#39;);</pre><p>As you can see, I included the format name of the FILE FORMAT object, but I also included METADATA$FILE_ROW_NUMBER; this ensures that we can determine the exact order in which each line appeared in the original file. That will be important when we’re assembling rows of this table into objects.</p><p><strong>3. Dump Unnecessary Rows</strong></p><p>The raw JSON came in a very easy format — each line contained one token. It’s this fact that allows the rest of this to work so easily. For example, there are only two lines of JSON that aren’t needed, which are the &quot;Report_Entry&quot;: [{ line near the top that identifies the single element, and the }] line near the bottom that completes the array. If we remove those two, we will have just a complete list of valid employee objects, thanks to the starting and ending brackets that surround the rest of the content — those will turn into the start and end of the first and last employee record, respectively. We can accomplish this very simply, with a where clause:</p><pre>WHERE ROW_DATA NOT IN (&#39;&quot;Report_Entry&quot;: [{&#39;, &#39;}]&#39;)</pre><p><strong>4. Identify the Rows for each Employee</strong></p><p>Since we know that the rows were ordered in the original file, and the only rows present are actual employee records and the dividing brackets, we can filter out all the non-bracket rows, and do a self join on the table to match up the brackets.</p><pre>SELECT OB.ROW_NUM OB_ROW, MIN(CB.ROW_NUM) CB_ROW<br>FROM DATA OB<br>INNER JOIN DATA CB ON OB.ROW_NUM &lt; CB.ROW_NUM<br>WHERE OB.K = &#39;{&#39; AND CB.K = &#39;}&#39;<br>GROUP BY OB.ROW_NUM</pre><p>In this join, OB represents the opening bracket in each JSON object, while CB represents the closing bracket. Naturally, the first bracket in the entire file is on the first line and the join will link it to all of the many closing brackets later in the file (with a later row number), but the MIN aggregation ensures that we only get the closing bracket that follows most closely after each opening bracket. This lets us know the starting and ending points of each employee record.</p><p>I initially thought I’d use a windowing function like ROW_NUMBER, but realized this was simpler, and probably faster.</p><p><strong>5. Break the N/V Pairs</strong></p><p>Every row of the file that contains actual data has a name and a value, surrounded by double quotes and separated by colon-space (: ). To turn these into strings, we can use the SPLIT function, but we also need to get rid of some possible blank space and extra quotation marks:</p><pre>TRIM(SPLIT(TRIM(ROW_DATA, &#39; ,&#39;), &#39;: &#39;)[0]::VARCHAR, &#39;&quot;&#39;) K,<br>TRIM(SPLIT(TRIM(ROW_DATA, &#39; ,&#39;), &#39;: &#39;)[1]::VARCHAR, &#39;&quot;&#39;) V</pre><p>This takes the original row data, and trims off any leading or trailing spaces and commas; then it splits the row into an array containing as many values as necessary based on the presence of the : . In this case, that means we will always have either one or two values; if there’s no separator, we’ll get one value ({) or (}) while if there is a separator, we’ll get the name, aka ‘key,’ and value. Finally, for each string, it trims off any double-quotation marks.</p><p>It is worth noting that I’m working with a very clean data set that doesn’t have any extraneous occurrences of : . In many other data sets, it may be necessary to build a slightly more complicated expression to account for the possibility that either a key or a value might actually have : in it.</p><p><strong>6a. Aggregate it all back into JSON</strong></p><p>Snowflake supports numerous SQL functions for manipulating objects in JSON format, such as OBJECT_CONSTRUCT and OBJECT_AGG. OBJECT_CONSTRUCT, if given pairs of values will convert those into a single object of name value pairs. For example:</p><p>OBJECT_CONSTRUCT(&#39;Key1&#39;, &#39;Value1&#39;, &#39;Key2&#39;, &#39;Value2&#39;) will produce:</p><pre>{<br>  &quot;Key1&quot;: &quot;Value1&quot;, <br>  &quot;Key2&quot;: &quot;Value2&quot;<br>}</pre><p>OBJECT_AGG does something very similar, but based on a set of rows. If it were just run on a table containing the above values, it would return the exact same JSON output as above. In our case, though, every row of the table can be associated with an opening bracket’s row number, so we can group on that and we will get back a single row per employee.</p><pre>SELECT OBJECT_AGG(K, V::VARIANT) EMPLOYEE<br>FROM DATA<br>INNER JOIN OB_AND_CB ON ROW_NUM BETWEEN OB_ROW AND CB_ROW<br>WHERE DATA.K NOT IN (&#39;{&#39;, &#39;}&#39;)<br>GROUP BY OB_ROW<br>ORDER BY OB_ROW</pre><p>The OBJECT_AGG function requires that the first (the key) argument be a string, which is how it is already formatted from the SPLIT, and the second (the value) be a variant, so I’m converting the V column into VARIANT on the fly. The INNER JOIN uses the row number for the opening bracket (OB) and closing bracket (CB) to gather up all the records for a given employee, and we filter out all the actual brackets at this point.</p><p>The GROUP BY ensures that all the key/value pairs for a single employee will be aggregated into an object together. The ORDER BY isn’t necessarily important, but I put it in so that the records will come out in the same order as what’s in the file.</p><p><strong>6b. Write the converted data into a table</strong></p><p>Putting all those pieces together, we get the following query and wrap it in a CREATE OR REPLACE TABLE command to persist the data in a table. Here is the full SQL, which brings together all the pieces above.</p><pre>CREATE OR REPLACE TABLE EMPLOYEE_JSON AS<br>WITH DATA AS (<br>        SELECT ROW_NUM,<br>                TRIM(SPLIT(TRIM(ROW_DATA, &#39; ,&#39;), &#39;: &#39;)[0]::VARCHAR, &#39;&quot;&#39;) K,<br>                TRIM(SPLIT(TRIM(ROW_DATA, &#39; ,&#39;), &#39;: &#39;)[1]::VARCHAR, &#39;&quot;&#39;) V        <br>        FROM JSON_ROW_INPUT<br>        WHERE ROW_DATA NOT IN (&#39;&quot;Report_Entry&quot;: [{&#39;, &#39;}]&#39;)<br>    ),<br>    OB_AND_CB AS (<br>        SELECT OB.ROW_NUM OB_ROW, MIN(CB.ROW_NUM) CB_ROW<br>        FROM DATA OB<br>        INNER JOIN DATA CB ON OB.ROW_NUM &lt; CB.ROW_NUM<br>        WHERE OB.K = &#39;{&#39; AND CB.K = &#39;}&#39;<br>        GROUP BY OB.ROW_NUM<br>    )<br>SELECT OBJECT_AGG(K, V::VARIANT) EMPLOYEE<br>FROM DATA<br>INNER JOIN OB_AND_CB ON ROW_NUM BETWEEN OB_ROW AND CB_ROW<br>WHERE DATA.K NOT IN (&#39;{&#39;, &#39;}&#39;)<br>GROUP BY OB_ROW<br>ORDER BY OB_ROW<br>    ;</pre><p>The original data file consisted of 651,220 lines, and the parsing was only this easy because the file was already well formatted, but JSON often is. Even if it weren’t formatted quite so well, it probably wouldn’t be very hard to factor in some simple conversions to make this work, such as making sure the brackets are on lines by themselves.</p><p>Even more important, though is that this particular JSON isn’t very complicated. Just as I was able to keep the key-value split very simple because I knew there were no extra : in my sample, I was able to use the brackets as delimiters because there were no child objects involved. If any of the elements included additional arrays or JSON, I’d have needed to do something more complicated to get it to work, possibly including using a procedural language instead of a single SQL query.</p><p><strong>Conclusion</strong></p><p>My customer’s original comment was “this not-very-big JSON file is too big to handle in Snowflake” (not a direct quote). Often, ‘too big’ means having some process shred the file, such as with CSV files that can often just be broken into chunks at random line breaks. My colleague, Paul Horan, <a href="https://medium.com/snowflake/working-with-large-json-files-in-snowflake-f527bf42e00e">gives a great example of that &amp; describes</a> how to use <a href="https://stedolan.github.io/jq/">jq</a> to split up JSON files. Paul also demonstrated doing the same thing with <a href="https://medium.com/snowflake/working-with-large-json-files-in-snowflake-part-2-sort-of-9ede10700980">Java</a>, as well as in a <a href="https://medium.com/snowflake/working-with-large-json-files-in-snowflake-part-iii-a62207c93580">streaming mode</a>. In some cases, though, it isn’t necessary to break out a procedural language just because the JSON is big.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abe0c93c438b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/using-sql-to-parse-a-large-json-array-in-snowflake-abe0c93c438b">Using SQL to Parse a Large JSON Array in Snowflake</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Function Validation in Snowflake, Part 3: JavaScript or _____]]></title>
            <link>https://medium.com/snowflake/custom-function-validation-in-snowflake-part-3-javascript-or-f9239e03fdd1?source=rss-1a3818055dd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9239e03fdd1</guid>
            <category><![CDATA[custom-functions]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Dylan Kaufman]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 21:34:50 GMT</pubDate>
            <atom:updated>2023-04-26T19:08:03.179Z</atom:updated>
            <content:encoded><![CDATA[<h4>Staging external hash results to validate in Snowflake</h4><h4>Previously On…</h4><p>In two earlier articles, I’ve described how to create a<a href="https://medium.com/snowflake/validating-a-python-hash-function-inside-snowflake-3c9255bf6bc4"> Python</a> or <a href="https://medium.com/snowflake/snowflake-udfs-for-hash-validation-part-2-java-a12c2f093e6d">Java</a> UDF in Snowflake to replicate one of Snowflake’s built-in hashing functions, and then query various amounts of data to verify with some confidence that the UDF and the built-in function are generating the same result.</p><p>This is by far the easiest way to validate such a script: because everything happens inside Snowflake, we don’t have to import or export any data, there’s no risk of the data being left somewhere we don’t want it, and we don’t have to worry about finding or supplying compute resources.</p><p>Having done that, we can have reasonable confidence that using the same Python or Java code <em>outside</em> Snowflake will get us the same result as running the built-in function <em>inside</em> Snowflake. Indeed, this was the original request from a customer:</p><blockquote>We need a Python version of MD5_NUMBER_LOWER64, so that we can bucket users both in Snowflake and outside Snowflake, but the one we wrote isn’t working; can you help?</blockquote><p>Not an exact quote.</p><h4>What about JavaScript?</h4><p>Since Snowflake has long supported JavaScript for UDFs and stored procedures, it would seem very logical to do the same thing in JavaScript that I’ve already done with Python and Java.</p><p>Unfortunately, JavaScript doesn’t include a built-in crypto library and our JS UDFs don’t support importing an external crypto library such as<a href="https://github.com/sytelus/CryptoJS/blob/master/rollups/md5.js"> CryptoJS</a>. Although it would very likely be possible to include the code from an external library in the UDF, that seems like a lot of work just for this validation.</p><p>If you really want to do this with JavaScript, you can follow the general instructions in my earlier articles, but build a UDF in JS that includes the full code for the MD5 hash function, so that you can do it all in Snowflake.</p><p>I’m going to leave that as an exercise for readers, though. That said, you <em>could</em> use JavaScript as your language of choice for the method I’m going to describe below.</p><h4>Well, OK, but can I use &lt;fill-in-the-blank&gt;?</h4><p>As I’ve mentioned before, Snowflake supports UDFs with Python, Java or JavaScript. It is easy to imagine, though, that you want to generate a value in some language we don’t support. Maybe you have an app in Go and you need to generate the same hash in the app that’s going to be available in Snowflake. Or maybe you use Ruby. Or Julia. Or TypeScript, even if that is basically JavaScript.</p><p>Fair enough. Snowflake provides<a href="https://docs.snowflake.com/en/user-guide/ecosystem-lang.html"> connectors and drivers</a> for a bunch of different languages; between the language-specific interfaces and the JDBC &amp; ODBC drivers, it should be possible to connect to Snowflake from just about anything.</p><p>There are some other ways to do it, but the method I’m going to describe is as shown in this diagram: run a hash on customer data, load the customer keys and hash into Snowflake, and then compare the custom hash to the Snowflake hash for each customer key on the fly.</p><figure><img alt="Diagram showing data flow and processing" src="https://cdn-images-1.medium.com/max/1024/1*IHMtBc0juwWF45N7q5XL-g.png" /><figcaption>Diagram showing data flow and processing</figcaption></figure><ol><li>Create the hash function in the language of your choice</li><li>Write a script that will: <br>- connect to Snowflake and query for the sample data,<br>- use the hash function to generate the hash for each sample value,<br>- write the sample value &amp; hash out to a CSV or JSON file (or a collection of files, if there’s a lot of data involved), and<br>- deliver the data file(s) to Snowflake</li><li>Run a query in Snowflake to apply the built-in function to each sample value and compare to the hash, returning rows (or a count) if there are any discrepancies</li></ol><p>I chose this way because it is relatively few steps, we’re only moving data <em>to </em>Snowflake, and this is generally simpler than some of the other options.</p><h4>Generating External Hash Data</h4><p>Let’s say I need to use PYFL (Pick-Your-Favorite-Language) to generate the hash in a non-Snowflake compute engine. I need to make sure that the PYFL version of the hash will match the Snowflake version of the hash. To do that validation, I wrote a program in PYFL that connected to my Snowflake account and ran a query like the following against the TPC SF1000 database:</p><pre>SELECT c_name || ‘/’ || c_address AS INPUT<br>FROM SNOWFLAKE_SAMPLE_DATA.TPCH_SF1000.CUSTOMER;</pre><p>Next, it took the 150 million records and generated a hash for each one, using a PYFL version of the MD5_NUMBER_LOWER64. The result looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Zso1DmKL8HSb0Gco" /></figure><p>Then, it wrote all the rows into a collection of CSV files, split the data into many files called hashtest/csv/data_#_#_#.csv, and compressed them with gzip, just to reduce the amount of data being moved.</p><p>Finally, it delivered the resulting 328 csv.gz files into a named internal Snowflake<a href="https://docs.snowflake.com/en/user-guide/data-load-local-file-system-create-stage.html"> stage</a> called TESTDB.PUBLIC.TEST. Snowflake’s LIST command lets us see what’s in a stage; the screenshot below shows 5 of the files, as displayed by LIST @TESTDB.PUBLIC.TEST/hashtest/csv;:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qUiQu1DvGXfJCF6b" /></figure><h4>Delivering the External Hash Data to Snowflake</h4><p>At this point, we have a list of 150 million values with their PYFL hash values, and I need to generate the hash value with the Snowflake function and then compare it to the PYFL value.</p><p>In order to run the Snowflake internal function on the sample data and compare the results to the external data within Snowflake, we have to get the data into Snowflake. I’ve mentioned delivering it to a named internal stage, but we could also use a user or table stage, which are also types of<a href="https://docs.snowflake.com/en/user-guide/data-load-local-file-system-create-stage.html"> internal stages</a>, or we could even use an external stage on<a href="https://docs.snowflake.com/en/user-guide/data-load-s3-create-stage.html"> AWS S3</a>,<a href="https://docs.snowflake.com/en/user-guide/data-load-azure-create-stage.html"> Azure Blob Storage</a>, or<a href="https://docs.snowflake.com/en/user-guide/data-load-gcs-config.html"> Google Cloud Storage</a>. Here’s a quick summary of the pros and cons:</p><ol><li>user stage: every user has a user stage accessible only to them; nothing to create, just upload the files to it</li><li>table stage: only exists with a table, and is intended specifically for files meant &amp; formatted for that table; any user with access to the table can use the stage</li><li>internal named stage: easy to create and easy to use, just upload the files to it once it is created; anyone with access to the stage can use it</li><li>external stages: these require an account in one of the 3 supported cloud storage services, and take a bit more effort to create than an internal named stage, but it may be easier to write data files directly to the blob storage and avoid writing them locally and then uploading them; anyone with access to the stage can use it</li></ol><p>If you’re writing the files to blob storage, “delivering the data to Snowflake” just means setting up the stage object in Snowflake, if you haven’t already done so. If you’re writing the files locally and then moving them into one of the internal stages, or writing directly to a table, you have a bunch of choices, including <a href="https://docs.snowflake.com/en/user-guide/snowsql.html">SnowSQL</a> or one of Snowflake’s many <a href="https://docs.snowflake.com/en/user-guide/conns-drivers.html">connectors and drivers</a>.</p><p>In the case of my PYFL program, as I mentioned, it split the data into a set of gzipped CSV files and delivered them to an internal named stage.</p><h4>Comparing with the Internal Function</h4><p>With the files sitting in the stage, the next step for a general data pipeline use case would likely be to ingest the data into tables for further querying and ELT usage. In this particular case, though, we’ll keep it simple by querying directly against the stage:</p><pre>SELECT TOP 50 $1, $2<br>FROM @TEST_DB.PUBLIC.TEST/hash_test/csv;</pre><p>The $1 and $2 tokens simply represent the two columns in the files; if there were more columns, each would have a number. We can run the validation query that way too, without actually bothering to ingest it into a Snowflake table first:</p><pre>SELECT $2 = MD5_NUMBER_LOWER64($1) AS MATCH,<br>       COUNT(*) AS NUM_ROWS<br>FROM @TESTDB.PUBLIC.TEST/hash_test/csv<br>GROUP BY MATCH;</pre><p>This query will return one or two rows, telling us how many of the hashes match and how many don’t. If our PYFL function is doing what we want, there will be one row with the MATCH column showing TRUE.</p><p><em>Just to be clear — we’re actually running this query directly against the compressed CSV files, without taking the time to load them into a table.</em></p><p>If there are hashes that don’t match, they will show up on a row with the MATCH column set to FALSE. In that case, we may want to see some of the values where the hashes don’t match. For that, we’ll run a slightly different query, where we display all the input values where the internal and external hashes don’t match, and both of the hashes.</p><pre>SELECT $1 AS INPUT,<br>       $2 AS EXT_HASH,<br>       MD5_NUMBER_LOWER64($1) AS INT_HASH,<br>       METADATA$FILENAME<br>FROM @TESTDB.PUBLIC.TEST/hash_test/csv<br>WHERE EXT_HASH &lt;&gt; INT_HASH;</pre><p>I’ve also thrown in another potentially interesting piece of information: the METADATA$FILENAME column will display the name of the file the input row came from, which could be useful for debugging in some cases. There’s also a METADATA$FILE_ROW_NUMBER column, which will show the row within each file.</p><p>Naturally, the pretend PYFL function I wrote worked flawlessly the very first time, so the first query returns only a single row showing 150m matches, while the second returns none.</p><h4>Pay No Attention to the Man Behind the Curtain</h4><p>Hey, remember when I said “let’s pretend” earlier? Well, I didn’t <em>actually</em> write a function in another language and write a wrapper around it to connect to Snowflake and all that stuff. I’d have included all the code, if I had!</p><p>No, instead, I took advantage of my original Python UDF and<a href="https://docs.snowflake.com/en/sql-reference/sql/copy-into-location.html"> Snowflake’s COPY INTO &lt;location&gt; feature</a>, which allows writing any query out to data files in a stage in CSV, JSON, or Parquet format.</p><p>Here’s the query I used; I kept this pretty simple, just telling it to prefix all the files with hash_test/csv/ and format them as CSV.</p><pre>COPY INTO @TESTDB.PUBLIC.TEST/hash_test/csv/<br>FROM (SELECT c_name || ‘/’ || c_address AS INPUT,<br>             TESTDB.PUBLIC.MD5_NUMBER_LOWER64_PY(INPUT) AS HASH<br>      FROM SNOWFLAKE_SAMPLE_DATA.TPCH_SF1000.CUSTOMER)<br>FILE_FORMAT = (TYPE = CSV);</pre><p>This simulated the behavior of the PYFL code I described: use a custom function to generate a hash and put the data into a bunch of files that can be read in Snowflake.</p><p>If you’re curious, the numbers in the file names, shown in the LIST output earlier, represent the node number of the compute node within the virtual warehouse, the CPU core number, and a sequential number for how many files were written by that node. _0_1_38 means, since they are all zero-based, it is the 39th file written by node 0’s CPU core 1.</p><h4>But Wait! There’s More!</h4><p>With these three articles, we’ve seen that whether you’re using Python, Java, or some other language, there is a way to validate functions that need to be run both inside and outside Snowflake. This is true even if the function running <em>inside</em> Snowflake is not provided by Snowflake, in fact.</p><p>Here are the scenarios we’ve covered specifically:</p><ul><li>Use Python or Java inside Snowflake to compare the outputs of a custom function and a built-in Snowflake function, entirely within Snowflake</li><li>Use Snowflake to validate data generated by a custom function in just about any language outside Snowflake against a built-in Snowflake function</li></ul><p>We aren’t limited to those uses, though. Here are some more possibilities, just in the ‘validating function output’ category:</p><ul><li>Use Snowflake to generate data for validation outside Snowflake against a custom function in any language: generate hashes in Snowflake, export the sample data &amp; hash values to files, then validate with a function written outside of Snowflake. This requires moving data <em>out</em> of Snowflake, which can take time and is a potential security risk. It also requires having compute resources on which to receive and process the data.</li><li>Snowflake also supports <a href="https://docs.snowflake.com/en/sql-reference/external-functions">External Functions</a>, which are a type of UDF that is actually configured to call out to a 3rd party service, whether it is a custom function you’re running in AWS Lambda (or similar) or a function actually provided by someone else. In this case, it mirrors my original Python and Java samples, except that the data is being sent over to the external service provider and results are being sent back (over https, so it should be fairly secure, as long as you trust the external service).</li><li>We don’t have to be validating against a built-in function: if we need to be able to generate the same output with Python and/or Java, and <em>another</em> language, we could combine these techniques — deploy the Python and Java functions into Snowflake, load data from the third language’s function into Snowflake, and then use a single query to validate all three against each other.</li><li>We don’t even necessarily need to be planning to use Snowflake in general. The ability to run a custom function against a substantial amount of data makes it a great option for this sort of validation, even for functions that won’t be run in Snowflake other than for the validation. Suppose you have two versions of an app, one in Python and the other in Java, and you’ve written a function meant to do the same thing in each — again, deploy the two functions into Snowflake, then query them against a large amount of data to validate that they are returning the same values.</li></ul><p>Ultimately, the many ways Snowflake supports running complex functions can be used to do a great deal more than this sort of validation, such as:</p><ul><li>machine learning scoring</li><li>inference (such as sentiment analysis)</li><li>parsing unstructured or complex semi-structured data into something more easily queried</li><li>image or video analysis (such as manufacturing QA or equipment damage analysis)</li><li>audio analysis (such as transcribing physician’s recorded visit notes)</li><li>converting PDF or other formats into semi-structured or tabular formats</li><li>and many more</li></ul><h4>“Just One More Thing” — Columbo</h4><p>If you loaded a big chunk of data into a stage for the validation, you’ll probably want to remove it when finished, rather than let it take up that space. Don’t forget…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9239e03fdd1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/custom-function-validation-in-snowflake-part-3-javascript-or-f9239e03fdd1">Custom Function Validation in Snowflake, Part 3: JavaScript or _____</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyzing Wordle]]></title>
            <link>https://medium.com/@dylan.kaufman/analyzing-wordle-9405e3706c53?source=rss-1a3818055dd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9405e3706c53</guid>
            <category><![CDATA[wordle]]></category>
            <dc:creator><![CDATA[Dylan Kaufman]]></dc:creator>
            <pubDate>Tue, 25 Jan 2022 00:19:13 GMT</pubDate>
            <atom:updated>2022-02-02T18:57:50.139Z</atom:updated>
            <content:encoded><![CDATA[<p>Reminds me of Mastermind. Or Hangman, for that matter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*SGkhbwxZm1RgSsaR-ijm3A.png" /><figcaption>My Wordle 219 Result</figcaption></figure><p>I only figured out what Wordle was a few days ago. I spend little to no time on Facebook anymore, but I hopped on to see what a few friends were up to and saw people posting their results. At some point, I wound up googling it, and have now played a few times at <a href="https://www.powerlanguage.co.uk/wordle/">https://www.powerlanguage.co.uk/wordle/</a>.</p><p>Then a couple of days later, a friend reported that her 14-year-old daughter, Ellie, said it’s just another version of Mastermind. I always liked Mastermind as a kid, and I’ve played it with my kids occasionally.</p><h4>Finding a Good Starting Point</h4><p>Ellie is pretty much exactly correct that Wordle is just a slightly different version of Mastermind. In Mastermind, with 6 colors, there are 6⁴ possible codes (6 choices in each of 4 slots), which is a total of 1,296 possible combinations. You can reduce that to 360 if you don’t allow repeating colors, or 900 if you only allow repeating each color once, which are common variations.</p><p>In Wordle, there are 5 slots, and at least at first glance, 26 different letters you can put in them. 26⁵ is almost 12 million combinations, and you only get 6 chances to get them right.</p><p>The clues are the same in Wordle as in Mastermind — for each letter, the game tells you whether it is the right letter in the right place, the right letter in the wrong place, or just wrong.</p><p>There are some constraints on the choices, though. I was assuming that it would work from a list of words, so the final answer wouldn’t ever be something that wasn’t considered a word by the person who created the list.</p><p>I’ve heard about a few different strategies for starting:</p><ul><li>a consonant heavy word</li><li>a vowel heavy word</li><li>all vowels</li><li>all consonants</li><li>the same starting word every day</li></ul><p>I did some checking, and according to Wikipedia, the <a href="https://en.wikipedia.org/wiki/Letter_frequency">most commonly used letters</a> in the English language are E, T, A, I, and O. As it turns out. I decided to try that, but it turns out that the 5 letters you enter must be in the game’s word list. Unfortunately, there doesn’t seem to be a 5-letter word with those letters, not even iotae, which I could easily imagine pretending was the plural of iota. This does not quite rule out words with exclusively consonants… crypt depends on whether you choose to count ‘y’ as a vowel, and <a href="https://www.merriam-webster.com/dictionary/crwth">crwth</a> is an English word.</p><p>I also learned recently that the game will includes some words that have the same letter more than once, both as doubles (SWILL) or separately (OASIS). There are certainly valid 5-letter words that use the same letter 3 times, such as SASSY, but I’m going to guess that there aren’t any that use more than that, so really, the maximum possible is 26³*25*24, which is <em>only</em> 10.5 million instead of nearly 12.</p><p>I found that Josh Wardle, who hosts (and I assume created) <a href="https://www.powerlanguage.co.uk/wordle/">Wordle</a> has a somewhat similar game hosted in his GitHub, including a list of 267,751 <a href="https://raw.githubusercontent.com/powerlanguage/guess-my-word/master/wordlist/sowpods.txt">words</a> ranging from 2 to 15 letters. That’s pretty similar to <a href="https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt">this list</a> of 370,103 words ranging from 1 to 31 letters. Cutting each of those lists down to just the 5 letter words, I found 12,478 in the first list and 15,918 in the other. Combining them and making them unique got me 18,377 5-letter words.</p><p>Please note that I’m not currently questioning the validity of any of these combinations of 5-letters as ‘words’. For example, though the aforementioned crwth is in the Merriam-Webster dictionary, cwtch and fldxt are not. Those are 3 of the 9 from the combined list of 18,377 that have no vowels, not even ‘y’.</p><p>I used regular expressions both to get rid of everything not 5-letters long and to split all the remaining words into tab-delimited lists to make them easy to paste into Excel. 5 quick, sorted pivot tables later, and here are the 5 most common letters in each of the 5 positions, based on these two word lists:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_b_Hx2kOIb08RTx1iioNsA.png" /></figure><p>Not very surprising that all 5 in the 2nd position are vowels. I was thinking that I wouldn’t have been surprised to see ‘h’ up pretty high, and then went back to the full pivot to find that the ‘r’, ‘l’, and ‘h’ are the next three most common, with ‘r’ being over 50% more common in the second place (1298 to 808).</p><p>As it turns out, SARES, which is the word you’d get if the most common in each position made a word, isn’t a word. At least, not on the list used by Wordle. The next letter in the 5th spot that isn’t duplicating one of the earlier is ‘y’. So, if you want to use a word that has a high probability of a lot of correct letters, SAREY might be your word, except it’s not in the list.</p><p>YEARSon the other hand is undoubtedly in the list, so that one might be a good starting word. After using YEARS to reasonably good effect, my friend Holly commented that Y isn’t all that common — she uses TEARS. I should have noticed originally that using ‘b’ or ‘t’ in the first position would be more likely successful there than ‘y’.</p><p>I came back to this article and started thinking through the letter counts by position and realized that CARES is probably better than either YEARS or TEARS, at least with the large set of words I used to do the analysis.</p><p>The other way to look at it is simply the sheer number of uses of each letter, regardless of position:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*vKBRSWvEOm74QSFA9FCXJA.png" /></figure><p>So, the 5 most common letters throughout the word list, are ‘a’, ‘e’, ‘s’, ‘o’, and ‘r’. That suggests the word AROSE might be the most likely to get the most correct letters, though not necessarily the right positions, on the first guess.</p><h4>Play Strategy</h4><p>I always start with the same word — I’ve been using YEARS, but I’m going to switch to either TEARS or CARES now. CARES gives the highest chance of the right letter in the right position, but AROSE would appear to have a better chance of right letters in any position. Ultimately, I want to get as much information as possible from each guess.</p><p>The first guess should never have the same letter more than once because it wastes the opportunity to get information. Getting the right answer on the first try is 100% luck anyway.</p><p>If I get any correct letters, I <em>always</em> use them in each later guess. The result below shows that someone made a guess (#4) without reusing either of the letters from guess #3 that were already proven to be correct; in my view, that’s a complete waste of a guess.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*mnTvnVGPWP9fYKeioRBUSA.png" /></figure><p>There’s an option, if you click on the gear icon at the top right of the Wordle screen (at least in a desktop web browser), for ‘hard mode’, which forces you to use revealed hints in later guesses. That option will force you to put the same letter in the 4th position and make sure that the letter you have wrong in the 2nd position is somewhere in guess 4. It also highlights letters on the keyboard, making it <em>easier</em>, as far as I’m concerned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZZ3eT80fYDwl0xv0hHsmg.png" /></figure><p>Often, after a couple of guesses, I wind up actually writing out the options on a piece of paper or in a text file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*d1Rzcp0HSYRm80FkNloUEw.png" /></figure><p>In this case, at this point, I knew that ‘O’ is the 2nd position and that ‘S’ and ‘T’ are correct but can only be in certain positions. That makes it much easier to think through possible words.</p><p>There’s still a certain amount of luck involved, even after the first guess:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*CBkfSahxSbR7WEzuIFkSrg.png" /></figure><p>I don’t remember what the first letter of guess 3 was, but I was pretty sure based on guess two that I was looking for _IGHT, and then it was just luck that I got the right first letter by guess 5, since there are a lot of choices — I believe there are 10 five letter words ending in IGHT.</p><p>Wordle is definitely fun. I really like the way the shareable result looks. I wish I could go back and try some of the older ones, not having seen them. I wouldn’t be averse to it giving more chances. I’m definitely going to be playing it, but I’ll definitely play Mastermind any time I can get my kids to play with me!</p><p>There are surely lots of strategies available that I didn’t mention, and a lot of other interesting information about letter combinations. There are numerous articles about doing cryptograms, for example, that discuss extensively common double letters (such as ‘tt’ in ‘letters’) and common pairs or triplets (such as the many pairs starting with ‘s’ and ‘t’ that are so common they’re practically letters themselves: sh, sp, th…). Those articles will also discuss a lot of other interesting factors for figuring out ciphers, such as common single letter words, letters that are used after apostrophes, and a whole host of patterns.</p><p>Do you have a particular strategy?</p><h4>Addendum</h4><p>I looked at the source code, and there are 2315 words encoded it. If 1/31/21 was the 226th day of the game, it must have started on 6/20/21, and will run out of words on approximately Friday, October 22, 2027. I started to try to interpret the code, but it’s obfuscated at least by having all the variables and functions named with meaningless letter combinations. I decided not to do the numerical analysis of those words…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9405e3706c53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake UDFs for Hash Validation, Part 2: Java]]></title>
            <link>https://medium.com/snowflake/snowflake-udfs-for-hash-validation-part-2-java-a12c2f093e6d?source=rss-1a3818055dd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a12c2f093e6d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[snowpark]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Dylan Kaufman]]></dc:creator>
            <pubDate>Thu, 20 Jan 2022 17:26:43 GMT</pubDate>
            <atom:updated>2022-01-20T17:26:43.733Z</atom:updated>
            <content:encoded><![CDATA[<p>Snowpark UDFs support Java, Javascript, SQL, <strong>and</strong> Python</p><h4>Recap</h4><p>A few weeks ago, I published an article about helping a customer with a Python function to generate a hash value that would match the MD5_NUMBER_LOWER_64 hash function we support in Snowflake SQL.</p><p><a href="https://medium.com/snowflake/validating-a-python-hash-function-inside-snowflake-3c9255bf6bc4">Validating a Python Hash Function Inside Snowflake</a></p><p>Our customer needs to divide their users more-or-less randomly into roughly equal-size groups, so they want a function that gives them a more-or-less random number based on some user information. They need to do this both inside Snowflake, where they can just use the function we already provide, <em>and</em> outside Snowflake, where they want to use Python. The Python they wrote wasn’t giving the same numbers, so we gave them a Python function that does, and used our new Python UDF feature (still in Private Preview right now) to confirm with some confidence that the results are consistent.</p><h4>Will you…</h4><p>A friend of mine, who shall remain nameless, promptly asked me: “will you create a Java version of the same to help other customer personas?” My initial answer was “probably not,” but then I decided I might as well. Java is a key part of Snowpark, where we allow you to build Java code to suit your requirements, deploy a jar to Snowflake, and then execute that code directly in Snowflake SQL queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxouCsWX6ArO41r0AuypNA.png" /></figure><p>So, back to <a href="https://medium.com/u/10e0a1bfb86b">Yoshi Matsuzaki</a> for the Java version.</p><pre>CREATE OR REPLACE FUNCTION MD5_NUMBER_LOWER64_JAVA(msg VARCHAR)<br>RETURNS NUMBER<br>LANGUAGE JAVA<br>HANDLER=&#39;Example.md5_number_lower64&#39;<br>TARGET_PATH=&#39;@~/example.jar&#39;<br>AS <br>$$<br>import java.security.MessageDigest;<br>import java.security.NoSuchAlgorithmException;<br>import java.nio.charset.StandardCharsets;<br>import java.util.Arrays;<br>import java.math.BigInteger;</pre><pre>class Example {<br>    public static BigInteger md5_number_lower64(String msg) throws NoSuchAlgorithmException {<br>        MessageDigest md = MessageDigest.getInstance(&quot;MD5&quot;);<br>        byte[] rawDigest = md.digest(msg.getBytes(StandardCharsets.UTF_8));<br>        return new BigInteger(1, Arrays.copyOfRange(rawDigest, 8, 16));<br>    }<br>}<br>$$;</pre><p>You can see that this is very similar to the Python version. The initial definition portion tells Snowflake what to call the function, what arguments it takes, what type of value it returns, and where to find it. In this particular case, Yoshi used only functions that are built in to the base Java packages available to the UDFs, and the code for our hash is simple enough to be easily included inline. If we needed custom functions or the actual UDF were very complex, we could deploy custom JAR files (or Python packages) to Snowflake instead.</p><p>The actual Java code is a bit more complex than the Python code, but ultimately it does the same : import some libraries and provide a function to execute. One thing some Java programmers may notice: although the NoSuchAlgorithmException class has to be imported, I haven’t bothered to catch that exception. I know the MD5 algorithm exists, and didn’t want the extra lines. I would’ve removed the import, if I could!</p><p>One little problem we ran into initially: Yoshi’s first Java version didn’t have the 1st argument (1) in the BigInteger constructor. This resulted in Yoshi’s test, using the word ‘Snowflake’, returning the correct result, while my first test, using a few different words, only returned the correct result some of the time.</p><h4>And how’d it do?</h4><p>As before, I ran a simple SQL query to validate the hashes of 598 GPS tracks between the internal function and the Java function (and I left the Python function in as well). At this point, it will come as no surprise that there were no rows returned, meaning that all the Java-generated hash values matched the values from the built-in Snowflake function.</p><pre>SELECT MD5_NUMBER_LOWER64(TRACK) <br>            = MD5_NUMBER_LOWER64_PY(TRACK) PY_MATCH,<br>       MD5_NUMBER_LOWER64(TRACK) <br>            = MD5_NUMBER_LOWER64_JAVA(TRACK) JAVA_MATCH,<br>       COUNT(*) NUM_ROWS<br>FROM RAW_TRACKS<br>GROUP BY PY_MATCH, JAVA_MATCH</pre><p>For these matching queries, I’ve changed the way I’m doing them so that they return a number of rows that match or don’t match; I think this is better than just returning no results.</p><p>For kicks, I also ran the incorrect version and got about 50% correct answers. Considering that the code difference has to do with how the number is represented (signed or two’s complement), that makes sense: slightly more than half of the results in signed ints were negative.</p><p>Next up? The much larger test against the TPCH_SF1000 database, also with no differences:</p><pre>WITH CTE AS (<br>    SELECT c_name || &#39;/&#39; || c_address CUST_ID<br>    FROM SNOWFLAKE_SAMPLE_DATA.TPCH_SF1000.CUSTOMER<br>)<br>SELECT MD5_NUMBER_LOWER64(CUST_ID) <br>           = MD5_NUMBER_LOWER64_JAVA(CUST_ID) MATCH,<br>       COUNT(*) NUM_ROWS<br>FROM CTE<br>GROUP BY MATCH;</pre><p>In this query, I’ve not only changed to the more definitive return of a count of matching rows, I’ve also switched to using a CTE so that I can include the assembly of the &quot;CUST_ID&quot; only one time. In a real use case where there might be multiple columns being collected, a slight mismatch among multiple uses of that calculation might cause mistakes.</p><p>By the way, I probably should mention that Snowflake includes 2 TPC-DS and 4 TPC-H <a href="https://docs.snowflake.com/en/user-guide/sample-data.html">sample data sets</a> available for use in all of our deployments. The TPC-H samples run from 150k customers with 6m line items across 1.5m orders to 150m customers with 6 <em>billion</em><strong><em> </em></strong>line items across 1.5b orders. Couple that with all the data sets available in the <a href="https://www.snowflake.com/data-marketplace/">Snowflake Data Marketplace</a>, some of them free like the COVID-19 data being used to power the State of California’s COVID-19 <a href="https://covid19.ca.gov/">website</a>, and you’ve got a treasure trove of interesting data you can use seamlessly!</p><h4>Need More STATS!</h4><p>My friend, Mr. Nameless, though he knows who he is, also asked “if all the buckets are within 1% of the median, what’s the standard deviation?” and “I wonder how many collisions there are?” He actually wanted to know about collisions with real customer data, but I don’t have that, so I’m sticking with TPC-H.</p><pre>WITH BUCKETS AS (<br>    SELECT MD5_NUMBER_LOWER64(c_name || &#39;/&#39; || c_address) % 1000,<br>           COUNT(*) users<br>    FROM SNOWFLAKE_SAMPLE_DATA.TPCH_SF1000.CUSTOMER<br>    GROUP BY 1)<br>SELECT MEDIAN(users) - AVG(users) &quot;MEDIAN DEV&quot;, <br>        MIN(users) - AVG(users) &quot;MIN DEV&quot;, <br>        MAX(users) - AVG(users) &quot;MAX DEV&quot;, <br>        ROUND(STDDEV(users)) &quot;STDDEV&quot; FROM BUCKETS;</pre><p>This query tells us the deviation of the median, smallest, and largest buckets from the precise average of 150,000 customers per bucket, as well as the standard deviation. Note that, in this case, I do need the double quotation marks around 3 of the column aliases, since I chose to include spaces in those names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8nlhykbx3cQHYKKgBKMB4A.png" /></figure><p>Now, to be clear, I picked 1000 buckets because it was convenient. We could have used a larger or smaller number, or we could even have computed a number of buckets based on the approximate number of people we wanted in each.</p><p>Meanwhile, the following query returns no rows, telling us that there are no hash collisions among 150 million essentially random strings. I also ran it against the 10,000 scale factor version of TPC_H, which has 1.5 <em>billion</em> customer records and also got no collisions.</p><pre>SELECT MD5_NUMBER_LOWER64(c_name || &#39;/&#39; || c_address), <br>       COUNT(*) users<br>FROM SNOWFLAKE_SAMPLE_DATA.TPCH_SF1000.CUSTOMER<br>GROUP BY 1<br>HAVING COUNT(*) &gt; 1</pre><h4>Let me Sum Up</h4><p>The Python and Java UDFs I’ve presented are meant both as examples of how to use custom UDFs in Snowflake, as well as how UDFs can help avoid having to move data into or out of Snowflake for validation purposes. These hash values can be used for validating, grouping, or even keying data¹, so knowing that the Python and Java functions can be used outside of Snowflake to generate the same hash is very useful for this customer’s use case.</p><p>¹ There is a risk of collisions with MD5, so some people may worry that it isn’t ideal for keying, but the likelihood of a collision is pretty low. MD5 hashes are commonly used as keys in Data Vault modeling, for example.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a12c2f093e6d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/snowflake-udfs-for-hash-validation-part-2-java-a12c2f093e6d">Snowflake UDFs for Hash Validation, Part 2: Java</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validating a Python Hash Function Inside Snowflake]]></title>
            <link>https://medium.com/snowflake/validating-a-python-hash-function-inside-snowflake-3c9255bf6bc4?source=rss-1a3818055dd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c9255bf6bc4</guid>
            <category><![CDATA[snowpark]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Dylan Kaufman]]></dc:creator>
            <pubDate>Thu, 16 Dec 2021 17:02:39 GMT</pubDate>
            <atom:updated>2022-01-20T19:54:01.315Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Snowpark with Python to group users</h4><h4>Generating Even Buckets Based on a Hash</h4><p>A customer of mine uses <a href="https://en.wikipedia.org/wiki/MD5">MD5 hashing</a> to group their users into a bunch of groups, randomly but fairly evenly. The idea here is that the hash will be unique if computed across enough pieces of user information to define a unique key for the user. Applying a modulo division function to the effectively random value of the hash as an integer will put each person into one of some number of buckets at random. The distribution may not be perfectly even, but it’ll probably be pretty close across enough users.</p><p>Crucially, my customer also needs to be able to do this both inside Snowflake, and outside Snowflake so that they have the same hash values, and the same buckets.</p><p>It’s important to understand that although MD5 was originally intended for cryptographic purposes, it isn’t secure enough for that use any longer. It can still be used for my customer’s bucketing use case, which is very similar to the common partitioning usage in <a href="https://www.snowflake.com/data-warehousing-glossary/data-vault/">Data Vault</a> data modeling, among others.</p><p>It can also still be used to identify corruption in files, as is commonly done with software downloads, including our drivers and connectors: download the file and the MD5 hash, run the MD5 function against the file yourself and compare it to the original hash. Although the hash values aren’t guaranteed to be unique for different inputs, if you get the same value as the one you downloaded, the file most likely hasn’t been corrupted.</p><p>As a really quick example of how to do this, I used the MD5_NUMBER_LOWER64 hash function. I picked that one because it directly returns an integer, rather than a hex string.</p><p>In this example, I ran it on two strings, one with my name and one with another name followed by company name and company address. One could easily imagine having a bunch of other information in the input string, such as title, phone number, etc. Presumably, it would be as many attributes as necessary to form a fairly unique key for the user.</p><pre>SELECT &#39;Me&#39; &quot;WHO&quot;, MD5_NUMBER_LOWER64(&#39;Dylan Kaufman/Snowflake/450 Concar Dr, San Mateo, CA 94402&#39;) &quot;HASH&quot;<br>UNION<br>SELECT &#39;Mgr&#39;, MD5_NUMBER_LOWER64(&#39;Alex Rottinghuis/Snowflake/450 Concar Dr, San Mateo, CA 94402&#39;);</pre><figure><img alt="Table showing output of example query." src="https://cdn-images-1.medium.com/max/844/1*zTuaouQCLsGRCGxith2wPQ.png" /><figcaption>Snowsight output of the example query</figcaption></figure><p>Supposing we want 1000 buckets of users, since “mod 1000” is very easy to do in your head, that would put me in bucket 378 and Alex in bucket 664. If we only wanted 750 groups, we’d use MOD(&quot;HASH&quot;,750) and then I’d be in group 128 and Alex in 414.</p><p>This is all well and good, but as I mentioned before, my customer needs to be able to generate the exact same hash <em>outside of</em> Snowflake as well. They were trying to do this in Python themselves, but were not getting the same results as generated by our LOWER64 function. Then they asked me for help.</p><h4>MD5 Hashing Support in Snowflake SQL</h4><p>Snowflake supports a few <a href="https://docs.snowflake.com/en/sql-reference/functions/md5.html">MD5 hashing functions</a>. The standard MD5 function returns a hexadecimal string, as does MD5_HEX. MD5_BINARY returns it as a binary string, which we default to displaying as a hexadecimal string (differing from the MD5/MD5_HEX version only in that it uses capital letters, rather than all lower-case). We also have the MD5_NUMBER_LOWER64 and MD5_NUMBER_UPPER64 versions, which return part of the hash as an integer, as I showed earlier with the MD5_NUMBER_LOWER64 function.</p><p>This SQL script shows the output of each of those functions (I left out MD5_HEX, since it is the same as MD5), using the very cool UNPIVOT function to convert it into an easier format for reading here.</p><pre>SET ME = &#39;Dylan Kaufman/Snowflake/450 Concar Dr, San Mateo, CA 94402&#39;;</pre><pre>WITH CTE AS (<br>  SELECT MD5($ME) &quot;MD5&quot;,<br>    TO_VARCHAR(MD5_BINARY($ME)) &quot;MD5_BINARY&quot;,<br>    TO_VARCHAR(MD5_NUMBER_UPPER64($ME)) &quot;MD5_NUMBER_UPPER64&quot;,<br>    TO_VARCHAR(MD5_NUMBER_LOWER64($ME)) &quot;MD5_NUMBER_LOWER64&quot;<br> )<br>SELECT * FROM CTE<br>  UNPIVOT(&quot;HASH&quot; FOR &quot;FUNCTION&quot; IN <br>         (MD5, MD5_BINARY, MD5_NUMBER_UPPER64, MD5_NUMBER_LOWER64));</pre><figure><img alt="Table showing output of four different MD5 hash functions" src="https://cdn-images-1.medium.com/max/1024/1*9IOlVBJUbGD9GGAUlSQFtg.png" /><figcaption>Output of 4 different MD5 hash functions</figcaption></figure><p>It is perhaps worth mentioning that Snowflake also supports cryptographically secure hashing with <a href="https://docs.snowflake.com/en/sql-reference/functions/sha1.html">SHA1</a> and <a href="https://docs.snowflake.com/en/sql-reference/functions/sha2.html">SHA2</a>, each of which also has a _BINARY version. Also, when you’re using these functions, though I didn’t bother to do it here, you may want to TRIM your input strings to make sure there’s no whitespace at the end of it; that whitespace will not be easy to see when you’re looking at the data, and it <em>will</em> affect the hash. If you’re trying to compare the output between two systems and one of them isn’t trimming, you’re going to get a little frustrated!</p><p>Since the customer needs to do this in Python, they need either to figure out how to fix their implementation or to start using one that is known to work. I asked around internally about whether we had a Python example I could pass along and soon had a small Python script from <a href="https://medium.com/u/10e0a1bfb86b">Yoshi Matsuzaki</a>, complete with the matching outputs of a single run each, of Yoshi’s Python script and of our internal function. <a href="https://medium.com/u/279fe54c149a">Felipe Hoffa</a> promptly turned that example into a <a href="https://stackoverflow.com/questions/70266037/match-snowflake-md5-to-python-md5/70266038#70266038">Stack Overflow</a> post.</p><p>One thing that concerned me, though, was the very small sample size in the example. Does doing a single hash on one word prove that the little Python implementation will consistently return the same value as the built-in function?</p><p>I don’t actually know how far off the results were for my customer. For all I know, the results from their code are different on every input and getting the right result on one input is sufficient. On the assumption that their code sometimes gives the same result, I decided that I should run some other tests to try to get more certainty.</p><h4>Generating Some Hash Values to Test</h4><p>As it happens, I have 598 GPS tracks from bike rides, recorded on a Garmin GPS or with the Strava app, already loaded into a table. The XML of the .gpx and .tcx files is stored in a VARIANT column, and they range in size from 1,887 bytes (must’ve been a very short ride!!) to almost 46 MB. The Snowflake VARIANT column converts automatically to a string, so running it through one of the MD5 functions is trivial:</p><pre>SELECT MD5_NUMBER_LOWER64(TRACK) FROM RAW_TRACKS;</pre><p>The output of that function, which I’m not going to bother showing here, is unsurprisingly, 598 integer values. Throwing a DISTINCT on there still got me 598, so I know they’re unique. It’s important to remember that MD5 isn’t guaranteed unique.</p><p>Now I need to run the same XML strings through a Python function to do the same thing, and I need to be able to tie the output of the Python function to the output of the Snowflake function so that I can tell whether they’re the same.</p><p>I don’t yet have the names of the files associated with their rows in the RAW_TRACKS table, so writing a Python program on my computer to generate a list of file names and hashes and then doing something to compare that to the list from Snowflake isn’t really practical right now.</p><h4>Generating Hashes using Python inside Snowflake</h4><p>Instead, what better way than to run the Python code directly inside Snowflake, against the same table, using Snowflake Python UDFs? Python UDFs, part of <a href="https://www.snowflake.com/blog/snowday-python-comes-to-snowpark/">Snowpark</a>, are a new feature currently in Private Preview, so not yet available to everyone. As the name suggests, this new feature allows users to create user-defined functions that use Python code; as shown in the diagram below, creating a UDF with Python installs Python bytecode into a secure sandbox for execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oA2vuEN-6KzMqHbPVJMs6A.png" /><figcaption>Basic Python UDF operation diagram in Snowflake</figcaption></figure><p>Here is what the SQL code to create the Python UDF looks like in <a href="https://docs.snowflake.com/en/user-guide/ui-snowsight.html">Snowsight</a>, with syntax highlighting, at least for the SQL parts. You can also find it farther down in this article if you want to copy it.</p><figure><img alt="Screenshot from Snowsight of the Python UDF with syntax highlighting" src="https://cdn-images-1.medium.com/max/1024/1*JPVDGQ969dM16s4h-BE29w.png" /><figcaption>SQL code to create the Python UDF</figcaption></figure><p>The first part of this code is similar to <a href="https://docs.snowflake.com/en/sql-reference/sql/create-function.html">creating functions</a> in the other languages we already support: SQL, Javascript, and Java. That section:</p><ol><li>names the function,</li><li>provides the input argument names and types,</li><li>specifies the return type,</li><li>identifies the language (not necessary for SQL)</li><li>the runtime version (for Python)</li><li>and the name of the handler function in the code (for Python and Java), since the code may include many functions</li></ol><p>The rest of the code, between the $$ markers, is the actual Python code. As you can see that code is pretty simple. The md5 function comes right out of Python’s built-inhashliblibrary, and we have to encode the input, hash it, and then manipulate the result a little to get the lower 64 bits of numeric data and return that number as an integer.</p><h4>Validating the Hashes with a SQL Query</h4><p>Now that I have the Python UDF created, it’s a simple matter to create a query that computes the hash using both the built-inMD5_NUMBER_LOWER64 function and the UDF and returns only those combinations that don’t match:</p><pre>SELECT MD5_NUMBER_LOWER64(TRACK) INTERNAL, <br>       MD5_NUMBER_LOWER64_PY(TRACK) UDF<br>FROM RAW_TRACKS<br>WHERE &quot;INTERNAL&quot; &lt;&gt; &quot;UDF&quot;;</pre><p>I ran this against all 598 GPS tracks, and didn’t get back any rows, so we now know that all the hashes are the same, at least for these few sample strings.</p><p>598 GPS tracks isn’t really all that big a sample size… I wonder if we can do a much larger data set? Not as if we don’t have plenty available. For example, Snowflake shares a SAMPLE_DATA database with every account. This database includes several different sizes of the TPC-H and TPC-DS testing databases, which can have huge amounts of data in them. I decided to use TPC-H SF1000, which has a customer table consisting of 150 million randomly generated customer names and addresses.</p><p>The customer names are “Customer#” followed by a number and the addresses are completely random text. When combined, this gives us 150 million unique text values such as Customer#044207085/9ON0dUnisbCaXsMDB3XBFrhmAWWPWWkSr33. After running the query below, there are still no mismatches between the internal function and the Python UDF, so while still not definitive proof that they will always return the same value, it’s enough to make me feel pretty confident.</p><pre>SELECT MD5_NUMBER_LOWER64(c_name || &#39;/&#39; || c_address) INTERNAL, <br>       MD5_NUMBER_LOWER64_PY(c_name || &#39;/&#39; || c_address) UDF<br>FROM SNOWFLAKE_SAMPLE_DATA.TPCH_SF1000.CUSTOMER<br>WHERE &quot;INTERNAL&quot; &lt;&gt; &quot;UDF&quot;;</pre><p>Oh, and going back to my comment earlier about not getting perfectly even groups out of this, I ran another query to see how many of our TPC-H customers fall into each of the 1000 buckets:</p><pre>SELECT MD5_NUMBER_LOWER64(c_name || &#39;/&#39; || c_address) % 1000,          <br>       COUNT(*)<br>FROM SNOWFLAKE_SAMPLE_DATA.TPCH_SF1000.CUSTOMER<br>GROUP BY 1<br>ORDER BY 2;</pre><p>The resulting buckets contain from 148,572 to 151,156 users per bucket, with a median of 149,998. Every bucket is within 1% of the average of 150k.</p><p>Here’s the code for the UDF in-line in case you want to copy it:</p><pre>CREATE OR REPLACE FUNCTION MD5_NUMBER_LOWER64_PY(msg STRING)<br>RETURNS INTEGER<br>LANGUAGE PYTHON<br>RUNTIME_VERSION=3.8<br>HANDLER = &#39;COMPUTE_HASH&#39;<br>AS<br>$$<br>import hashlib<br>def compute_hash(msg):<br>   return int.from_bytes(hashlib.md5(msg.encode(&#39;utf-8&#39;)).digest()[8:], &#39;big&#39;)<br>$$;</pre><p>And don’t worry, I’ll be adding the .fit files from my Garmin as well, but those are binary and require more conversion to be useful, so I haven’t gotten to them yet. That’s a story for another day, though.</p><h4>Updates</h4><p>A colleague pointed out that using VALUES can make for simpler queries in some of my examples above.</p><pre>SELECT $1 AS WHO, <br>       MD5_NUMBER_LOWER64($2) AS HASH<br>FROM VALUES<br>       (&#39;Me&#39;, &#39;Dylan Kaufman/Snowflake/450 Concar Dr, San Mateo, CA 94402&#39;),<br>       (&#39;Mgr&#39;, &#39;Alex Rottinghuis/Snowflake/450 Concar Dr, San Mateo, CA 94402&#39;);</pre><p>In this case, using two rows of VALUES allows me to avoid the UNION I used, or UNION ALL, which is technically more efficient when you know there are no duplicate rows.</p><p>Similarly, VALUES allows a single statement where I originally used a SET command and then embedded a variable in the query:</p><pre>WITH CTE AS (<br>  SELECT MD5($1) MD5,<br>    TO_VARCHAR(MD5_BINARY($1)) MD5_BINARY,<br>    TO_VARCHAR(MD5_NUMBER_UPPER64($1)) MD5_NUMBER_UPPER64,<br>    TO_VARCHAR(MD5_NUMBER_LOWER64($1)) MD5_NUMBER_LOWER64<br>    FROM VALUES<br>      (&#39;Dylan Kaufman/Snowflake/450 Concar Dr, San Mateo, CA 94402&#39;)<br> )<br>SELECT * FROM CTE<br>  UNPIVOT(HASH FOR FUNCTION IN <br>         (MD5, MD5_BINARY, MD5_NUMBER_UPPER64, MD5_NUMBER_LOWER64));</pre><p>His version of the matching query will always give some result, either showing that all the samples match, or showing how many do and how many don’t, rather than returning no rows like mine:</p><pre>SELECT (MD5_NUMBER_LOWER64(TRACK) = MD5_NUMBER_LOWER64_PY(TRACK)) AS IS_MD5_MATCH,<br>       COUNT(*) AS NUM_ROWS<br>FROM RAW_TRACKS<br>GROUP BY 1<br>ORDER BY 1;</pre><p>Also, I used double-quotes &quot; to mark various identifiers, which wasn’t really necessary.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c9255bf6bc4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/validating-a-python-hash-function-inside-snowflake-3c9255bf6bc4">Validating a Python Hash Function Inside Snowflake</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>