> For the complete documentation index, see [llms.txt](https://qb.ortusbooks.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://qb.ortusbooks.com/8.2.0/query-builder/building-queries/unions.md).

# Unions

The query builder also lets you create union statements on your queries using either `UNION` or `UNION ALL` strategies.

The `union` methods take either a Query Builder instance or a closure which you use to define a new QueryBuilder instance.

Union statements are added in the order in which the `union` methods are invoked, but the `union` statements can be in any order in your API call stack. This means you can safely declare your `union` method calls before the `select`, `from` and `orderBy` calls on the source Query Builder instance.

* `union()` — This method builds a SQL statement using the `UNION` clause which combines two SQL queries into a single result set containing all the matching rows. The two queries *must* have the same defined columns and compatible data types or the SQL engine will generate an error. The `union` clause only returns unique rows.
* `unionAll()` — This builds a SQL statement using the `UNION ALL` clause. This is the same as `union` but includes duplicate rows.&#x20;

{% hint style="danger" %}
**IMPORTANT:** The QueryBuilder instances passed to a `union` statement *cannot* contain a defined order. Any use of the `orderBy()` method on the unioned QueryBuilder instances will result in an `OrderByNotAllowed`exception. To order the results, add an `orderBy()` call to the parent source Query Builder instance.
{% endhint %}

## union

| Name  | Type                     | Required | Default | Description                                                                                                                               |
| ----- | ------------------------ | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| input | Function \| QueryBuilder | `true`   |         | The function or QueryBuilder instance to use as the unioned query.                                                                        |
| all   | boolean                  | `false`  | `false` | Determines if statement should be a "UNION ALL". Passing this as an argument is discouraged. Use the dedicated `unionAll` where possible. |

Adds a UNION statement to the query.

{% code title="QueryBuilder" %}

```javascript
query.from( "users" )
    .select( "name" )
    .where( "id", 1 )
    .union( function ( q ) {
        q.from( "users" )
            .select( "name" )
            .where( "id", 2 );
    } );
```

{% endcode %}

{% code title="MySQL" %}

```sql
SELECT `name`
FROM `users`
WHERE `id` = ?
UNION
SELECT `name`
FROM `users`
WHERE `id` = ?
```

{% endcode %}

Adding multiple union statements will append it to the query.

{% code title="QueryBuilder" %}

```javascript
query.from( "users" )
    .select( "name" )
    .where( "id", 1 )
    .union( function ( q ) {
        q.from( "users" )
            .select( "name" )
            .where( "id", 2 );
    } )
    .union( function ( q ) {
        q.from( "users" )
            .select("name")
            .where( "id", 3 );
    } );
```

{% endcode %}

{% code title="MySQL" %}

```sql
SELECT `name`
FROM `users`
WHERE `id` = ?
UNION
SELECT `name`
FROM `users`
WHERE `id` = ?
UNION
SELECT `name`
FROM `users`
WHERE `id` = ?
```

{% endcode %}

It can also add union queries as QueryBuilder instances.

{% code title="QueryBuilder" %}

```javascript
var q1 = query.newQuery()
    .from( "users" )
    .select( "name" )
    .where( "id", 2 );
    
var q2 = query.newQuery()
    .from( "users" )
    .select( "name" )
    .where( "id", 3 );

query.from( "users" )
    .select( "name" )
    .where( "id", 1 )
    .union( q1 )
    .union( q2 );
```

{% endcode %}

{% code title="MySQL" %}

```sql
SELECT `name`
FROM `users`
WHERE `id` = ?
UNION
SELECT `name`
FROM `users`
WHERE `id` = ?
UNION
SELECT `name`
FROM `users`
WHERE `id` = ?
```

{% endcode %}

## unionAll

| Name  | Type                     | Required | Default | Description                                                        |
| ----- | ------------------------ | -------- | ------- | ------------------------------------------------------------------ |
| input | Function \| QueryBuilder | `true`   |         | The function or QueryBuilder instance to use as the unioned query. |

Adds a UNION ALL statement to the query.

{% code title="QueryBuilder" %}

```javascript
query.from( "users" )
    .select( "name" )
    .where( "id", 1 )
    .unionAll( function( q ) {
        q.from( "users" )
            .select( "name" )
            .where( "id", 2 );
     } );
```

{% endcode %}

{% code title="MySQL" %}

```sql
SELECT `name`
FROM `users`
WHERE `id` = ?
UNION ALL
SELECT `name`
FROM `users`
WHERE `id` = ?
```

{% endcode %}

Adding multiple `unionAll` statements will append it to the query.

{% code title="QueryBuilder" %}

```javascript
query.from( "users" )
    .select( "name" )
    .where( "id", 1 )
    .unionAll( function( q ) {
        q.from( "users" )
            .select( "name" )
            .where( "id", 2 );
     } )
    .unionAll( function( q ) {
        q.from( "users" )
            .select( "name" )
            .where( "id", 3 );
     } );
```

{% endcode %}

{% code title="MySQL" %}

```sql
SELECT `name`
FROM `users`
WHERE `id` = ?
UNION ALL
SELECT `name`
FROM `users`
WHERE `id` = ?
UNION ALL
SELECT `name`
FROM `users`
WHERE `id` = ?
```

{% endcode %}

It can also add union queries as QueryBuilder instances.

{% code title="QueryBuilder" %}

```javascript
var q1 = query.newQuery()
    .from( "users" )
    .select( "name" )
    .where( "id", 2 );
    
var q2 = query.newQuery()
    .from( "users" )
    .select( "name" )
    .where( "id", 3 );

query.from( "users" )
    .select( "name" )
    .where( "id", 1 )
    .unionAll( q1 )
    .unionAll( q2 );
```

{% endcode %}

{% code title="MySQL" %}

```sql
SELECT `name`
FROM `users`
WHERE `id` = ?
UNION ALL
SELECT `name`
FROM `users`
WHERE `id` = ?
UNION ALL
SELECT `name`
FROM `users`
WHERE `id` = ?
```

{% endcode %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://qb.ortusbooks.com/8.2.0/query-builder/building-queries/unions.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `build a script that syncs our docs to a CMS` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
