{"id":391,"date":"2020-07-29T23:40:07","date_gmt":"2020-07-29T23:40:07","guid":{"rendered":"https:\/\/snowflake.pavlik.us\/?p=391"},"modified":"2021-05-25T12:58:49","modified_gmt":"2021-05-25T12:58:49","slug":"getting-snowflake-primary-key-columns-as-a-table","status":"publish","type":"post","link":"https:\/\/snowflake.pavlik.us\/index.php\/2020\/07\/29\/getting-snowflake-primary-key-columns-as-a-table\/","title":{"rendered":"Getting Snowflake Primary Key Columns as a Table"},"content":{"rendered":"\n<p>One of my customers had an interesting requirement. In order to dynamically create merge statements, they needed a way to collect the primary key columns for any given table. After discussing some options &#8212; returning them as a delimited string, array, etc., we agreed that returning the columns in a table is the best option. <\/p>\n\n\n\n<p>This User Defined Table Function (UDTF) returns the columns for a table&#8217;s primary key. The UDTF will return a table with a single column, each row in the table is one of the columns in the input table&#8217;s primary key. If there is no primary key, the table will have no rows. For a single-column primary key, the table will have the one row, and for composite primary keys it will return all columns in the key.<\/p>\n\n\n\n<p>One thing you may notice is that the input to the UDTF is the table&#8217;s DDL, not just the table&#8217;s name. The reason for this is because UDTFs cannot execute SQL. The simplest way to handle this situation is to nest the GET_DDL function as the parameter for the GET_PK_COLUMNS function. You can see how this works in the code samp<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncreate database DB_Primary_Keys;\n\n\/**************************************************************************************************************\n*                                                                                                             *\n*  Set up test tables with four types of primary key: Named composite, unnamed composite, inline, and none.   * \n*                                                                                                             *\n**************************************************************************************************************\/\n \n-- Named multi-column PK\ncreate or replace temporary table table1\n(\ncolumn_name1 number NOT NULL,\ncolumn_name2 number NOT NULL,\ncolumn_name3 string,\nCONSTRAINT Constraint_name PRIMARY KEY (column_name1, column_name2)\n);\n \n-- Unnamed multi-column PK\ncreate temporary table table2\n(\ncolumn_name1 number NOT NULL,\ncolumn_name2 number NOT NULL,\ncolumn_name3 string,\nPRIMARY KEY (column_name1, column_name2)\n);\n \n-- Inline single-column PK\ncreate or replace temporary table table3\n(\ncolumn_name1 number primary key,\ncolumn_name2 number NOT NULL,\ncolumn_name3 string\n);\n \n-- No PK defined\ncreate or replace temporary table table4\n(\ncolumn_name1 number,\ncolumn_name2 number,\ncolumn_name3 string\n);\n \n\/********************************************************************************************************\n*                                                                                                       *\n* User defined table function (UDTF) to get primary keys for a table.                                   *\n*                                                                                                       *\n* @param  {string}:  TABLE_DDL    The DDL for the table to get the PKs. Usually use get_ddl.            *\n* @return {table}:                A table with the columns comprising the table&#039;s primary key           *\n*                                                                                                       *\n********************************************************************************************************\/\ncreate or replace function GET_PK_COLUMNS(TABLE_DDL string)\nreturns table (PK_COLUMN string)\nlanguage javascript\nas\n$$\n{\n    processRow: function get_params(row, rowWriter, context){\n        var pkCols = getPKs(row.TABLE_DDL);\n        for (i = 0; i &amp;lt; pkCols.length; i++) {\n            rowWriter.writeRow({PK_COLUMN: pkCols&#x5B;i]}); \n        }\n         \n        function getPKs(tableDDL) {\n            var c;\n            var keyword = &quot;primary key&quot;;\n            var ins = -1;\n            var s = tableDDL.split(&quot;\\n&quot;);\n            for (var i = 0; i &amp;lt; s.length; i++) {  \n                ins = s&#x5B;i].indexOf(keyword);\n                if (ins != -1) {\n                    var colList = s&#x5B;i].substring(ins + keyword.length);\n                    colList = colList.replace(&quot;(&quot;, &quot;&quot;);\n                    colList = colList.replace(&quot;)&quot;, &quot;&quot;);\n                    var colArray = colList.split(&quot;,&quot;);\n                    for (pkc = 0; c &amp;lt; colArray.length; pkc++) {\n                        colArray&#x5B;pkc] = colArray&#x5B;pkc].trim();\n                    }\n                    return colArray;\n                }\n            }\n            return &#x5B;];  \/\/ No PK\n        }\n    }\n}\n$$;\n \n\/**************************************************************************************************************\n*                                                                                                             *\n*  Test execution of the UDTF.                                                                                * \n*                                                                                                             *\n**************************************************************************************************************\/\n \nselect * from table(get_pk_columns(get_ddl(&#039;table&#039;, &#039;table1&#039;))) PKS;  -- Multi-column PK with named constraint\nselect * from table(get_pk_columns(get_ddl(&#039;table&#039;, &#039;table2&#039;))) PKS;  -- Multi-column PK with no name for constraint\nselect * from table(get_pk_columns(get_ddl(&#039;table&#039;, &#039;table3&#039;))) PKS;  -- Single column PK inline definition\nselect * from table(get_pk_columns(get_ddl(&#039;table&#039;, &#039;table4&#039;))) PKS;  -- No PKs\n<\/pre><\/div>","protected":false},"excerpt":{"rendered":"<p>One of my customers had an interesting requirement. In order to dynamically create merge statements, they needed a way to collect the primary key columns for any given table. After discussing some options &#8212; returning them as a delimited string, array, etc., we agreed that returning the columns in a table is the best option. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7,1],"tags":[],"class_list":["post-391","post","type-post","status-publish","format-standard","hentry","category-udf-sql","category-uncategorized"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.3 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\r\n<title>Getting Snowflake Primary Key Columns as a Table - Snowflake in the Carolinas<\/title>\r\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\r\n<link rel=\"canonical\" href=\"https:\/\/snowflake.pavlik.us\/index.php\/2020\/07\/29\/getting-snowflake-primary-key-columns-as-a-table\/\" \/>\r\n<meta property=\"og:locale\" content=\"en_US\" \/>\r\n<meta property=\"og:type\" content=\"article\" \/>\r\n<meta property=\"og:title\" content=\"Getting Snowflake Primary Key Columns as a Table - Snowflake in the Carolinas\" \/>\r\n<meta property=\"og:description\" content=\"One of my customers had an interesting requirement. In order to dynamically create merge statements, they needed a way to collect the primary key columns for any given table. After discussing some options &#8212; returning them as a delimited string, array, etc., we agreed that returning the columns in a table is the best option. [&hellip;]\" \/>\r\n<meta property=\"og:url\" content=\"https:\/\/snowflake.pavlik.us\/index.php\/2020\/07\/29\/getting-snowflake-primary-key-columns-as-a-table\/\" \/>\r\n<meta property=\"og:site_name\" content=\"Snowflake in the Carolinas\" \/>\r\n<meta property=\"article:published_time\" content=\"2020-07-29T23:40:07+00:00\" \/>\r\n<meta property=\"article:modified_time\" content=\"2021-05-25T12:58:49+00:00\" \/>\r\n<meta name=\"author\" content=\"Greg Pavlik\" \/>\r\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\r\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Greg Pavlik\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\r\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/snowflake.pavlik.us\\\/index.php\\\/2020\\\/07\\\/29\\\/getting-snowflake-primary-key-columns-as-a-table\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/snowflake.pavlik.us\\\/index.php\\\/2020\\\/07\\\/29\\\/getting-snowflake-primary-key-columns-as-a-table\\\/\"},\"author\":{\"name\":\"Greg Pavlik\",\"@id\":\"https:\\\/\\\/snowflake.pavlik.us\\\/#\\\/schema\\\/person\\\/019455f4675665b6cf5edea31ec44d7b\"},\"headline\":\"Getting Snowflake Primary Key Columns as a Table\",\"datePublished\":\"2020-07-29T23:40:07+00:00\",\"dateModified\":\"2021-05-25T12:58:49+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/snowflake.pavlik.us\\\/index.php\\\/2020\\\/07\\\/29\\\/getting-snowflake-primary-key-columns-as-a-table\\\/\"},\"wordCount\":208,\"commentCount\":0,\"articleSection\":[\"UDF\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/snowflake.pavlik.us\\\/index.php\\\/2020\\\/07\\\/29\\\/getting-snowflake-primary-key-columns-as-a-table\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/snowflake.pavlik.us\\\/index.php\\\/2020\\\/07\\\/29\\\/getting-snowflake-primary-key-columns-as-a-table\\\/\",\"url\":\"https:\\\/\\\/snowflake.pavlik.us\\\/index.php\\\/2020\\\/07\\\/29\\\/getting-snowflake-primary-key-columns-as-a-table\\\/\",\"name\":\"Getting Snowflake Primary Key Columns as a Table - Snowflake in the Carolinas\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/snowflake.pavlik.us\\\/#website\"},\"datePublished\":\"2020-07-29T23:40:07+00:00\",\"dateModified\":\"2021-05-25T12:58:49+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/snowflake.pavlik.us\\\/#\\\/schema\\\/person\\\/019455f4675665b6cf5edea31ec44d7b\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/snowflake.pavlik.us\\\/index.php\\\/2020\\\/07\\\/29\\\/getting-snowflake-primary-key-columns-as-a-table\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/snowflake.pavlik.us\\\/index.php\\\/2020\\\/07\\\/29\\\/getting-snowflake-primary-key-columns-as-a-table\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/snowflake.pavlik.us\\\/index.php\\\/2020\\\/07\\\/29\\\/getting-snowflake-primary-key-columns-as-a-table\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/snowflake.pavlik.us\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Getting Snowflake Primary Key Columns as a Table\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/snowflake.pavlik.us\\\/#website\",\"url\":\"https:\\\/\\\/snowflake.pavlik.us\\\/\",\"name\":\"Snowflake in the Carolinas\",\"description\":\"Random thoughts on all things Snowflake in the Carolinas\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/snowflake.pavlik.us\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/snowflake.pavlik.us\\\/#\\\/schema\\\/person\\\/019455f4675665b6cf5edea31ec44d7b\",\"name\":\"Greg Pavlik\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/d81df729eebf37a042922b17d4a4c834b1e0ccfa9fea1c2c78cb8e95c7e91701?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/d81df729eebf37a042922b17d4a4c834b1e0ccfa9fea1c2c78cb8e95c7e91701?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/d81df729eebf37a042922b17d4a4c834b1e0ccfa9fea1c2c78cb8e95c7e91701?s=96&d=mm&r=g\",\"caption\":\"Greg Pavlik\"},\"description\":\"Greg is a Senior Sales Engineer at Snowflake Computing, in the Raleigh-Durham area. He's been in data management and security for the twenty years.\"}]}<\/script>\r\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Getting Snowflake Primary Key Columns as a Table - Snowflake in the Carolinas","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/snowflake.pavlik.us\/index.php\/2020\/07\/29\/getting-snowflake-primary-key-columns-as-a-table\/","og_locale":"en_US","og_type":"article","og_title":"Getting Snowflake Primary Key Columns as a Table - Snowflake in the Carolinas","og_description":"One of my customers had an interesting requirement. In order to dynamically create merge statements, they needed a way to collect the primary key columns for any given table. After discussing some options &#8212; returning them as a delimited string, array, etc., we agreed that returning the columns in a table is the best option. [&hellip;]","og_url":"https:\/\/snowflake.pavlik.us\/index.php\/2020\/07\/29\/getting-snowflake-primary-key-columns-as-a-table\/","og_site_name":"Snowflake in the Carolinas","article_published_time":"2020-07-29T23:40:07+00:00","article_modified_time":"2021-05-25T12:58:49+00:00","author":"Greg Pavlik","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Greg Pavlik","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/snowflake.pavlik.us\/index.php\/2020\/07\/29\/getting-snowflake-primary-key-columns-as-a-table\/#article","isPartOf":{"@id":"https:\/\/snowflake.pavlik.us\/index.php\/2020\/07\/29\/getting-snowflake-primary-key-columns-as-a-table\/"},"author":{"name":"Greg Pavlik","@id":"https:\/\/snowflake.pavlik.us\/#\/schema\/person\/019455f4675665b6cf5edea31ec44d7b"},"headline":"Getting Snowflake Primary Key Columns as a Table","datePublished":"2020-07-29T23:40:07+00:00","dateModified":"2021-05-25T12:58:49+00:00","mainEntityOfPage":{"@id":"https:\/\/snowflake.pavlik.us\/index.php\/2020\/07\/29\/getting-snowflake-primary-key-columns-as-a-table\/"},"wordCount":208,"commentCount":0,"articleSection":["UDF"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/snowflake.pavlik.us\/index.php\/2020\/07\/29\/getting-snowflake-primary-key-columns-as-a-table\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/snowflake.pavlik.us\/index.php\/2020\/07\/29\/getting-snowflake-primary-key-columns-as-a-table\/","url":"https:\/\/snowflake.pavlik.us\/index.php\/2020\/07\/29\/getting-snowflake-primary-key-columns-as-a-table\/","name":"Getting Snowflake Primary Key Columns as a Table - Snowflake in the Carolinas","isPartOf":{"@id":"https:\/\/snowflake.pavlik.us\/#website"},"datePublished":"2020-07-29T23:40:07+00:00","dateModified":"2021-05-25T12:58:49+00:00","author":{"@id":"https:\/\/snowflake.pavlik.us\/#\/schema\/person\/019455f4675665b6cf5edea31ec44d7b"},"breadcrumb":{"@id":"https:\/\/snowflake.pavlik.us\/index.php\/2020\/07\/29\/getting-snowflake-primary-key-columns-as-a-table\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/snowflake.pavlik.us\/index.php\/2020\/07\/29\/getting-snowflake-primary-key-columns-as-a-table\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/snowflake.pavlik.us\/index.php\/2020\/07\/29\/getting-snowflake-primary-key-columns-as-a-table\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/snowflake.pavlik.us\/"},{"@type":"ListItem","position":2,"name":"Getting Snowflake Primary Key Columns as a Table"}]},{"@type":"WebSite","@id":"https:\/\/snowflake.pavlik.us\/#website","url":"https:\/\/snowflake.pavlik.us\/","name":"Snowflake in the Carolinas","description":"Random thoughts on all things Snowflake in the Carolinas","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/snowflake.pavlik.us\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/snowflake.pavlik.us\/#\/schema\/person\/019455f4675665b6cf5edea31ec44d7b","name":"Greg Pavlik","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/d81df729eebf37a042922b17d4a4c834b1e0ccfa9fea1c2c78cb8e95c7e91701?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/d81df729eebf37a042922b17d4a4c834b1e0ccfa9fea1c2c78cb8e95c7e91701?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/d81df729eebf37a042922b17d4a4c834b1e0ccfa9fea1c2c78cb8e95c7e91701?s=96&d=mm&r=g","caption":"Greg Pavlik"},"description":"Greg is a Senior Sales Engineer at Snowflake Computing, in the Raleigh-Durham area. He's been in data management and security for the twenty years."}]}},"_links":{"self":[{"href":"https:\/\/snowflake.pavlik.us\/index.php\/wp-json\/wp\/v2\/posts\/391","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/snowflake.pavlik.us\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/snowflake.pavlik.us\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/snowflake.pavlik.us\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/snowflake.pavlik.us\/index.php\/wp-json\/wp\/v2\/comments?post=391"}],"version-history":[{"count":11,"href":"https:\/\/snowflake.pavlik.us\/index.php\/wp-json\/wp\/v2\/posts\/391\/revisions"}],"predecessor-version":[{"id":497,"href":"https:\/\/snowflake.pavlik.us\/index.php\/wp-json\/wp\/v2\/posts\/391\/revisions\/497"}],"wp:attachment":[{"href":"https:\/\/snowflake.pavlik.us\/index.php\/wp-json\/wp\/v2\/media?parent=391"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/snowflake.pavlik.us\/index.php\/wp-json\/wp\/v2\/categories?post=391"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/snowflake.pavlik.us\/index.php\/wp-json\/wp\/v2\/tags?post=391"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}