CodeIgniter 4 Query Builder union() and unionAll() methods

UNION and UNION ALL set operators return the combined rows from 1 or more SELECT queries. CodeIgniter 4 Query Builder now supports UNION and UNION ALL queries with the $builder->union() and $builder->unionAll() methods respectively. Learn how to create these types of queries in this article.

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. #buildinpublic #learninpublic #indiehackers #developer

The Newsletter for PHP and MySQL Developers

Receive a copy of my ebook, “10 MySQL Tips For Everyone”absolutely free when you subscribe to the OpenLampTech newsletter.

Data setup and housekeeping

I’m using 2 simple tables with minimal data for the example queries, a customer and employee table:

Sample employee table data

Sample customer table data

I also have these 2 protected properties in the Model class I am working with:

protected $db;
protected $builder;

I’ll be logging (not shown) all of the executed queries using the $db->getLastQuery() method. I have written in-depth about $db->getLastQuery() in the past so I won’t go into any details about it here.

CodeIgniter 4 Query Builder $builder->union() method

Perhaps one of the classic database practice questions with these 2 tables could be a requirement of: “Show me all the employees and customers in a single table.”

We can absolutely do that with a UNION by using the $builder->union() method.

Click Here