<?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 Philip Carrington on Medium]]></title>
        <description><![CDATA[Stories by Philip Carrington on Medium]]></description>
        <link>https://medium.com/@philipcarrington?source=rss-7dc96449847d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*guL2-BegmuDIDide.</url>
            <title>Stories by Philip Carrington on Medium</title>
            <link>https://medium.com/@philipcarrington?source=rss-7dc96449847d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 01:57:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@philipcarrington/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[When WITH:]]></title>
            <link>https://medium.com/@philipcarrington/when-with-597d1f989d70?source=rss-7dc96449847d------2</link>
            <guid isPermaLink="false">https://medium.com/p/597d1f989d70</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[views]]></category>
            <category><![CDATA[database-development]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Philip Carrington]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 11:04:21 GMT</pubDate>
            <atom:updated>2020-06-16T11:04:21.416Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@philipcarrington/why-with-a636058a56c8">Previously</a> I wrote about How <strong>WITH</strong> now we will look simply at the When it could be useful. Here we are going to look at creating “create view” code through SQL using <strong>WITH’s</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lZbFRxIEh2cF9F_l" /><figcaption>Photo by <a href="https://unsplash.com/@treesoftheplanet?utm_source=medium&amp;utm_medium=referral">Niklas Weiss</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is the premise:</h3><p>I am working on a personal project and I needed to denormalise the database I had designed to make the next stage of the project easier. The denormalisation was simply because I would not have to continuously keep writing the <strong>JOIN’s</strong> and <strong>FROM’s</strong> for what I needed to do and would be pretty interesting I thought as well</p><p>The database I am using is MySQL but I hope with a little tweaking then you could use at least the design pattern against many on the RDBMS’s that have meta data</p><h3>Getting Meta:</h3><p>Meta data in MySQL is stored in the <strong>information_schema </strong>tables. Here we are pretty much exclusively going to use two tables:</p><pre>information_schema.key_column_usage<br>information_schema.columns</pre><p>There are <a href="https://dev.mysql.com/doc/refman/8.0/en/information-schema.html">loads</a> more though that you could use for purposes!</p><h3>Get the tables we are interested in:</h3><p>The tables in the information_schema are all the tables in your database generally, and this is the case in MySQL. So you can run something like:</p><pre><strong>select *<br>from </strong>information_schema.key_column_usage<strong> </strong>kcu<br><strong>where </strong>kcu.constraint_schema<strong> </strong>= &#39;&lt;Your database (schema) name&gt;&#39;</pre><p>And you will get a data back on the columns that are in the tables of the desired schema and if they are used in any type of database constraint (e.g. a Primary Key, Foreign Key (FK), Unique Key etc)</p><p>I have a standard in my DB’s as much as possible that if there is a Foreign Key it is identified in the nam with the prefix of <em>‘fk_’ </em>so extending the above:</p><pre><strong>select *<br>from </strong>information_schema.key_column_usage<strong> </strong>kcu<br><strong>where </strong>kcu.constraint_schema<strong> </strong>= <strong> </strong>= &#39;&lt;Your database (schema) name&gt;&#39;<br>    <strong>and </strong>kcu.constraint_name<strong> like </strong>&#39;fk_%&#39;</pre><p>This gets rows showing the tables that are the child and parents in the FK’s. In other databases the FK’s are better marked, in MySQL then this is the best way I have found, but I am not a expert expert on MySQL.</p><h4>Getting important data:</h4><p>Lets first create a table:</p><pre><strong>drop table </strong>denormalise_tables_data;<br><br><strong>create table </strong>denormalise_tables_data (<br>    table_no                    <strong>int</strong>,<br>    table_schema                <strong>varchar</strong>(255),<br>    <strong>table_name                  varchar</strong>(255),<br>    table_acronym               <strong>varchar</strong>(10),<br>    table_aliased_columns       <strong>varchar</strong>(1000)<br>);</pre><p>This will be used to store the information that we will use later to save us from having a too large SQL statement in the final stage. I am giving all the tables a number so that it is easier to <strong>JOIN </strong>as well, it also means that I can use it to differentiate between tables that acronym to the same value.</p><pre><strong>set </strong>@row_number:=0;<br><br><strong>insert into </strong>denormalise_tables_data<br><strong>with <br>    </strong>tables_with_acronyms <strong>as </strong>(<br>        <strong>select </strong>@row_number:=@row_number + 1 <strong>as </strong>table_no,<br>               rel_table_base.table_schema,                           <br>               rel_table_base.table_name,<br>               rel_table_base.table_acronym<br>        <strong>from </strong>(                    <br>            <strong>select </strong>kcu.table_schema,<br>                   kcu.table_name,<br>                   acronym(kcu.table_name) <strong>as </strong>table_acronym                                                                             <br>            <strong>from </strong>information_schema.key_column_usage<strong> </strong>kcu<br>            <strong>where </strong>kcu.constraint_schema<strong> </strong>= &#39;&lt;Your database (schema) name&gt;&#39;<br>                <strong>and </strong>kcu.constraint_name<strong> like </strong>&#39;fk_%&#39;<br>            <strong>union<br>            select </strong>kcu.referenced_table_schema,<br>                   kcu.referenced_table_name,<br>                   acronym(kcu.referenced_table_name) <strong>as </strong>table_acronym<br>            <strong>from </strong>information_schema.key_column_usage<strong> </strong>kcu<br>            <strong>where </strong>kcu.constraint_schema<strong> </strong>= &#39;&lt;Your database (schema) name&gt;&#39;<br>                <strong>and </strong>kcu.constraint_name<strong> like </strong>&#39;fk_%&#39;<br>          ) <strong>as </strong>rel_table_base<br>    )                                      <br><strong>select </strong>twa.table_no,<br>       twa.table_schema,<br>       twa.<strong>table_name</strong>,<br>       twa.table_acronym,<br>       <strong>group_concat</strong>(<br>          <strong>concat</strong>(&#39;\t&#39;, twa.table_acronym, &#39;_&#39;, twa.table_no, &#39;.&#39;,     isc.<strong>column_name</strong>, &#39; as &#39;, twa.table_acronym, &#39;_&#39;, isc.<strong>column_name</strong>)<br>                    <strong>separator </strong>&#39;, \n &#39;<br>       ) <strong>as </strong>table_aliased_columns<br><strong>from </strong>information_schema.columns<strong> </strong>isc<br>    <strong>inner join </strong>tables_with_acronyms twa<br>        <strong>on </strong>isc.table_schema = twa.table_schema<br>            <strong>and </strong>isc.table_name<strong> </strong>= twa.table_name<strong><br>group by </strong>twa.table_no,<br>       twa.table_schema,<br>       twa.table_name,<br>       twa.table_acronym;</pre><p>This <strong>INSERT WITH </strong>gets all the tables from your database that are child or parent. you will see that I use a function: <a href="https://github.com/philipcarrington/sql-stuff/blob/master/functions/mysql/acroym-function.sql">acronym</a>. It is one that I borrowed / changed slightly to improve performance in MySQL, and will return the first letter in the seperated names of the value passed in. e.g.</p><pre><strong>select </strong>acronym(&#39;table_in_your_database&#39;)</pre><p>Returns:</p><pre>acronym(&#39;table_in_your_database&#39;)    <br>------------------------------------ <br>tiyd</pre><p>The table that has now just been populated if you query it will look something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubhJdKyE6FR9oXQ6KRkBBg.png" /><figcaption>Screenshot of the denormalise_tables_data table when queried</figcaption></figure><h3>Get the table (reverse) hierarchy:</h3><p>Again we will make use of a table to store the data for the final query and for debugging if we hit any snags:</p><pre><strong>drop table </strong>denormalized_view_data;<br><br><strong>create table </strong>denormalized_view_data ( <br>    orig_table_no               <strong>int</strong>,<br>    orig_table_schema           <strong>varchar</strong>(255),<br>    orig_table_name             <strong>varchar</strong>(255),<br>    orig_table_alias            <strong>varchar</strong>(10),<br>    level_no                    <strong>int</strong>,<br>    cur_table_no                <strong>int</strong>,<br>    cur_table_schema            <strong>varchar</strong>(255), <br>    cur_table_name              <strong>varchar</strong>(255),<br>    cur_table_alias             <strong>varchar</strong>(10),<br>    cur_join_column_name        <strong>varchar</strong>(255),<br>    cur_table_columns           <strong>varchar</strong>(1000),<br>    ref_table_no                <strong>int</strong>, <br>    ref_table_schema            <strong>varchar</strong>(255), <br>    ref_table_name              <strong>varchar</strong>(255),    <br>    ref_table_alias             <strong>varchar</strong>(10),<br>    ref_join_column_name        <strong>varchar</strong>(255),<br>    ref_table_columns           <strong>varchar</strong>(1000)<br>);</pre><p>This table has three “sets” of columns in it:</p><ol><li><em>orig_</em> : These will be the anchor that no matter the level will always contain the details of the table that “started” the chain</li><li><em>cur_</em> : Are the table details for the level that we are on now, for the first level then they will be the same as the orig_ values</li><li><em>ref_</em> : This is effectively the parent of the cur_ table, and will be the next level to be investigated.</li></ol><p>This is populated by:</p><pre><strong>insert into </strong>denormalized_view_data<br><strong>with recursive </strong>table_hirearchy <strong>as </strong>(<br>    <strong>select </strong>c_dtd.table_no <strong>as </strong>orig_table_no,<br>           c_dtd.table_schema <strong>as </strong>orig_table_schema,<br>           c_dtd.<strong>table_name as </strong>orig_table_name,<br>           c_dtd.table_acronym <strong>as </strong>orig_table_alias,<br>           1 <strong>as </strong>level_no,<br>           c_dtd.table_no <strong>as </strong>cur_table_no,<br>           c_dtd.table_schema <strong>as </strong>cur_table_schema,<br>           c_dtd.<strong>table_name as </strong>cur_table_name,<br>           c_dtd.table_acronym <strong>as </strong>cur_table_alias,<br>           kcu.<strong>column_name as </strong>cur_join_column_name,<br>           c_dtd.table_aliased_columns <strong>as </strong>cur_table_columns,                      <br>           r_dtd.table_no <strong>as </strong>ref_table_no,<br>           r_dtd.table_schema <strong>as </strong>ref_table_schema,<br>           r_dtd.<strong>table_name as </strong>ref_table_name,<br>           r_dtd.table_acronym <strong>as </strong>ref_table_alias,<br>           kcu.referenced_column_name <strong>as </strong>ref_join_column_name,<br>           r_dtd.table_aliased_columns <strong>as </strong>ref_table_columns                    <br>    <strong>from </strong>information_schema.key_column_usage<strong> </strong>kcu<br>        <strong>inner join </strong>denormalise_tables_data c_dtd<br>            <strong>on </strong>kcu.table_schema = c_dtd.table_schema<br>                <strong>and </strong>kcu.table_name<strong> </strong>= c_dtd.table_name<strong><br>        inner join </strong>denormalise_tables_data r_dtd<br>            <strong>on </strong>kcu.referenced_table_schema = r_dtd.table_schema<br>                <strong>and </strong>kcu.referenced_table_name = r_dtd.table_name<strong> <br>    union all<br>    select </strong>th.orig_table_no,<br>           th.orig_table_schema,<br>           th.orig_table_name,<br>           th.orig_table_alias,<br>           1 + th.level_no <strong>as </strong>level_no,<br>           th.ref_table_no <strong>as </strong>cur_table_no,<br>           th.ref_table_schema <strong>as </strong>cur_table_schema,<br>           th.ref_table_name <strong>as </strong>cur_table_name,<br>           th.ref_table_alias <strong>as </strong>cur_table_alias,<br>           th.ref_join_column_name <strong>as </strong>cur_join_column_name,<br>           th.ref_table_columns <strong>as </strong>cur_table_columns,                          <br>           r_dtd.table_no <strong>as </strong>ref_table_no,<br>           r_dtd.table_schema <strong>as </strong>ref_table_schema,<br>           r_dtd.table_name<strong> as </strong>ref_table_name,<br>           r_dtd.table_acronym <strong>as </strong>ref_table_alias,<br>           kcu2.referenced_column_name <strong>as </strong>ref_join_column_name,<br>           r_dtd.table_aliased_columns <strong>as </strong>ref_table_columns                    <br>    <strong>from </strong>table_hirearchy th       <br>        <strong>inner join </strong>information_schema.key_column_usage<strong> </strong>kcu2<br>            <strong>on </strong>th.ref_table_schema = kcu2.table_schema<br>                <strong>and </strong>th.ref_table_name = kcu2.table_name<strong>        <br>        inner join </strong>denormalise_tables_data r_dtd<br>            <strong>on </strong>kcu2.referenced_table_schema = r_dtd.table_schema<br>                <strong>and </strong>kcu2.referenced_table_name = r_dtd.table_name<strong>                            <br></strong>)<br><strong>select distinct </strong>*<br><strong>from </strong>table_hirearchy</pre><p>Reading the code you can see we use the MySQL <strong>WITH </strong>recursively to follow the hierarchy. It is also worth noting that this is the reverse hierarchy, the level_no 1 tables are actually the tables at the “bottom” of the ERD, and generally the ones with the high level_no’s are actually towards the “top” of the ERD.</p><p>Which when queried gives you something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yg5rL5UrU-EF0WmaXab1vQ.png" /><figcaption>Reduced columns of denormalized_view_data</figcaption></figure><h3>Finally get to a result:</h3><p>Lets take a look at the SQL to generate the actual “<em>create view</em>” code using the above tables (sorry not sorry, its a little verbose):</p><pre><strong>set session </strong>group_concat_max_len = 10000;<br><br><strong>with<br>    </strong>create_view_const <strong>as </strong>(<br>        <strong>select distinct<br>            </strong>dvd.orig_table_no,<br>            <em>-- Edit this to create in a different schema:<br>            </em><strong>coalesce</strong>(<strong>null</strong>, dvd.orig_table_schema) <strong>as </strong>view_schema,<br>            <em>-- Edit thiis to give it a different view name:<br>            </em><strong>coalesce</strong>(<strong>null</strong>, dvd.orig_table_name) <strong>as </strong>view_main_name,<br>            <em>-- Edit this to change the suffix to the view:<br>            </em><strong>coalesce</strong>(<strong>null</strong>, &#39;_denorm&#39;) <strong>as </strong>view_main_suffix,<br>            <em>-- Edit this for the statement sep<br>            </em><strong>coalesce</strong>(<strong>null</strong>, &#39;\n go \n&#39;) <strong>as </strong>statement_sep<br>        <strong>from </strong>denormalized_view_data dvd        <em><br>         </em><strong>where </strong>orig_table_schema = &#39;&lt;Your database (schema) name&gt;<em>&#39;            <br>    </em>),<br>    view_drop <strong>as </strong>(<br>        <strong>select <br>            distinct </strong>dvd.orig_table_no,<br>            <strong>concat</strong>(<br>            &#39;drop view &#39;,            <em><br>            </em>cvc.view_schema, &#39;.&#39;,            <em><br>            </em>cvc.view_main_name,<em><br>            </em>cvc.view_main_suffix, cvc.statement_sep            <br>        ) <strong>as </strong>drop_view_line <br>        <strong>from </strong>denormalized_view_data dvd<br>            <strong>inner join </strong>create_view_const cvc<br>                <strong>on </strong>dvd.orig_table_no = cvc.orig_table_no         <em><br>         </em><strong>where </strong>orig_table_schema = &#39;&lt;Your database (schema) name&gt;<em>&#39; <br>    </em>),<br>    view_create <strong>as </strong>(<br>        <strong>select distinct </strong>dvd.orig_table_no,<br>            <strong>concat</strong>(<br>            &#39;create view &#39;,            <em><br>            </em>cvc.view_schema, &#39;.&#39;,<em><br>            </em>cvc.view_main_name,<em><br>            </em>cvc.view_main_suffix, &#39; as (&#39;            <br>        ) <strong>as </strong>create_view_line_start,<br>        <strong>concat</strong>(&#39;\n)&#39;, cvc.statement_sep) <strong>as </strong>create_view_line_end <br>        <strong>from </strong>denormalized_view_data dvd<br>            <strong>inner join </strong>create_view_const cvc<br>                <strong>on </strong>dvd.orig_table_no = cvc.orig_table_no         <em><br>         </em><strong>where </strong>orig_table_schema = &#39;&lt;Your database (schema) name&gt;<em>&#39;   <br>    </em>),<br>    view_columns <strong>as </strong>(         <br>         <strong>select </strong>cols_base.orig_table_no,<br>                <strong>concat</strong>(&#39;select \n&#39;,<br>                        <strong>group_concat</strong>(cols_base.table_columns)<br>                      ) <strong>as </strong>columns_section<br>         <strong>from </strong>(<br>                 <strong>select </strong>dvd.orig_table_no,<br>                        dvd.cur_table_columns <strong>as </strong>table_columns<br>                 <strong>from </strong>denormalized_view_data dvd<br>                 <em>-- For testing:<br>                 </em><strong>where </strong>orig_table_schema = &#39;&lt;Your database (schema) name&gt;<em>&#39; <br>                 </em><strong>union distinct <br>                 select </strong>dvd.orig_table_no,<br>                        dvd.ref_table_columns <strong>as </strong>table_columns<br>                 <strong>from </strong>denormalized_view_data dvd<br>                 <em>-- For testing:<br>                 </em><strong>where </strong>orig_table_schema = &#39;&lt;Your database (schema) name&gt;<em>&#39; <br>                </em>) <strong>as </strong>cols_base<br>         <strong>group by  </strong>cols_base.orig_table_no                                            <br>    ),<br>    view_from <strong>as </strong>(<br>        <strong>select distinct<br>               </strong>dvd.orig_table_no,<br>               <strong>concat</strong>(<br>                    &#39;from &#39;, dvd.orig_table_schema, &#39;.&#39;, dvd.orig_table_name, &#39; as &#39;, dvd.orig_table_alias, &#39;_&#39;, dvd.orig_table_no<br>               ) <strong>as </strong>from_section<br>        <strong>from </strong>denormalized_view_data dvd<em><br>        </em><strong>where </strong>orig_table_schema = &#39;&lt;Your database (schema) name&gt;<em>&#39;<br>    </em>),<br>    view_joins <strong>as </strong>(<br>        <strong>select </strong>dvd.orig_table_no,<br>               dvd.level_no,<br>               <strong>concat </strong>(<br>                    &#39;inner join &#39;, dvd.ref_table_schema, &#39;.&#39;, dvd.ref_table_name, &#39; as &#39;, dvd.ref_table_alias, &#39;_&#39;, dvd.ref_table_no, &#39;\n&#39;, <br>                    &#39;\t on &#39;, dvd.cur_table_alias, &#39;_&#39;, dvd.cur_table_no, &#39;.&#39;, dvd.cur_join_column_name, &#39; = &#39;,  dvd.ref_table_alias, &#39;_&#39;, dvd.ref_table_no, &#39;.&#39;, dvd.ref_join_column_name                   <br>               ) <strong>as </strong>joins_section<br>        <strong>from </strong>denormalized_view_data dvd<em><br>        </em><strong>where </strong>orig_table_schema = &#39;&lt;Your database (schema) name&gt;<em>&#39;<br>    </em>) <br><strong>select  </strong>vd.drop_view_line,<br>        <strong>concat</strong>(<br>            vcr.create_view_line_start, &#39;\n&#39;,<br>            vc.columns_section, &#39;\n&#39;,<br>            vf.from_section, &#39;\n\t&#39;,<br>            <strong>group_concat</strong>(<br>                vj.joins_section<br>                <strong>order by </strong>vj.level_no<br>                <strong>separator </strong>&#39;\n\t&#39;<br>                <br>            ),<br>            vcr.create_view_line_end<br>       ) <strong>as </strong>view_code<br><strong>from </strong>view_create vcr<br>    <strong>inner join </strong>view_drop vd<br>        <strong>on </strong>vcr.orig_table_no = vd.orig_table_no<br>    <strong>inner join </strong>view_columns vc<br>        <strong>on </strong>vcr.orig_table_no = vc.orig_table_no<br>    <strong>inner join </strong>view_from vf<br>        <strong>on </strong>vcr.orig_table_no = vf.orig_table_no<br>    <strong>left join </strong>view_joins vj<br>        <strong>on </strong>vcr.orig_table_no = vj.orig_table_no<br><strong>group by </strong>vd.drop_view_line,<br>         vcr.create_view_line_start,<br>         vc.columns_section,<br>         vf.from_section,<br>         vcr.create_view_line_end</pre><p>As you can see there are a lot of <strong>WITH</strong>’s in the code, you can see that it enables an easy break down of the different parts that you require to make up the “<em>create view</em>” statement.</p><p>At the top there is a constants table that is used throughout and allows you to set things like a statement separator and schemas you wish the views (as a set) to go into, it generates the <strong>DROP </strong>command (so be careful), and then the various parts of the <strong>CREATE </strong>view statement.</p><h4>What does this create:</h4><p>This returns a result like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f4bH2Cs9Zdb4WtJmnSxxMg.png" /><figcaption>Screenshot of output of the creation SQL</figcaption></figure><h3>Future Developments:</h3><p>At the moment you still need to run the commands that are generated manually. I or you can look to make this as part of a stored procedure (or some other type of scripting) to enable this to be automated on database create.</p><h3>Where can you find the code:</h3><p>All of the above is a little garbled by the formatting in Medium then you can find the code in my <a href="https://github.com/philipcarrington/sql-stuff/tree/master/views/auto-generating/mysql">GitHub Repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=597d1f989d70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to WITH:]]></title>
            <link>https://medium.com/swlh/how-to-with-47e68477045a?source=rss-7dc96449847d------2</link>
            <guid isPermaLink="false">https://medium.com/p/47e68477045a</guid>
            <category><![CDATA[with]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Philip Carrington]]></dc:creator>
            <pubDate>Fri, 05 Jun 2020 13:01:01 GMT</pubDate>
            <atom:updated>2020-06-06T16:23:41.541Z</atom:updated>
            <content:encoded><![CDATA[<h3>HowWITH:</h3><p><a href="https://medium.com/@philipcarrington/why-with-a636058a56c8">Previously</a> I wrote about Why WITH now we will look simply at the How</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B_QNWdQ6OsUg838Q" /><figcaption>Photo by <a href="https://unsplash.com/@prkns?utm_source=medium&amp;utm_medium=referral">David Perkins</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What are we going to cover:</h3><p>There are a whole load of pages out there showing <a href="https://www.google.com/search?sxsrf=ALeKk03RUQ2yd5TrqtxDGxBVtNu1XEfYyw%3A1591008079095&amp;ei=T9vUXuSrBYHWatKKhbAP&amp;q=examples+of+WITH+in+SQL&amp;oq=examples+of+WITH+in+SQL&amp;gs_lcp=CgZwc3ktYWIQAzIGCAAQFhAeMgYIABAWEB4yBggAEBYQHjIGCAAQFhAeMgYIABAWEB4yBggAEBYQHjIGCAAQFhAeMgYIABAWEB4yBggAEBYQHjIGCAAQFhAeOgQIABBHOgIIAFCVLlicOWCKPWgAcAF4AIABlwWIAY8TkgEHMC4xLjUtNJgBAKABAaoBB2d3cy13aXo&amp;sclient=psy-ab&amp;ved=0ahUKEwikj477tuDpAhUBqxoKHVJFAfYQ4dUDCAw&amp;uact=5">examples of WITH</a> across so many different database so it is repetition, but I want to pull the usages together into one place here and any GOTCHA’s that I found along the way. All the code snippets in here are specific to MySQL, but principally should work in any database (<strong><em>GOTCHA</em></strong>: The names and columns of the meta tables will need changing)</p><h3>TL;DR:</h3><p>You can basically use a <strong>WITH</strong> in the places where you can use a <strong>SELECT</strong> in SQL where your particular Database Engine supports it. You might need to add additional parenthesis or the odd keyword, but as a method of creating a database object at runtime that can be referenced again and agin it is super useful!</p><h3><strong>A Simple WITH:</strong></h3><p>Creating a WITH CTE statement is easy in most of the database implementations of SQL that I have come across so far. They generally go a git like this:</p><pre><strong>with</strong> &lt;with table name&gt; as (<br>        <strong>select</strong> *<br>        <strong>from</strong> &lt;schema&gt;.&lt;table&gt; as &lt;alias&gt;<br>        <strong>where</strong> &lt;alias&gt;.&lt;field&gt; &lt;operator&gt; &lt;value&gt;  <br>    )<br><strong>select</strong> *<br><strong>from</strong> &lt;with table name&gt;</pre><p>So as you can read then your code will effectively consist of now two SQL statements (there are variations for this but for simplicity). For something that you could run now (in MySQL):</p><pre><strong>with </strong>info_schema_table_cols <strong>as </strong>(<br>        <strong>select </strong>isc.table_schema,<br>               isc.<strong>table_name</strong>,<br>               isc.<strong>column_name<br>        from </strong>information_schema.<strong>columns </strong>isc<br>        <strong>where </strong>isc.table_schema = &#39;information_schema&#39;<br>    )<br><strong>select </strong>*<br><strong>from </strong>info_schema_table_cols</pre><p>This returns a set of data on the columns names and the tables that you will find in the “information_schema”. Maybe not the best use of a with but to get us started</p><h3>A JOIN’ed WITH:</h3><p>You can JOIN a WITH just as you would any other table in an SQL statement:</p><pre><strong>with </strong>info_schema_table_cols <strong>as </strong>(<br>        <strong>select </strong>isc.table_schema,<br>               isc.<strong>table_name</strong>,<br>               isc.<strong>column_name<br>        from </strong>information_schema.<strong>columns </strong>isc<br>        <strong>where </strong>isc.table_schema = &#39;information_schema&#39;<br>    )<br><strong>select </strong>istc.*,<br>       ist.table_type       <br><strong>from </strong>info_schema_table_cols istc<br>    <strong>inner join </strong>information_schema.<strong>tables </strong>ist<br>        <strong>on </strong>istc.table_schema = ist.table_schema<br>            <strong>and </strong>istc.<strong>table_name </strong>= ist.<strong>table_name</strong></pre><p>The code above again is a little example to show how to JOIN onto a WITH’ed table using another table in the database (and it works).</p><h3>A ReJOIN’ed WITH:</h3><p>For a more serious example lets say you wanted to look at Foreign Keys (FK) and the tables on each side of the FK. You could do something like this:</p><pre><strong>with </strong>table_info <strong>as </strong>(<br>        <strong>select </strong>isc.table_schema,<br>               isc.<strong>table_name</strong>,<br>               isc.<strong>column_name</strong>,<br>               isc.ordinal_position,<br>               isc.column_type<br>        <strong>from </strong>information_schema.<strong>columns </strong>isc<br>    )<br><strong>select </strong>iskcu.<strong>constraint_schema</strong>,<br>       iskcu.<strong>constraint_name</strong>,       <br>       iskcu.table_schema <strong>as </strong>constrained_schema,<br>       iskcu.<strong>table_name as </strong>constrained_table,<br>       iskcu.<strong>column_name as </strong>constrained_column,<br>       <em>-- from with table:<br>       </em>ti.ordinal_position <strong>as </strong>constrained_ordinal_position,<br>       ti.column_type <strong>as </strong>constrained_type,<br>       <em>-- if it is a FK:<br>       </em>iskcu.referenced_table_schema,<br>       iskcu.referenced_table_name,<br>       iskcu.referenced_column_name,<br>       <em>-- from with table - REUSED!!:<br>       </em>r_ti.ordinal_position <strong>as </strong>referenced_ordinal_position,<br>       r_ti.column_type <strong>as </strong>referenced_type<br><strong>from </strong>information_schema.<strong>key_column_usage </strong>iskcu<br>    <strong>inner join </strong>table_info ti<br>        <strong>on </strong>iskcu.table_schema = ti.table_schema<br>            <strong>and </strong>iskcu.<strong>table_name </strong>= ti.<strong>table_name<br>            and </strong>iskcu.<strong>column_name </strong>= ti.<strong>column_name<br>    left join </strong>table_info r_ti<br>        <strong>on </strong>iskcu.referenced_table_schema = r_ti.table_schema<br>            <strong>and </strong>iskcu.referenced_table_name = r_ti.<strong>table_name<br>            and </strong>iskcu.referenced_column_name = r_ti.<strong>column_name</strong></pre><p>As you can read here we have used the same with table twice, for comparison is an example below using the Sub Query method in the <strong>JOIN:</strong></p><pre><strong>select </strong>iskcu.<strong>constraint_schema</strong>,<br>       iskcu.<strong>constraint_name</strong>,       <br>       iskcu.table_schema <strong>as </strong>constrained_schema,<br>       iskcu.<strong>table_name as </strong>constrained_table,<br>       iskcu.<strong>column_name as </strong>constrained_column,<br>       <em>-- from with table:<br>       </em>ti.ordinal_position <strong>as </strong>constrained_ordinal_position,<br>       ti.column_type <strong>as </strong>constrained_type,<br>       <em>-- if it is a FK row:<br>       </em>iskcu.referenced_table_schema,<br>       iskcu.referenced_table_name,<br>       iskcu.referenced_column_name,<br>       <em>-- from with table:<br>       </em>r_ti.ordinal_position <strong>as </strong>referenced_ordinal_position,<br>       r_ti.column_type <strong>as </strong>referenced_type<br><strong>from </strong>information_schema.<strong>key_column_usage </strong>iskcu<br>    <strong>inner join </strong>(<br>                <strong>select </strong>isc.table_schema,<br>                       isc.<strong>table_name</strong>,<br>                       isc.<strong>column_name</strong>,<br>                       isc.ordinal_position,<br>                       isc.column_type<br>                <strong>from </strong>information_schema.<strong>columns </strong>isc<br>            ) ti<br>        <strong>on </strong>iskcu.table_schema = ti.table_schema<br>            <strong>and </strong>iskcu.<strong>table_name </strong>= ti.<strong>table_name<br>            and </strong>iskcu.<strong>column_name </strong>= ti.<strong>column_name<br>    left join </strong>(<br>                <strong>select </strong>isc.table_schema,<br>                       isc.<strong>table_name</strong>,<br>                       isc.<strong>column_name</strong>,<br>                       isc.ordinal_position,<br>                       isc.column_type<br>                <strong>from </strong>information_schema.<strong>columns </strong>isc<br>            ) r_ti<br>        <strong>on </strong>iskcu.referenced_table_schema = r_ti.table_schema<br>            <strong>and </strong>iskcu.referenced_table_name = r_ti.<strong>table_name<br>            and </strong>iskcu.referenced_column_name = r_ti.<strong>column_name</strong></pre><p>The query cost of the WITH version of this query is:1575 and the Sub Query version is: 1576, so not a good example for this particular query but in DB2 and SQL server over Multi 100’s of GB’s of data then I have seen a 10x or more improvement in the query speed using a WITH rather than a Sub Query.</p><h3>Multiple WITH’s:</h3><p>This is easy an builds on what we have seen so far the basic premise is:</p><pre>with &lt;first with table name&gt; as (<br>        some type of select clause<br>    ),<br>    &lt;second with table name&gt; as (<br>        some type of select clause<br>    )<br>select *<br>from &lt;first with table name&gt; as &lt;fwtn&gt;<br>    inner join &lt;second with table name&gt; as &lt;swtn&gt;<br>      on &lt;fwtn&gt;.&lt;field&gt; = &lt;swtn&gt;.&lt;field&gt;</pre><p>Just to blow your mind (it did mine the first time I tried to use it and it worked) then you can do another two multiple with things:</p><h4>WITH inside a WITH:</h4><p>It is possible although I do not have a good example I think I last did this with some none simple analytical query</p><pre><strong>with </strong>&lt;outer with name&gt; <strong>as </strong>(<br>    <strong>with </strong>&lt;inner with name&gt; <strong>as </strong>(<br>            some type of <strong>select </strong>clause         <br>         ),<br>         &lt;inner with name<strong> </strong>2&gt; <strong>as </strong>(<br>            some type of <strong>select </strong>clause         <br>         )<br>    <strong>select </strong>*    <br>    <strong>from </strong>&lt;inner with name&gt; <strong>as </strong>i1<br>        <strong>left join </strong>&lt;inner with name<strong> </strong>2&gt; <strong>as </strong>i2<br>            <strong>on </strong>i1.&lt;field&gt; = i2.&lt;field&gt;<br>    <strong>where </strong>i2.&lt;field&gt; <strong>is not null<br></strong>)<br><strong>select </strong>&lt;some<strong> </strong>complicated analytical query&gt;<br><strong>from </strong>&lt;outer with name&gt; <strong>as </strong>own<br>    <strong>left outer join </strong>&lt;schema&gt;.&lt;table name&gt; <strong>as </strong>stn<br>        <strong>on </strong>own.&lt;field&gt; = stn.&lt;field&gt;</pre><h4>WITH referencing a WITH:</h4><pre><strong>with </strong>&lt;with name<strong> </strong>1&gt; <strong>as </strong>(<br>        &lt;some type of<strong> select </strong>clause&gt;<br>    ),<br>    &lt;with name<strong> </strong>2&gt; <strong>as </strong>(<br>        <strong>select </strong>&lt;some fields&gt;<br>        <strong>from </strong>&lt;with name<strong> </strong>1&gt; <strong>as </strong>wn1<br>            <strong>inner join </strong>&lt;schema&gt;.&lt;table name&gt; <strong>as </strong>stn<br>                <strong>on </strong>wn1.&lt;field&gt; = stn.&lt;field&gt;<br>    )<br><strong>select </strong>*<br><strong>from </strong>&lt;with name<strong> </strong>2&gt;</pre><p>Here you can read that the 2nd <strong>WITH</strong> uses the result set of the first <strong>WITH. </strong>This is useful when an earlier <strong>WITH SELECT </strong>contains something that several subsequent WITH’s may need. An example of this would be a number of constants that could be used throughout the whole statement.</p><h3>A Recursive WITH:</h3><p>This is one of the most difficult to understand parts WITH functionality, but the most useful when you want to decompose hierarchies’ in SQL. I have in the past used it in <a href="http://www.dangerousdba.com/xml-shredding-data-model-and-code/">DB2 to shred XML documents</a>, more recently I have been working on some code to denormalise a database based on foreign keys stored in the meta database:</p><pre><strong>with <em>recursive</em> </strong>table_hirearchy <strong>as </strong>(<br>    <strong>select <br>           </strong><em>-- The level of the denormalisation:<br>           </em>1 <strong>as </strong>level_no, <br>           <em>-- The original table for the denormalisation:<br>           </em>kcu.table_schema <strong>as </strong>orig_table_schema,<br>           kcu.<strong>table_name as </strong>orig_table_name,<br>           <em>-- The current table that the FK refers too:<br>           </em>kcu.table_schema <strong>as </strong>cur_table_schema,<br>           kcu.<strong>table_name as </strong>cur_table_name,           <br>           kcu.<strong>column_name as </strong>cur_join_column_name, <br>           <em>-- The refered to table that will be the next level:                                                      <br>           </em>kcu.referenced_table_schema <strong>as </strong>ref_table_schema,<br>           kcu.referenced_table_name <strong>as </strong>ref_table_name,           <br>           kcu.referenced_column_name <strong>as </strong>ref_join_column_name                               <br>    <strong>from </strong>information_schema.<strong>key_column_usage </strong>kcu<br>    <strong>where </strong>kcu.<strong>constraint_schema </strong>= &#39;&lt;your database name&gt;&#39;<br>        <strong>and </strong>(kcu.<strong>constraint_name like </strong>&#39;&lt;your databases   identification of FK&#39;s if you have one!&gt;%&#39;)          <br>    <strong>union all<br>    select <br>           </strong><em>-- Add one to the level as this is <br>           --  now one step further on<br>           --  in denormalisation:<br>           </em>1 + th.level_no <strong>as </strong>level_no,<br>           <em>-- Keep the original table as an anchor <br>           -- for the result for later use:<br>           </em>th.orig_table_schema <strong>as </strong>orig_table_schema,<br>           th.orig_table_name <strong>as </strong>orig_table_name,<br>           <em>-- Move onto looking at the next set of tables<br>           </em>th.ref_table_schema <strong>as </strong>cur_table_schema,<br>           th.ref_table_name <strong>as </strong>cur_table_name,<br>           th.ref_join_column_name <strong>as </strong>cur_join_column_name,<br>           <em>-- Get the next level data to be passed back in:                                                           <br>           </em>kcu2.referenced_table_schema <strong>as </strong>ref_table_schema,<br>           kcu2.referenced_table_name <strong>as </strong>ref_table_name,           <br>           kcu2.referenced_column_name <strong>as </strong>ref_join_column_name                   <br>    <strong>from </strong>table_hirearchy th       <br>        <strong>inner join </strong>information_schema.<strong>key_column_usage </strong>kcu2<br>            <strong>on </strong>th.ref_table_schema = kcu2.table_schema<br>                <strong>and </strong>th.ref_table_name = kcu2.<strong>table_name    <br>    where </strong>kcu2.<strong>constraint_schema </strong>= &#39;&lt;your database name&gt;&#39;<br>        <strong>and </strong>(kcu2.<strong>constraint_name like </strong>&#39;&lt;your databases identification of FK&#39;s if you have one!&gt;%&#39;)                                                        <br>)<br><strong>select distinct </strong>*<br><strong>from </strong>table_hirearchy</pre><p>The <strong><em>recursive</em></strong> in the example above is a MySQL specific keyword in the definition of the recursive CTE, I have not seen this in DB2 or MS SQL Server. So there are some inline comments in there for you but essentially you will get something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vg0U0tEWzwiYiw2hDGezIg.png" /><figcaption>Output from the Recursive WITH</figcaption></figure><p>As you can see you will get a row for all the FK’s that you have against a table, the observant amongst you might have also noticed that actually the levels are reversed as you start at the lowest level and work back up the relations.</p><p><strong>GOTCHA: </strong>Google BigQuery (GBQ) does not support recursive WITH (CTE’s). This is mainly due to the size of data that you be using in GBQ</p><h3>An INSERT WITH:</h3><p>DB2, MySQL, Redshift and Google BigQuery support this at time of writing, I assume the rest of the <strong>WITH </strong>supporting DB’s do to as well. This is not a stretch of what we have seen so far, its like an:</p><pre><strong>insert into</strong> &lt;schema&gt;.&lt;table name&gt;<br><strong>select</strong> &lt;some columns&gt;<br><strong>from</strong> &lt;schema&gt;.&lt;table name&gt;</pre><p>But in its most simplified format it is:</p><pre><strong>insert into</strong> &lt;schema&gt;.&lt;table name&gt;<br><strong>with </strong>&lt;a meaningful name&gt; as (<br>     <strong>select</strong> &lt;some columns&gt; , , , <br>     <strong>from</strong> &lt;schema&gt;.&lt;table name&gt;<br>)<br><strong>select</strong> * <br><strong>from</strong> &lt;a meaningful name&gt;</pre><h3>An UPDATE WITH:</h3><p>Never done one of these so going with a very lightly tested solution I found on <a href="https://stackoverflow.com/questions/45688678/using-with-and-update-statements-in-the-same-sql-query">stackoverflow</a>. You still have to obey the normal <strong>UPDATE</strong> rules of providing and atomic value, but otherwise it looks like a valid solution:</p><pre><strong>update </strong>&lt;schema&gt;.&lt;table<strong> </strong>name&gt; <strong>as </strong>stn<br><strong>set </strong>&lt;field&gt; = (<br>                <strong>with </strong>&lt;with table name&gt; <strong>as</strong>(<br>                    &lt;Valid SQL <strong>SELECT </strong>statement&gt;<br>                    )<br>               <strong>select </strong>&lt;field&gt;<br>               <strong>from   </strong>&lt;with table name&gt; <strong>as </strong>wtn<br>               <strong>where  </strong>stn.&lt;field<strong> </strong>2&gt; = wtn.&lt;field<strong> </strong>2&gt;<br>             )</pre><h3>A MERGE WITH:</h3><p>Again this pretty much replaces the <strong>SELECT</strong> statement with a <strong>WITH:</strong></p><pre><strong>merge</strong> <strong>into </strong>&lt;schema&gt;.&lt;table<strong> </strong>name&gt; <strong>as </strong>stn<br><strong>using </strong>(<br>        <strong>with </strong>&lt;with<strong> </strong>table<strong> </strong>name&gt; <strong>as</strong>(<br>                &lt;Valid SQL<strong> SELECT </strong>statement&gt;<br>                )<br>        <strong>select </strong>&lt;field<strong> </strong>1&gt;,<br>               &lt;field<strong> </strong>2&gt;,<br>               . . . <br>               &lt;field<strong> </strong>n&gt;                  <br>        <strong>from </strong>&lt;with table name&gt; <strong>as </strong>wtn<br>      ) <strong>as </strong>wmd<br><strong>on </strong>stn.&lt;field&gt; = wmd.&lt;field&gt;<br><strong>when matched</strong> <strong>then <br>    update </strong>. . . <br><strong>when not matched</strong> <strong>then<br>    insert </strong>. . .</pre><p>Of course your <strong>WITH </strong>could be any of the Recursive, Joined, ReJoin’ed or any of the things we have looked at above.</p><h3><strong>Conclusion:</strong></h3><p><strong>WITH</strong> is a useful thing used correctly it is very powerful tool to extend what limited actions you may have due to other limiting factors in your environment such as permissions, and what you are required to do is less than simple!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47e68477045a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-with-47e68477045a">How to WITH:</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why WITH:]]></title>
            <link>https://medium.com/swlh/why-with-a636058a56c8?source=rss-7dc96449847d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a636058a56c8</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[useful-tips]]></category>
            <category><![CDATA[with]]></category>
            <category><![CDATA[sql-command]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Philip Carrington]]></dc:creator>
            <pubDate>Mon, 01 Jun 2020 09:53:16 GMT</pubDate>
            <atom:updated>2020-06-06T10:19:15.975Z</atom:updated>
            <content:encoded><![CDATA[<p>The WITH statement in SQL can be a powerful thing, but all to easy to overuse:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bmXFePp94H_dsP2Y" /><figcaption>Photo by <a href="https://unsplash.com/@golimpio?utm_source=medium&amp;utm_medium=referral">Gilberto Olimpio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>WITH in SQL:</h3><p>Most of the major relational databases support the <strong>WITH</strong> clause to create a <strong>CTE</strong> (Common Table Expression); even MySQL does now! This was a pleasant surprise for me when I was reviewing how to solve a problem in a personal project I am working on at the moment, but MySQL still does not support <strong>ROW_NUMBER() OVER()</strong> so still a bit “toy” in my opinion :-).</p><h3>What can you use with for:</h3><p><strong>WITH</strong> allows you to create tables in a query that are created at and exist for the duration of that query. It has obvious memory impacts on your database engine but the payoffs in the reduced complexity of your query can be large. A super simple example can be seen below, many can be found on the internet.</p><pre>with &lt;with table name&gt; as (<br>        some type of select clause<br>    )<br>select *<br>from &lt;with table name&gt;</pre><p>The tables are reusable, so you can reference a <strong>WITH</strong> table in multiple times, in another <strong>WITH</strong> or in the <strong>FROM</strong> clause of a table, or multiple times in the <strong>FROM</strong> clause of another <strong>WITH:</strong></p><pre>with &lt;first with table name&gt; as (<br>        some type of select clause<br>    ),<br>    &lt;second with table name&gt; as (<br>        some type of select clause<br>    )<br>select *<br>from &lt;first with table name&gt; as &lt;fwtn&gt;<br>    inner join &lt;second with table name&gt; as &lt;swtn&gt;<br>      on &lt;fwtn&gt;.&lt;field&gt; = &lt;swtn&gt;.&lt;field&gt;</pre><p>There are also more “advanced” things that can be done with a <strong>WITH</strong> like using it as part of an <strong>INSERT</strong> or as part of a recursive query. Recursive queries are really part of <strong>WITH</strong>’s superpowers</p><h3>WITH VS View VS Subquery:</h3><p>Why use a WITH over a standard SQL view or a subquery.</p><h4>Permissions (database or organisational) — View Lose, WITH Win:</h4><p>In some database systems such as IBM DB2 then to create a view then you need a “higher level” of <strong>SELECT </strong>privilege to be able to create a View, which can be then restrictive. There may also be organisational change management issues where the View implemented need changing and can’t in an agile way. <strong>WITH </strong>gets round both of these by only needing an SQL change to the <strong>CTE </strong>and will only work with your executing privileges.</p><h4>Reuse — WITH Win, Subquery Lose:</h4><p>Using a subquery in SQL if you want to use the same result set again for &lt;reason&gt; then you need to write (copy / paste) the same code again and give it a different alias. If you want to then add an additional field to the Subquery then you will have to add it twice. Additionally at execution time then the Subquery will be (depending on how clever your DBMS optimiser is) will have to be run twice before a set is computed. <strong>WITH </strong>gets doges this by being one section of code that can be referenced multiple times and therefore one place to edit and one piece of code to execute.</p><h4>Recursion — WITH Win, Subquery Lose, View Lose:</h4><p>Using a <strong>WITH</strong> you can recursively go through a result set to generate the hierarchy of the data that you are working with. Using the other methods; a view would have to be queried programatically multiple times to get the different levels and a Subquery would have to be copied many times and joined suitably to get the depth that you require.</p><h3>GOTCHA’s:</h3><p>Nothing comes as a free lunch, so one of the main issues with WITH is that it will hold all of that result data in memory ready to be accessed, this can cause some bottlenecking in the DBMS</p><h3><strong>Whats next for WITH:</strong></h3><p>I am planning on writing an other couple of articles on the How and When of <strong>WITH.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a636058a56c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/why-with-a636058a56c8">Why WITH:</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>