# Query

> Query represents a SELECT SQL statement in a way that is independent of DBMS.

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [db](/docs/api/yii/db/index.md) › Query

| class | `yii\db\Query` |
| --- | --- |
| Extends | [`yii\base\Component`](/docs/api/yii/base/component/index.md) » [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`QueryInterface`](/docs/api/yii/db/queryinterface/index.md), [`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md), [`yii\base\Configurable`](/docs/api/yii/base/configurable/index.md) |
| Uses traits | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| Since | 2.0 |
| Source | [`framework/db/Query.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/db/Query.php#L52) |

1 subclass:

- [`ActiveQuery`](/docs/api/yii/db/activequery/index.md)

Query represents a SELECT SQL statement in a way that is independent of DBMS.

Query provides a set of methods to facilitate the specification of different clauses
in a SELECT statement. These methods can be chained together.

By calling [`createCommand()`](/docs/api/yii/db/query/index.md#method-createCommand), we can get a [`Command`](/docs/api/yii/db/command/index.md) instance which can be further
used to perform/execute the DB query against a database.

For example,

```
$query = new Query;
// compose the query
$query->select('id, name')
    ->from('user')
    ->limit(10);
// build and execute the query
$rows = $query->all();
// alternatively, you can create DB command and execute it
$command = $query->createCommand();
// $command->sql returns the actual SQL
$rows = $command->queryAll();
```

Query internally uses the [`QueryBuilder`](/docs/api/yii/db/querybuilder/index.md) class to generate the SQL statement.

A more detailed usage guide on how to work with Query can be found in the [guide article on Query Builder](/docs/guide/db-query-builder/index.md).

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="property-behaviors"></span>[`$behaviors`](/docs/api/yii/base/component/index.md#property-behaviors) read-only | `array<`[`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md)`<static>>` | List of behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`$distinct`](#property-distinct) | `bool` | Whether to select distinct rows of data only. Default: `false`. | `Query` |
| <span id="property-emulateExecution"></span>[`$emulateExecution`](/docs/api/yii/db/querytrait/index.md#property-emulateExecution) | `bool` | Whether to emulate the actual query execution, returning empty or false results. Default: `false`. Available since 2.0.11. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| [`$from`](#property-from) | `array\|string\|null` | The table(s) to be selected from. Default: `null`. | `Query` |
| [`$groupBy`](#property-groupBy) | `array\|null` | How to group the query results. Default: `null`. | `Query` |
| [`$having`](#property-having) | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | The condition to be applied in the GROUP BY clause. Default: `null`. | `Query` |
| <span id="property-indexBy"></span>[`$indexBy`](/docs/api/yii/db/querytrait/index.md#property-indexBy) | `string\|callable\|null` | The name of the column by which the query results should be indexed by. Default: `null`. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| [`$join`](#property-join) | `array\|null` | How to join with other tables. Default: `null`. | `Query` |
| <span id="property-limit"></span>[`$limit`](/docs/api/yii/db/querytrait/index.md#property-limit) | `int\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | Maximum number of records to be returned. Default: `null`. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="property-offset"></span>[`$offset`](/docs/api/yii/db/querytrait/index.md#property-offset) | `int\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | Zero-based offset from where the records are to be returned. Default: `null`. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="property-orderBy"></span>[`$orderBy`](/docs/api/yii/db/querytrait/index.md#property-orderBy) | `array\|null` | How to sort the query results. Default: `null`. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| [`$params`](#property-params) | `array\|null` | List of query parameter values indexed by parameter placeholders. Default: `[]`. | `Query` |
| <span id="property-queryCacheDependency"></span>`$queryCacheDependency` | [`yii\caching\Dependency`](/docs/api/yii/caching/dependency/index.md)`\|null` | The dependency to be associated with the cached query result for this query Default: `null`. Available since 2.0.14. | `Query` |
| [`$queryCacheDuration`](#property-queryCacheDuration) | `int\|bool\|null` | The default number of seconds that query results can remain valid in cache. Default: `null`. Available since 2.0.14. | `Query` |
| [`$select`](#property-select) | `array\|null` | The columns being selected. Default: `null`. | `Query` |
| [`$selectOption`](#property-selectOption) | `string\|null` | Additional option that should be appended to the 'SELECT' keyword. Default: `null`. | `Query` |
| <span id="property-tablesUsedInFrom"></span>`$tablesUsedInFrom` read-only | `string[]` | Table names indexed by aliases. | `Query` |
| [`$union`](#property-union) | `array\|null` | This is used to construct the UNION clause(s) in a SQL statement. Default: `null`. | `Query` |
| <span id="property-unionLimit"></span>`$unionLimit` | `int\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | Number of records to return from the complete UNION result. Default: `null`. Available since 22.0. | `Query` |
| <span id="property-unionOffset"></span>`$unionOffset` | `int\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | Zero-based offset for the complete UNION result. Default: `null`. Available since 22.0. | `Query` |
| <span id="property-unionOrderBy"></span>`$unionOrderBy` | `array<int\|string, int\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`>\|null` | How to sort the complete UNION result. Default: `null`. Available since 22.0. | `Query` |
| <span id="property-where"></span>[`$where`](/docs/api/yii/db/querytrait/index.md#property-where) | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | Query condition. Default: `null`. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| [`$withQueries`](#property-withQueries) | `array\|null` | This is used to construct the WITH section in a SQL query. Default: `null`. Available since 2.0.35. | `Query` |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| <span id="method-__construct"></span>[`__construct()`](/docs/api/yii/base/baseobject/index.md#method-__construct) | Constructor. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__call"></span>[`__call()`](/docs/api/yii/base/component/index.md#method-__call) | Calls the named method which is not a class method. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__clone"></span>[`__clone()`](/docs/api/yii/base/component/index.md#method-__clone) | This method is called after the object is created by cloning an existing one. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__get"></span>[`__get()`](/docs/api/yii/base/component/index.md#method-__get) | Returns the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__isset"></span>[`__isset()`](/docs/api/yii/base/component/index.md#method-__isset) | Checks if a property is set, i.e. defined and not null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__set"></span>[`__set()`](/docs/api/yii/base/component/index.md#method-__set) | Sets the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`__toString()`](#method-__toString) | Returns the SQL representation of Query | `Query` |
| <span id="method-__unset"></span>[`__unset()`](/docs/api/yii/base/component/index.md#method-__unset) | Sets a component property to be null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`addGroupBy()`](#method-addGroupBy) | Adds additional group-by columns to the existing ones. | `Query` |
| <span id="method-addOrderBy"></span>[`addOrderBy()`](/docs/api/yii/db/querytrait/index.md#method-addOrderBy) | Adds additional ORDER BY columns to the query. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| [`addParams()`](#method-addParams) | Adds additional parameters to be bound to the query. | `Query` |
| [`addSelect()`](#method-addSelect) | Add more columns to the SELECT part of the query. | `Query` |
| [`addUnionOrderBy()`](#method-addUnionOrderBy) | Adds ORDER BY columns to the complete UNION result. | `Query` |
| [`all()`](#method-all) | Executes the query and returns all results as an array. | `Query` |
| [`andFilterCompare()`](#method-andFilterCompare) | Adds a filtering condition for a specific column and allow the user to choose a filter operator. | `Query` |
| [`andFilterHaving()`](#method-andFilterHaving) | Adds an additional HAVING condition to the existing one but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). | `Query` |
| <span id="method-andFilterWhere"></span>[`andFilterWhere()`](/docs/api/yii/db/querytrait/index.md#method-andFilterWhere) | Adds an additional WHERE condition to the existing one but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| [`andHaving()`](#method-andHaving) | Adds an additional HAVING condition to the existing one. | `Query` |
| [`andWhere()`](#method-andWhere) | Adds an additional WHERE condition to the existing one. | `Query` |
| <span id="method-attachBehavior"></span>[`attachBehavior()`](/docs/api/yii/base/component/index.md#method-attachBehavior) | Attaches a behavior to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehaviors"></span>[`attachBehaviors()`](/docs/api/yii/base/component/index.md#method-attachBehaviors) | Attaches a list of behaviors to the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`average()`](#method-average) | Returns the average of the specified column values. | `Query` |
| [`batch()`](#method-batch) | Starts a batch query. | `Query` |
| <span id="method-behaviors"></span>[`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) | Returns a list of behaviors that this component should behave as. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`cache()`](#method-cache) | Enables query cache for this Query. | `Query` |
| <span id="method-canGetProperty"></span>[`canGetProperty()`](/docs/api/yii/base/component/index.md#method-canGetProperty) | Returns a value indicating whether a property can be read. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-canSetProperty"></span>[`canSetProperty()`](/docs/api/yii/base/component/index.md#method-canSetProperty) | Returns a value indicating whether a property can be set. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-className"></span>[`className()`](/docs/api/yii/base/baseobject/index.md#method-className) static | Returns the fully qualified name of this class. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| [`column()`](#method-column) | Executes the query and returns the first column of the result. | `Query` |
| [`count()`](#method-count) | Returns the number of records. | `Query` |
| [`create()`](#method-create) static | Creates a new Query object and copies its property values from an existing one. | `Query` |
| [`createCommand()`](#method-createCommand) | Creates a DB command that can be used to execute this query. | `Query` |
| <span id="method-detachBehavior"></span>[`detachBehavior()`](/docs/api/yii/base/component/index.md#method-detachBehavior) | Detaches a behavior from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-detachBehaviors"></span>[`detachBehaviors()`](/docs/api/yii/base/component/index.md#method-detachBehaviors) | Detaches all behaviors from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`distinct()`](#method-distinct) | Sets the value indicating whether to SELECT DISTINCT or not. | `Query` |
| [`each()`](#method-each) | Starts a batch query and retrieves data row by row. | `Query` |
| <span id="method-emulateExecution"></span>[`emulateExecution()`](/docs/api/yii/db/querytrait/index.md#method-emulateExecution) | Sets whether to emulate query execution, preventing any interaction with data storage. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-ensureBehaviors"></span>[`ensureBehaviors()`](/docs/api/yii/base/component/index.md#method-ensureBehaviors) | Makes sure that the behaviors declared in [`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) are attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`exists()`](#method-exists) | Returns a value indicating whether the query result contains any row of data. | `Query` |
| [`filterHaving()`](#method-filterHaving) | Sets the HAVING part of the query but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). | `Query` |
| <span id="method-filterWhere"></span>[`filterWhere()`](/docs/api/yii/db/querytrait/index.md#method-filterWhere) | Sets the WHERE part of the query but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| [`from()`](#method-from) | Sets the FROM part of the query. | `Query` |
| <span id="method-getBehavior"></span>[`getBehavior()`](/docs/api/yii/base/component/index.md#method-getBehavior) | Returns the named behavior object. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getBehaviors"></span>[`getBehaviors()`](/docs/api/yii/base/component/index.md#method-getBehaviors) | Returns all behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`getTablesUsedInFrom()`](#method-getTablesUsedInFrom) | Returns table names used in [`from()`](/docs/api/yii/db/query/index.md#method-from) indexed by aliases. | `Query` |
| [`groupBy()`](#method-groupBy) | Sets the GROUP BY part of the query. | `Query` |
| <span id="method-hasEventHandlers"></span>[`hasEventHandlers()`](/docs/api/yii/base/component/index.md#method-hasEventHandlers) | Returns a value indicating whether there is any handler attached to the named event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasMethod"></span>[`hasMethod()`](/docs/api/yii/base/component/index.md#method-hasMethod) | Returns a value indicating whether a method is defined. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasProperty"></span>[`hasProperty()`](/docs/api/yii/base/component/index.md#method-hasProperty) | Returns a value indicating whether a property is defined for this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`having()`](#method-having) | Sets the HAVING part of the query. | `Query` |
| <span id="method-indexBy"></span>[`indexBy()`](/docs/api/yii/db/querytrait/index.md#method-indexBy) | Sets the [`indexBy()`](/docs/api/yii/db/querytrait/index.md#method-indexBy) property. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-init"></span>[`init()`](/docs/api/yii/base/baseobject/index.md#method-init) | Initializes the object. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| [`innerJoin()`](#method-innerJoin) | Appends an INNER JOIN part to the query. | `Query` |
| [`join()`](#method-join) | Appends a JOIN part to the query. | `Query` |
| [`leftJoin()`](#method-leftJoin) | Appends a LEFT OUTER JOIN part to the query. | `Query` |
| <span id="method-limit"></span>[`limit()`](/docs/api/yii/db/querytrait/index.md#method-limit) | Sets the LIMIT part of the query. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| [`max()`](#method-max) | Returns the maximum of the specified column values. | `Query` |
| [`min()`](#method-min) | Returns the minimum of the specified column values. | `Query` |
| [`noCache()`](#method-noCache) | Disables query cache for this Query. | `Query` |
| <span id="method-off"></span>[`off()`](/docs/api/yii/base/component/index.md#method-off) | Detaches an existing event handler from this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-offset"></span>[`offset()`](/docs/api/yii/db/querytrait/index.md#method-offset) | Sets the OFFSET part of the query. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-on"></span>[`on()`](/docs/api/yii/base/component/index.md#method-on) | Attaches an event handler to an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`one()`](#method-one) | Executes the query and returns a single row of result. | `Query` |
| <span id="method-orderBy"></span>[`orderBy()`](/docs/api/yii/db/querytrait/index.md#method-orderBy) | Sets the ORDER BY part of the query. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| [`orFilterHaving()`](#method-orFilterHaving) | Adds an additional HAVING condition to the existing one but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). | `Query` |
| <span id="method-orFilterWhere"></span>[`orFilterWhere()`](/docs/api/yii/db/querytrait/index.md#method-orFilterWhere) | Adds an additional WHERE condition to the existing one but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| [`orHaving()`](#method-orHaving) | Adds an additional HAVING condition to the existing one. | `Query` |
| [`orWhere()`](#method-orWhere) | Adds an additional WHERE condition to the existing one. | `Query` |
| [`params()`](#method-params) | Sets the parameters to be bound to the query. | `Query` |
| [`populate()`](#method-populate) | Converts the raw query results into the format as specified by this query. | `Query` |
| [`prepare()`](#method-prepare) | Prepares for building SQL. | `Query` |
| [`rightJoin()`](#method-rightJoin) | Appends a RIGHT OUTER JOIN part to the query. | `Query` |
| [`scalar()`](#method-scalar) | Returns the query result as a scalar value. | `Query` |
| [`select()`](#method-select) | Sets the SELECT part of the query. | `Query` |
| [`sum()`](#method-sum) | Returns the sum of the specified column values. | `Query` |
| <span id="method-trigger"></span>[`trigger()`](/docs/api/yii/base/component/index.md#method-trigger) | Triggers an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`union()`](#method-union) | Appends a SQL statement using UNION operator. | `Query` |
| [`unionLimit()`](#method-unionLimit) | Sets the LIMIT part of the complete UNION result. | `Query` |
| [`unionOffset()`](#method-unionOffset) | Sets the OFFSET part of the complete UNION result. | `Query` |
| [`unionOrderBy()`](#method-unionOrderBy) | Sets the ORDER BY part of the complete UNION result. | `Query` |
| [`where()`](#method-where) | Sets the WHERE part of the query. | `Query` |
| [`withQuery()`](#method-withQuery) | Prepends a SQL statement using WITH syntax. | `Query` |
| [`cleanUpTableNames()`](#method-cleanUpTableNames) protected | Clean up table names and aliases Both aliases and names are enclosed into {{ and }}. | `Query` |
| <span id="method-filterCondition"></span>[`filterCondition()`](/docs/api/yii/db/querytrait/index.md#method-filterCondition) protected | Removes [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty) from the given query condition. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-isEmpty"></span>[`isEmpty()`](/docs/api/yii/db/querytrait/index.md#method-isEmpty) protected | Returns a value indicating whether the give value is "empty". | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| <span id="method-normalizeOrderBy"></span>[`normalizeOrderBy()`](/docs/api/yii/db/querytrait/index.md#method-normalizeOrderBy) protected | Normalizes format of ORDER BY data. | [`QueryTrait`](/docs/api/yii/db/querytrait/index.md) |
| [`normalizeSelect()`](#method-normalizeSelect) protected | Normalizes the SELECT columns passed to [`select()`](/docs/api/yii/db/query/index.md#method-select) or [`addSelect()`](/docs/api/yii/db/query/index.md#method-addSelect). | `Query` |
| [`queryScalar()`](#method-queryScalar) protected | Queries a scalar value by setting [`select()`](/docs/api/yii/db/query/index.md#method-select) first. | `Query` |
| [`setCommandCache()`](#method-setCommandCache) protected | Sets $command cache, if this query has enabled caching. | `Query` |

## Property details

### $distinct <span id="property-distinct"></span>

```php
public bool $distinct = false
```

Whether to select distinct rows of data only.

If this is set true,
the SELECT clause would be changed to SELECT DISTINCT.

### $from <span id="property-from"></span>

```php
public array|string|null $from = null
```

The table(s) to be selected from.

For example, `['user', 'post']`.
This is used to construct the FROM clause in a SQL statement.

### $groupBy <span id="property-groupBy"></span>

```php
public array|null $groupBy = null
```

How to group the query results.

For example, `['company', 'department']`.
This is used to construct the GROUP BY clause in a SQL statement.

### $having <span id="property-having"></span>

```php
public string|array|yii\db\ExpressionInterface|null $having = null
```

The condition to be applied in the GROUP BY clause.

It can be either a string or an array. Please refer to [`where()`](/docs/api/yii/db/query/index.md#method-where) on how to specify the condition.

### $join <span id="property-join"></span>

```php
public array|null $join = null
```

How to join with other tables.

Each array element represents the specification
of one join which has the following structure:

```
[$joinType, $tableName, $joinCondition]
```

For example,

```
[
    ['INNER JOIN', 'user', 'user.id = author_id'],
    ['LEFT JOIN', 'team', 'team.id = team_id'],
]
```

### $params <span id="property-params"></span>

```php
public array|null $params = []
```

List of query parameter values indexed by parameter placeholders.

For example, `[':name' => 'Dan', ':age' => 31]`.

### $queryCacheDuration <span id="property-queryCacheDuration"></span>

```php
public int|bool|null $queryCacheDuration = null
```

The default number of seconds that query results can remain valid in cache.

Use 0 to indicate that the cached data will never expire.
Use a negative number to indicate that query cache should not be used.
Use boolean `true` to indicate that [`Connection::$queryCacheDuration`](/docs/api/yii/db/connection/index.md#property-queryCacheDuration) should be used.

**Since**

2.0.14

### $select <span id="property-select"></span>

```php
public array|null $select = null
```

The columns being selected.

For example, `['id', 'name']`.
This is used to construct the SELECT clause in a SQL statement. If not set, it means selecting all columns.

### $selectOption <span id="property-selectOption"></span>

```php
public string|null $selectOption = null
```

Additional option that should be appended to the 'SELECT' keyword.

For example,
in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.

### $union <span id="property-union"></span>

```php
public array|null $union = null
```

This is used to construct the UNION clause(s) in a SQL statement.

Each array element is an array of the following structure:

- `query`: either a string or a [`Query`](/docs/api/yii/db/query/index.md) object representing a query
- `all`: boolean, whether it should be `UNION ALL` or `UNION`

### $withQueries <span id="property-withQueries"></span>

```php
public array|null $withQueries = null
```

This is used to construct the WITH section in a SQL query.

Each array element is an array of the following structure:

- `query`: either a string or a [`Query`](/docs/api/yii/db/query/index.md) object representing a query
- `alias`: string, alias of query for further usage
- `recursive`: boolean, whether it should be `WITH RECURSIVE` or `WITH`

**Since**

2.0.35

## Method details

### __toString() <span id="method-__toString"></span>

```php
public function __toString(): string
```

Returns the SQL representation of Query

**Returns**

`string`

### addGroupBy() <span id="method-addGroupBy"></span>

```php
public function addGroupBy(string|array|yii\db\ExpressionInterface $columns): $this
```

Adds additional group-by columns to the existing ones.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$columns` | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) | Additional columns to be grouped by. Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression). Note that if your group-by is an expression containing commas, you should always use an array to represent the group-by information. Otherwise, the method will not be able to correctly determine the group-by columns. Since version 2.0.7, an [`Expression`](/docs/api/yii/db/expression/index.md) object can be passed to specify the GROUP BY part explicitly in plain SQL. Since version 2.0.14, an [`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) object can be passed as well. |

**Returns**

`$this`: The query object itself

**See also**

- [`groupBy()`](/docs/api/yii/db/query/index.md#method-groupBy)

### addParams() <span id="method-addParams"></span>

```php
public function addParams(array $params): $this
```

Adds additional parameters to be bound to the query.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$params` | `array` | List of query parameter values indexed by parameter placeholders. For example, `[':name' => 'Dan', ':age' => 31]`. |

**Returns**

`$this`: The query object itself

**See also**

- [`params()`](/docs/api/yii/db/query/index.md#method-params)

### addSelect() <span id="method-addSelect"></span>

```php
public function addSelect(string|array|yii\db\ExpressionInterface $columns): $this
```

Add more columns to the SELECT part of the query.

Note, that if [`select()`](/docs/api/yii/db/query/index.md#method-select) has not been specified before, you should include `*` explicitly
if you want to select all remaining columns too:

```
$query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$columns` | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) | The columns to add to the select. See [`select()`](/docs/api/yii/db/query/index.md#method-select) for more details about the format of this parameter. |

**Returns**

`$this`: The query object itself

**See also**

- [`select()`](/docs/api/yii/db/query/index.md#method-select)

### addUnionOrderBy() <span id="method-addUnionOrderBy"></span>

```php
public function addUnionOrderBy(array<int|string, int|yii\db\ExpressionInterface>|string|yii\db\ExpressionInterface|null $columns): static
```

Adds ORDER BY columns to the complete UNION result.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$columns` | `array<int\|string, int\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`>\|string\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | The columns (and the directions) to be ordered by. |

**Returns**

`static`: The query object itself.

**Since**

22.0

**See also**

- [`unionOrderBy()`](/docs/api/yii/db/query/index.md#method-unionOrderBy)

### all() <span id="method-all"></span>

```php
public function all(yii\db\Connection|null $db = null): array
```

Executes the query and returns all results as an array.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to generate the SQL statement. If this parameter is not given, the `db` application component will be used. |

**Returns**

`array`: The query results. If the query results in nothing, an empty array will be returned.

### andFilterCompare() <span id="method-andFilterCompare"></span>

```php
public function andFilterCompare(string $name, string $value, string $defaultOperator = '='): $this
```

Adds a filtering condition for a specific column and allow the user to choose a filter operator.

It adds an additional WHERE condition for the given field and determines the comparison operator
based on the first few characters of the given value.
The condition is added in the same way as in [`andFilterWhere()`](/docs/api/yii/db/querytrait/index.md#method-andFilterWhere) so [empty values](/docs/api/yii/db/querytrait/index.md#method-isEmpty) are ignored.
The new condition and the existing one will be joined using the `AND` operator.

The comparison operator is intelligently determined based on the first few characters in the given value.
In particular, it recognizes the following operators if they appear as the leading characters in the given value:

- `<`: the column must be less than the given value.
- `>`: the column must be greater than the given value.
- `<=`: the column must be less than or equal to the given value.
- `>=`: the column must be greater than or equal to the given value.
- `<>`: the column must not be the same as the given value.
- `=`: the column must be equal to the given value.
- If none of the above operators is detected, the `$defaultOperator` will be used.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The column name. |
| `$value` | `string` | The column value optionally prepended with the comparison operator. |
| `$defaultOperator` | `string` | The operator to use, when no operator is given in `$value`. Defaults to `=`, performing an exact match. |

**Returns**

`$this`: The query object itself

**Since**

2.0.8

### andFilterHaving() <span id="method-andFilterHaving"></span>

```php
public function andFilterHaving(array $condition): $this
```

Adds an additional HAVING condition to the existing one but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty).

The new condition and the existing one will be joined using the `AND` operator.

This method is similar to [`andHaving()`](/docs/api/yii/db/query/index.md#method-andHaving). The main difference is that this method will
remove [empty query operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). As a result, this method is best suited
for building query conditions based on filter values entered by users.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `array` | The new HAVING condition. Please refer to [`having()`](/docs/api/yii/db/query/index.md#method-having) on how to specify this parameter. |

**Returns**

`$this`: The query object itself

**Since**

2.0.11

**See also**

- [`filterHaving()`](/docs/api/yii/db/query/index.md#method-filterHaving)
- [`orFilterHaving()`](/docs/api/yii/db/query/index.md#method-orFilterHaving)

### andHaving() <span id="method-andHaving"></span>

```php
public function andHaving(string|array|yii\db\ExpressionInterface $condition, array $params = []): $this
```

Adds an additional HAVING condition to the existing one.

The new condition and the existing one will be joined using the `AND` operator.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) | The new HAVING condition. Please refer to [`where()`](/docs/api/yii/db/query/index.md#method-where) on how to specify this parameter. |
| `$params` | `array` | The parameters (name => value) to be bound to the query. |

**Returns**

`$this`: The query object itself

**See also**

- [`having()`](/docs/api/yii/db/query/index.md#method-having)
- [`orHaving()`](/docs/api/yii/db/query/index.md#method-orHaving)

### andWhere() <span id="method-andWhere"></span>

```php
public function andWhere(string|array|yii\db\ExpressionInterface $condition, array $params = []): $this
```

Adds an additional WHERE condition to the existing one.

The new condition and the existing one will be joined using the `AND` operator.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) | The new WHERE condition. Please refer to [`where()`](/docs/api/yii/db/query/index.md#method-where) on how to specify this parameter. |
| `$params` | `array` | The parameters (name => value) to be bound to the query. |

**Returns**

`$this`: The query object itself

**See also**

- [`where()`](/docs/api/yii/db/query/index.md#method-where)
- [`orWhere()`](/docs/api/yii/db/query/index.md#method-orWhere)

### average() <span id="method-average"></span>

```php
public function average(string $q, yii\db\Connection|null $db = null): mixed
```

Returns the average of the specified column values.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$q` | `string` | The column name or expression. Make sure you properly [quote](/docs/guide/db-dao/index.md#quoting-table-and-column-names) column names in the expression. |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to generate the SQL statement. If this parameter is not given, the `db` application component will be used. |

**Returns**

`mixed`: The average of the specified column values.

### batch() <span id="method-batch"></span>

```php
public function batch(int $batchSize = 100, yii\db\Connection|null $db = null): yii\db\BatchQueryResult
```

Starts a batch query.

A batch query supports fetching data in batches, which can keep the memory usage under a limit.
This method will return a [`BatchQueryResult`](/docs/api/yii/db/batchqueryresult/index.md) object which implements the [`Iterator`](https://www.php.net/manual/en/class.iterator.php) interface
and can be traversed to retrieve the data in batches.

For example,

```
$query = (new Query)->from('user');
foreach ($query->batch() as $rows) {
    // $rows is an array of 100 or fewer rows from user table
}
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$batchSize` | `int` | The number of records to be fetched in each batch. |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection. If not set, the "db" application component will be used. |

**Returns**

[`BatchQueryResult`](/docs/api/yii/db/batchqueryresult/index.md): The batch query result. It implements the [`Iterator`](https://www.php.net/manual/en/class.iterator.php) interface and can be traversed to retrieve the data in batches.

### cache() <span id="method-cache"></span>

```php
public function cache(int|true $duration = true, yii\caching\Dependency|null $dependency = null): $this
```

Enables query cache for this Query.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$duration` | `int\|true` | The number of seconds that query results can remain valid in cache. Use 0 to indicate that the cached data will never expire. Use a negative number to indicate that query cache should not be used. Use boolean `true` to indicate that [`Connection::$queryCacheDuration`](/docs/api/yii/db/connection/index.md#property-queryCacheDuration) should be used. Defaults to `true`. |
| `$dependency` | [`yii\caching\Dependency`](/docs/api/yii/caching/dependency/index.md)`\|null` | The cache dependency associated with the cached result. |

**Returns**

`$this`: The Query object itself

**Since**

2.0.14

### column() <span id="method-column"></span>

```php
public function column(yii\db\Connection|null $db = null): array
```

Executes the query and returns the first column of the result.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to generate the SQL statement. If this parameter is not given, the `db` application component will be used. |

**Returns**

`array`: The first column of the query result. An empty array is returned if the query results in nothing.

### count() <span id="method-count"></span>

```php
public function count(string $q = '*', yii\db\Connection|null $db = null): int|string|null
```

Returns the number of records.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$q` | `string` | The COUNT expression. Defaults to '*'. Make sure you properly [quote](/docs/guide/db-dao/index.md#quoting-table-and-column-names) column names in the expression. |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to generate the SQL statement. If this parameter is not given (or null), the `db` application component will be used. |

**Returns**

`int|string|null`: Number of records. The result may be a string depending on the underlying database engine and to support integer values higher than a 32bit PHP integer can handle.

### create() <span id="method-create"></span>

```php
public static function create(yii\db\Query $from): yii\db\Query
```

Creates a new Query object and copies its property values from an existing one.

The properties being copies are the ones to be used by query builders.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$from` | [`Query`](/docs/api/yii/db/query/index.md) | The source query object |

**Returns**

[`Query`](/docs/api/yii/db/query/index.md): The new Query object

### createCommand() <span id="method-createCommand"></span>

```php
public function createCommand(yii\db\Connection|null $db = null): yii\db\Command
```

Creates a DB command that can be used to execute this query.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to generate the SQL statement. If this parameter is not given, the `db` application component will be used. |

**Returns**

[`Command`](/docs/api/yii/db/command/index.md): The created DB command instance.

### distinct() <span id="method-distinct"></span>

```php
public function distinct(bool $value = true): $this
```

Sets the value indicating whether to SELECT DISTINCT or not.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$value` | `bool` | Whether to SELECT DISTINCT or not. |

**Returns**

`$this`: The query object itself

### each() <span id="method-each"></span>

```php
public function each(int $batchSize = 100, yii\db\Connection|null $db = null): yii\db\BatchQueryResult
```

Starts a batch query and retrieves data row by row.

This method is similar to [`batch()`](/docs/api/yii/db/query/index.md#method-batch) except that in each iteration of the result,
only one row of data is returned. For example,

```
$query = (new Query)->from('user');
foreach ($query->each() as $row) {
}
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$batchSize` | `int` | The number of records to be fetched in each batch. |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection. If not set, the "db" application component will be used. |

**Returns**

[`BatchQueryResult`](/docs/api/yii/db/batchqueryresult/index.md): The batch query result. It implements the [`Iterator`](https://www.php.net/manual/en/class.iterator.php) interface and can be traversed to retrieve the data in batches.

### exists() <span id="method-exists"></span>

```php
public function exists(yii\db\Connection|null $db = null): bool
```

Returns a value indicating whether the query result contains any row of data.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to generate the SQL statement. If this parameter is not given, the `db` application component will be used. |

**Returns**

`bool`: Whether the query result contains any row of data.

### filterHaving() <span id="method-filterHaving"></span>

```php
public function filterHaving(array $condition): $this
```

Sets the HAVING part of the query but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty).

This method is similar to [`having()`](/docs/api/yii/db/query/index.md#method-having). The main difference is that this method will
remove [empty query operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). As a result, this method is best suited
for building query conditions based on filter values entered by users.

The following code shows the difference between this method and [`having()`](/docs/api/yii/db/query/index.md#method-having):

```
// HAVING `age`=:age
$query->filterHaving(['name' => null, 'age' => 20]);
// HAVING `age`=:age
$query->having(['age' => 20]);
// HAVING `name` IS NULL AND `age`=:age
$query->having(['name' => null, 'age' => 20]);
```

Note that unlike [`having()`](/docs/api/yii/db/query/index.md#method-having), you cannot pass binding parameters to this method.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `array` | The conditions that should be put in the HAVING part. See [`having()`](/docs/api/yii/db/query/index.md#method-having) on how to specify this parameter. |

**Returns**

`$this`: The query object itself

**Since**

2.0.11

**See also**

- [`having()`](/docs/api/yii/db/query/index.md#method-having)
- [`andFilterHaving()`](/docs/api/yii/db/query/index.md#method-andFilterHaving)
- [`orFilterHaving()`](/docs/api/yii/db/query/index.md#method-orFilterHaving)

### from() <span id="method-from"></span>

```php
public function from(string|array|yii\db\ExpressionInterface $tables): $this
```

Sets the FROM part of the query.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$tables` | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) | The table(s) to be selected from. This can be either a string (e.g. `'user'`) or an array (e.g. `['user', 'profile']`) specifying one or several table names. Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`). The method will automatically quote the table names unless it contains some parenthesis (which means the table is given as a sub-query or DB expression). When the tables are specified as an array, you may also use the array keys as the table aliases (if a table does not need alias, do not use a string key). Use a Query object to represent a sub-query. In this case, the corresponding array key will be used as the alias for the sub-query. To specify the `FROM` part in plain SQL, you may pass an instance of [`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md). Here are some examples: // SELECT * FROM  `user` `u`, `profile`; $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']); // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`; $subquery = (new \yii\db\Query)->from('user')->where(['active' => true]) $query = (new \yii\db\Query)->from(['activeusers' => $subquery]); // subquery can also be a string with plain SQL wrapped in parenthesis // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`; $subquery = "(SELECT * FROM `user` WHERE `active` = 1)"; $query = (new \yii\db\Query)->from(['activeusers' => $subquery]); |

**Returns**

`$this`: The query object itself

### getTablesUsedInFrom() <span id="method-getTablesUsedInFrom"></span>

```php
public function getTablesUsedInFrom(): string[]
```

Returns table names used in [`from()`](/docs/api/yii/db/query/index.md#method-from) indexed by aliases.

Both aliases and names are enclosed into {{ and }}.

**Returns**

`string[]`: Table names indexed by aliases

**Throws**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md)

**Since**

2.0.12

### groupBy() <span id="method-groupBy"></span>

```php
public function groupBy(string|array|yii\db\ExpressionInterface|null $columns): $this
```

Sets the GROUP BY part of the query.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$columns` | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | The columns to be grouped by. Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression). Note that if your group-by is an expression containing commas, you should always use an array to represent the group-by information. Otherwise, the method will not be able to correctly determine the group-by columns. Since version 2.0.7, an [`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) object can be passed to specify the GROUP BY part explicitly in plain SQL. Since version 2.0.14, an [`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) object can be passed as well. |

**Returns**

`$this`: The query object itself

**See also**

- [`addGroupBy()`](/docs/api/yii/db/query/index.md#method-addGroupBy)

### having() <span id="method-having"></span>

```php
public function having(string|array|yii\db\ExpressionInterface $condition, array $params = []): $this
```

Sets the HAVING part of the query.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) | The conditions to be put after HAVING. Please refer to [`where()`](/docs/api/yii/db/query/index.md#method-where) on how to specify this parameter. |
| `$params` | `array` | The parameters (name => value) to be bound to the query. |

**Returns**

`$this`: The query object itself

**See also**

- [`andHaving()`](/docs/api/yii/db/query/index.md#method-andHaving)
- [`orHaving()`](/docs/api/yii/db/query/index.md#method-orHaving)

### innerJoin() <span id="method-innerJoin"></span>

```php
public function innerJoin(string|array $table, string|array $on = '', array $params = []): $this
```

Appends an INNER JOIN part to the query.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$table` | `string\|array` | The table or sub-query to be joined. Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression). You may also specify the table as an array with one element, using the array key as the table alias (e.g. ['u' => 'user']). To join a sub-query, use an array with one element, with the value set to a [`Query`](/docs/api/yii/db/query/index.md) object representing the sub-query, and the corresponding key representing the alias. |
| `$on` | `string\|array` | The join condition that should appear in the ON part. Please refer to [`join()`](/docs/api/yii/db/query/index.md#method-join) on how to specify this parameter. |
| `$params` | `array` | The parameters (name => value) to be bound to the query. |

**Returns**

`$this`: The query object itself

### join() <span id="method-join"></span>

```php
public function join(string $type, string|array $table, string|array $on = '', array $params = []): $this
```

Appends a JOIN part to the query.

The first parameter specifies what type of join it is.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$type` | `string` | The type of join, such as INNER JOIN, LEFT JOIN. |
| `$table` | `string\|array` | The table or sub-query to be joined. Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression). You may also specify the table as an array with one element, using the array key as the table alias (e.g. ['u' => 'user']). To join a sub-query, use an array with one element, with the value set to a [`Query`](/docs/api/yii/db/query/index.md) object representing the sub-query, and the corresponding key representing the alias. |
| `$on` | `string\|array` | The join condition that should appear in the ON part. Please refer to [`where()`](/docs/api/yii/db/query/index.md#method-where) on how to specify this parameter. Note that the array format of [`where()`](/docs/api/yii/db/query/index.md#method-where) is designed to match columns to values instead of columns to columns, so the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would match the `post.author_id` column value against the string `'user.id'`. It is recommended to use the string syntax here which is more suited for a join: 'post.author_id = user.id' |
| `$params` | `array` | The parameters (name => value) to be bound to the query. |

**Returns**

`$this`: The query object itself

### leftJoin() <span id="method-leftJoin"></span>

```php
public function leftJoin(string|array $table, string|array $on = '', array $params = []): $this
```

Appends a LEFT OUTER JOIN part to the query.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$table` | `string\|array` | The table or sub-query to be joined. Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression). You may also specify the table as an array with one element, using the array key as the table alias (e.g. ['u' => 'user']). To join a sub-query, use an array with one element, with the value set to a [`Query`](/docs/api/yii/db/query/index.md) object representing the sub-query, and the corresponding key representing the alias. |
| `$on` | `string\|array` | The join condition that should appear in the ON part. Please refer to [`join()`](/docs/api/yii/db/query/index.md#method-join) on how to specify this parameter. |
| `$params` | `array` | The parameters (name => value) to be bound to the query |

**Returns**

`$this`: The query object itself

### max() <span id="method-max"></span>

```php
public function max(string $q, yii\db\Connection|null $db = null): mixed
```

Returns the maximum of the specified column values.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$q` | `string` | The column name or expression. Make sure you properly [quote](/docs/guide/db-dao/index.md#quoting-table-and-column-names) column names in the expression. |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to generate the SQL statement. If this parameter is not given, the `db` application component will be used. |

**Returns**

`mixed`: The maximum of the specified column values.

### min() <span id="method-min"></span>

```php
public function min(string $q, yii\db\Connection|null $db = null): mixed
```

Returns the minimum of the specified column values.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$q` | `string` | The column name or expression. Make sure you properly [quote](/docs/guide/db-dao/index.md#quoting-table-and-column-names) column names in the expression. |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to generate the SQL statement. If this parameter is not given, the `db` application component will be used. |

**Returns**

`mixed`: The minimum of the specified column values.

### noCache() <span id="method-noCache"></span>

```php
public function noCache(): $this
```

Disables query cache for this Query.

**Returns**

`$this`: The Query object itself

**Since**

2.0.14

### one() <span id="method-one"></span>

```php
public function one(yii\db\Connection|null $db = null): array|bool
```

Executes the query and returns a single row of result.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to generate the SQL statement. If this parameter is not given, the `db` application component will be used. |

**Returns**

`array|bool`: The first row (in terms of an array) of the query result. False is returned if the query results in nothing.

### orFilterHaving() <span id="method-orFilterHaving"></span>

```php
public function orFilterHaving(array $condition): $this
```

Adds an additional HAVING condition to the existing one but ignores [empty operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty).

The new condition and the existing one will be joined using the `OR` operator.

This method is similar to [`orHaving()`](/docs/api/yii/db/query/index.md#method-orHaving). The main difference is that this method will
remove [empty query operands](/docs/api/yii/db/querytrait/index.md#method-isEmpty). As a result, this method is best suited
for building query conditions based on filter values entered by users.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `array` | The new HAVING condition. Please refer to [`having()`](/docs/api/yii/db/query/index.md#method-having) on how to specify this parameter. |

**Returns**

`$this`: The query object itself

**Since**

2.0.11

**See also**

- [`filterHaving()`](/docs/api/yii/db/query/index.md#method-filterHaving)
- [`andFilterHaving()`](/docs/api/yii/db/query/index.md#method-andFilterHaving)

### orHaving() <span id="method-orHaving"></span>

```php
public function orHaving(string|array|yii\db\ExpressionInterface $condition, array $params = []): $this
```

Adds an additional HAVING condition to the existing one.

The new condition and the existing one will be joined using the `OR` operator.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) | The new HAVING condition. Please refer to [`where()`](/docs/api/yii/db/query/index.md#method-where) on how to specify this parameter. |
| `$params` | `array` | The parameters (name => value) to be bound to the query. |

**Returns**

`$this`: The query object itself

**See also**

- [`having()`](/docs/api/yii/db/query/index.md#method-having)
- [`andHaving()`](/docs/api/yii/db/query/index.md#method-andHaving)

### orWhere() <span id="method-orWhere"></span>

```php
public function orWhere(string|array|yii\db\ExpressionInterface $condition, array $params = []): $this
```

Adds an additional WHERE condition to the existing one.

The new condition and the existing one will be joined using the `OR` operator.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) | The new WHERE condition. Please refer to [`where()`](/docs/api/yii/db/query/index.md#method-where) on how to specify this parameter. |
| `$params` | `array` | The parameters (name => value) to be bound to the query. |

**Returns**

`$this`: The query object itself

**See also**

- [`where()`](/docs/api/yii/db/query/index.md#method-where)
- [`andWhere()`](/docs/api/yii/db/query/index.md#method-andWhere)

### params() <span id="method-params"></span>

```php
public function params(array $params): $this
```

Sets the parameters to be bound to the query.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$params` | `array` | List of query parameter values indexed by parameter placeholders. For example, `[':name' => 'Dan', ':age' => 31]`. |

**Returns**

`$this`: The query object itself

**See also**

- [`addParams()`](/docs/api/yii/db/query/index.md#method-addParams)

### populate() <span id="method-populate"></span>

```php
public function populate(array $rows, yii\db\Connection|null $db = null): array
```

Converts the raw query results into the format as specified by this query.

This method is internally used to convert the data fetched from database into the format as required by this
query.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$rows` | `array` | The raw query result from database. |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to retrieve the rows. |

**Returns**

`array`: The converted query result.

### prepare() <span id="method-prepare"></span>

```php
public function prepare(yii\db\QueryBuilder $builder): self
```

Prepares for building SQL.

This method is called by [`QueryBuilder`](/docs/api/yii/db/querybuilder/index.md) when it starts to build SQL from a query object.
You may override this method to do some final preparation work when converting a query into a SQL statement.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$builder` | [`QueryBuilder`](/docs/api/yii/db/querybuilder/index.md) |  |

**Returns**

`self`: A prepared query instance which will be used by [`QueryBuilder`](/docs/api/yii/db/querybuilder/index.md) to build the SQL

### rightJoin() <span id="method-rightJoin"></span>

```php
public function rightJoin(string|array $table, string|array $on = '', array $params = []): $this
```

Appends a RIGHT OUTER JOIN part to the query.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$table` | `string\|array` | The table or sub-query to be joined. Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression). You may also specify the table as an array with one element, using the array key as the table alias (e.g. ['u' => 'user']). To join a sub-query, use an array with one element, with the value set to a [`Query`](/docs/api/yii/db/query/index.md) object representing the sub-query, and the corresponding key representing the alias. |
| `$on` | `string\|array` | The join condition that should appear in the ON part. Please refer to [`join()`](/docs/api/yii/db/query/index.md#method-join) on how to specify this parameter. |
| `$params` | `array` | The parameters (name => value) to be bound to the query |

**Returns**

`$this`: The query object itself

### scalar() <span id="method-scalar"></span>

```php
public function scalar(yii\db\Connection|null $db = null): string|int|null|false
```

Returns the query result as a scalar value.

The value returned will be the first column in the first row of the query results.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to generate the SQL statement. If this parameter is not given, the `db` application component will be used. |

**Returns**

`string|int|null|false`: The value of the first column in the first row of the query result. False is returned if the query result is empty.

### select() <span id="method-select"></span>

```php
public function select(string|array|yii\db\ExpressionInterface $columns, string|null $option = null): $this
```

Sets the SELECT part of the query.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$columns` | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) | The columns to be selected. Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id"). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression). A DB expression may also be passed in form of an [`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) object. Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts. When the columns are specified as an array, you may also use array keys as the column aliases (if a column does not need alias, do not use a string key). Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column as a `Query` instance representing the sub-query. |
| `$option` | `string\|null` | Additional option that should be appended to the 'SELECT' keyword. For example, in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used. |

**Returns**

`$this`: The query object itself

### sum() <span id="method-sum"></span>

```php
public function sum(string $q, yii\db\Connection|null $db = null): mixed
```

Returns the sum of the specified column values.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$q` | `string` | The column name or expression. Make sure you properly [quote](/docs/guide/db-dao/index.md#quoting-table-and-column-names) column names in the expression. |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to generate the SQL statement. If this parameter is not given, the `db` application component will be used. |

**Returns**

`mixed`: The sum of the specified column values.

### union() <span id="method-union"></span>

```php
public function union(string|yii\db\Query $sql, bool $all = false): $this
```

Appends a SQL statement using UNION operator.

[`orderBy()`](/docs/api/yii/db/querytrait/index.md#method-orderBy), [`limit()`](/docs/api/yii/db/querytrait/index.md#method-limit), and [`offset()`](/docs/api/yii/db/querytrait/index.md#method-offset) configure the first SELECT statement. Use [`unionOrderBy()`](/docs/api/yii/db/query/index.md#method-unionOrderBy),
[`unionLimit()`](/docs/api/yii/db/query/index.md#method-unionLimit), and [`unionOffset()`](/docs/api/yii/db/query/index.md#method-unionOffset) to configure the complete UNION result.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$sql` | `string\|`[`Query`](/docs/api/yii/db/query/index.md) | The SQL statement to be appended using UNION |
| `$all` | `bool` | TRUE if using UNION ALL and FALSE if using UNION |

**Returns**

`$this`: The query object itself

### unionLimit() <span id="method-unionLimit"></span>

```php
public function unionLimit(int|yii\db\ExpressionInterface|null $limit): static
```

Sets the LIMIT part of the complete UNION result.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$limit` | `int\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | The limit. Use `null` or a negative value to disable it. |

**Returns**

`static`: The query object itself.

**Since**

22.0

### unionOffset() <span id="method-unionOffset"></span>

```php
public function unionOffset(int|yii\db\ExpressionInterface|null $offset): static
```

Sets the OFFSET part of the complete UNION result.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$offset` | `int\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | The offset. Use null or a negative value to disable it. |

**Returns**

`static`: The query object itself.

**Since**

22.0

### unionOrderBy() <span id="method-unionOrderBy"></span>

```php
public function unionOrderBy(array<int|string, int|yii\db\ExpressionInterface>|string|yii\db\ExpressionInterface|null $columns): static
```

Sets the ORDER BY part of the complete UNION result.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$columns` | `array<int\|string, int\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`>\|string\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md)`\|null` | The columns (and the directions) to be ordered by. |

**Returns**

`static`: The query object itself.

**Since**

22.0

**See also**

- [`addUnionOrderBy()`](/docs/api/yii/db/query/index.md#method-addUnionOrderBy)

### where() <span id="method-where"></span>

```php
public function where(string|array|yii\db\ExpressionInterface $condition, array $params = []): $this
```

Sets the WHERE part of the query.

The method requires a `$condition` parameter, and optionally a `$params` parameter
specifying the values to be bound to the query.

The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) | The conditions that should be put in the WHERE part. |
| `$params` | `array` | The parameters (name => value) to be bound to the query. |

**Returns**

`$this`: The query object itself

**See also**

- [`andWhere()`](/docs/api/yii/db/query/index.md#method-andWhere)
- [`orWhere()`](/docs/api/yii/db/query/index.md#method-orWhere)
- [`QueryInterface::where()`](/docs/api/yii/db/queryinterface/index.md#method-where)

### withQuery() <span id="method-withQuery"></span>

```php
public function withQuery(string|yii\db\Query $query, string $alias, bool $recursive = false): $this
```

Prepends a SQL statement using WITH syntax.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$query` | `string\|`[`Query`](/docs/api/yii/db/query/index.md) | The SQL statement to be prepended using WITH |
| `$alias` | `string` | Query alias in WITH construction |
| `$recursive` | `bool` | TRUE if using WITH RECURSIVE and FALSE if using WITH |

**Returns**

`$this`: The query object itself

**Since**

2.0.35

### cleanUpTableNames() <span id="method-cleanUpTableNames"></span>

```php
protected function cleanUpTableNames(array $tableNames): string[]
```

Clean up table names and aliases
Both aliases and names are enclosed into {{ and }}.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$tableNames` | `array` | Non-empty array |

**Returns**

`string[]`: Table names indexed by aliases

**Since**

2.0.14

### normalizeSelect() <span id="method-normalizeSelect"></span>

```php
protected function normalizeSelect(string|array|yii\db\ExpressionInterface $columns): array
```

Normalizes the SELECT columns passed to [`select()`](/docs/api/yii/db/query/index.md#method-select) or [`addSelect()`](/docs/api/yii/db/query/index.md#method-addSelect).

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$columns` | `string\|array\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) |  |

**Returns**

`array`

**Since**

2.0.21

### queryScalar() <span id="method-queryScalar"></span>

```php
protected function queryScalar(string|yii\db\ExpressionInterface $selectExpression, yii\db\Connection|null $db): bool|string|null
```

Queries a scalar value by setting [`select()`](/docs/api/yii/db/query/index.md#method-select) first.

Restores the value of select to make this query reusable.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$selectExpression` | `string\|`[`ExpressionInterface`](/docs/api/yii/db/expressioninterface/index.md) |  |
| `$db` | [`Connection`](/docs/api/yii/db/connection/index.md)`\|null` | The database connection used to execute the query. |

**Returns**

`bool|string|null`

**Throws**

- [`Throwable`](https://www.php.net/manual/en/class.throwable.php): if can't create command

### setCommandCache() <span id="method-setCommandCache"></span>

```php
protected function setCommandCache(yii\db\Command $command): yii\db\Command
```

Sets $command cache, if this query has enabled caching.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$command` | [`Command`](/docs/api/yii/db/command/index.md) |  |

**Returns**

[`Command`](/docs/api/yii/db/command/index.md)

**Since**

2.0.14