CodeIgniter 4 Query Builder union() and unionAll() methods
<p><code>UNION</code> and <code>UNION ALL</code> set operators return the combined rows from 1 or more <code>SELECT</code> queries. CodeIgniter 4 Query Builder now supports <code>UNION</code> and <code>UNION ALL</code> queries with the <code>$builder->union()</code> and <code>$builder->unionAll()</code> methods respectively. Learn how to create these types of queries in this article.</p>
<p>This article and many to follow, are part of a series of articles I am writing and sharing as I learn new concepts when I learn them. I think of it as a duty in sharing the things I learn as a self-taught developer. We all need to support one another as we continue to learn and grow. <strong>#buildinpublic</strong> <strong>#learninpublic</strong> <strong>#indiehackers</strong> <strong>#developer</strong></p>
<h2>The Newsletter for PHP and MySQL Developers</h2>
<p>Receive a copy of my ebook, <em>“10 MySQL Tips For Everyone”</em>, <strong><em>absolutely free</em></strong> when you <a href="http://openlamptech.substack.com/" rel="noopener ugc nofollow" target="_blank">subscribe to the <strong><em>OpenLampTech</em></strong> newsletter</a>.</p>
<h2>Data setup and housekeeping</h2>
<p>I’m using 2 simple tables with minimal data for the example queries, a customer and employee table:</p>
<p><img alt="" src="https://miro.medium.com/v2/resize:fit:378/0*XgUprZb5kz7GNhOF" style="height:215px; width:420px" /></p>
<p>Sample employee table data</p>
<p><img alt="" src="https://miro.medium.com/v2/resize:fit:385/0*efvyzOW2PNTFIuqq" style="height:202px; width:428px" /></p>
<p>Sample customer table data</p>
<p>I also have these 2 protected properties in the Model class I am working with:</p>
<pre>
protected $db;
protected $builder;</pre>
<p>I’ll be logging (not shown) all of the executed queries using the <code>$db->getLastQuery()</code> method. I have <a href="https://levelup.gitconnected.com/codeigniter-4-query-helper-db-getlastquery-method-for-sql-prototyping-b8c7d78f18a1?sk=df1ec71ed16aef4d74435eb8e8e017af" rel="noopener ugc nofollow" target="_blank">written in-depth about </a><code><a href="https://levelup.gitconnected.com/codeigniter-4-query-helper-db-getlastquery-method-for-sql-prototyping-b8c7d78f18a1?sk=df1ec71ed16aef4d74435eb8e8e017af" rel="noopener ugc nofollow" target="_blank">$db->getLastQuery()</a></code> in the past so I won’t go into any details about it here.</p>
<h2>CodeIgniter 4 Query Builder $builder->union() method</h2>
<p>Perhaps one of the classic database practice questions with these 2 tables could be a requirement of: <em>“Show me all the employees and customers in a single table.”</em></p>
<p>We can absolutely do that with a <code>UNION</code> by using the <code>$builder->union()</code> method.</p>
<p><a href="https://levelup.gitconnected.com/codeigniter-4-query-builder-union-and-unionall-methods-de00668e785c">Click Here</a></p>