Skip to content
PHP Ecosystem
Explore

QueryBuilder

API reference › yii › db › mssql › QueryBuilder

classyii\db\mssql\QueryBuilder
Extendsyii\db\QueryBuilder » yii\base\BaseObject
Implementsyii\base\Configurable
Since2.0
Sourceframework/db/mssql/QueryBuilder.php

QueryBuilder is the query builder for MS SQL Server databases (version 2019 and above).

PropertyTypeDescriptionDefined by
$dbyii\db\ConnectionThe database connection. Default: null.yii\db\QueryBuilder
$separatorstringThe separator between different fragments of a SQL statement. Default: ' '.yii\db\QueryBuilder
$typeMaparrayMapping from abstract column types (keys) to physical column types (values). Default: [\yii\db\mssql\Schema::TYPE_PK => 'int IDENTITY PRIMARY KEY', \yii\db\mssql\Schema::TYPE_UPK => 'int IDENTITY PRIMARY KEY', \yii\db\mssql\Schema::TYPE_BIGPK => 'bigint IDENTITY PRIMARY KEY', \yii\db\mssql\Schema::TYPE_UBIGPK => 'bigint IDENTITY PRIMARY KEY', \yii\db\mssql\Schema::TYPE_CHAR => 'nchar(1)', \yii\db\mssql\Schema::TYPE_STRING => 'nvarchar(255)', \yii\db\mssql\Schema::TYPE_TEXT => 'nvarchar(max)', \yii\db\mssql\Schema::TYPE_TINYINT => 'tinyint', \yii\db\mssql\Schema::TYPE_SMALLINT => 'smallint', \yii\db\mssql\Schema::TYPE_INTEGER => 'int', \yii\db\mssql\Schema::TYPE_BIGINT => 'bigint', \yii\db\mssql\Schema::TYPE_FLOAT => 'float', \yii\db\mssql\Schema::TYPE_DOUBLE => 'float', \yii\db\mssql\Schema::TYPE_DECIMAL => 'decimal(18,0)', \yii\db\mssql\Schema::TYPE_DATETIME => 'datetime', \yii\db\mssql\Schema::TYPE_TIMESTAMP => 'datetime', \yii\db\mssql\Schema::TYPE_TIME => 'time', \yii\db\mssql\Schema::TYPE_DATE => 'date', \yii\db\mssql\Schema::TYPE_BINARY => 'varbinary(max)', \yii\db\mssql\Schema::TYPE_BOOLEAN => 'bit', \yii\db\mssql\Schema::TYPE_MONEY => 'decimal(19,4)'].QueryBuilder
$conditionClasses protectedarrayMap of condition aliases to condition classes. Default: []. Available since 2.0.14.yii\db\QueryBuilder
$expressionBuilders protectedstring[]|yii\db\ExpressionBuilderInterface[]Maps expression class to expression builder class. Default: []. Available since 2.0.14.yii\db\QueryBuilder
MethodDescriptionDefined by
__construct()Constructor.yii\db\QueryBuilder
__call()Calls the named method which is not a class method.yii\base\BaseObject
__get()Returns the value of an object property.yii\base\BaseObject
__isset()Checks if a property is set, i.e. defined and not null.yii\base\BaseObject
__set()Sets value of an object property.yii\base\BaseObject
__unset()Sets an object property to null.yii\base\BaseObject
addCheck()Creates a SQL command for adding a check constraint to an existing table.yii\db\QueryBuilder
addColumn()Builds a SQL statement for adding a new DB column.yii\db\QueryBuilder
addCommentOnColumn()Builds a SQL command for adding comment to column.QueryBuilder
addCommentOnTable()Builds a SQL command for adding comment to table.QueryBuilder
addDefaultValue()Creates a SQL command for adding a default value constraint to an existing table.QueryBuilder
addForeignKey()Builds a SQL statement for adding a foreign key constraint to an existing table.yii\db\QueryBuilder
addPrimaryKey()Builds a SQL statement for adding a primary key constraint to an existing table.yii\db\QueryBuilder
addUnique()Creates a SQL command for adding an unique constraint to an existing table.yii\db\QueryBuilder
alterColumn()Builds a SQL statement for changing the definition of a column.QueryBuilder
batchInsert()Generates a batch INSERT SQL statement.yii\db\QueryBuilder
bindParam()Helper method to add $value to $params array using PARAM_PREFIX.yii\db\QueryBuilder
build()Generates a SELECT SQL statement from a Query object.yii\db\QueryBuilder
buildColumns()Processes columns and properly quotes them if necessary.yii\db\QueryBuilder
buildCondition()Parses the condition specification and generates the corresponding SQL expression.yii\db\QueryBuilder
buildExpression()Builds given $expressionyii\db\QueryBuilder
buildFrom()yii\db\QueryBuilder
buildGroupBy()yii\db\QueryBuilder
buildHaving()yii\db\QueryBuilder
buildJoin()yii\db\QueryBuilder
buildLimit()yii\db\QueryBuilder
buildOrderBy()yii\db\QueryBuilder
buildOrderByAndLimit()Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.QueryBuilder
buildSelect()yii\db\QueryBuilder
buildUnion()yii\db\QueryBuilder
buildUnionOrderByAndLimit()Builds the global ORDER BY and LIMIT/OFFSET clauses for a UNION query.QueryBuilder
buildWhere()yii\db\QueryBuilder
buildWithQueries()QueryBuilder
canGetProperty()Returns a value indicating whether a property can be read.yii\base\BaseObject
canSetProperty()Returns a value indicating whether a property can be set.yii\base\BaseObject
checkIntegrity()Builds a SQL statement for enabling or disabling integrity checks on table constraints.QueryBuilder
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
createConditionFromArray()Transforms $condition defined in array format (as described in Query::where() to instance of ConditionInterface according to $conditionClasses map.yii\db\QueryBuilder
createIndex()Builds a SQL statement for creating a new index.yii\db\QueryBuilder
createTable()Builds a SQL statement for creating a new DB table.yii\db\QueryBuilder
createView()Creates a SQL View.yii\db\QueryBuilder
delete()Creates a DELETE SQL statement.QueryBuilder
dropCheck()Creates a SQL command for dropping a check constraint.yii\db\QueryBuilder
dropColumn()Drop all constraints before column delete.QueryBuilder
dropCommentFromColumn()Builds a SQL command for adding comment to column.QueryBuilder
dropCommentFromTable()Builds a SQL command for adding comment to table.QueryBuilder
dropDefaultValue()Creates a SQL command for dropping a default value constraint.QueryBuilder
dropForeignKey()Builds a SQL statement for dropping a foreign key constraint.yii\db\QueryBuilder
dropIndex()Builds a SQL statement for dropping an index.yii\db\QueryBuilder
dropPrimaryKey()Builds a SQL statement for removing a primary key constraint to an existing table.yii\db\QueryBuilder
dropTable()Builds a SQL statement for dropping a DB table.yii\db\QueryBuilder
dropUnique()Creates a SQL command for dropping an unique constraint.yii\db\QueryBuilder
dropView()Drops a SQL View.yii\db\QueryBuilder
executeResetSequence()Execute a SQL statement for resetting the sequence value of a table’s primary key.yii\db\QueryBuilder
getColumnType()Converts an abstract column type into a physical column type.QueryBuilder
getExpressionBuilder()Gets object of ExpressionBuilderInterface that is suitable for $expression.yii\db\QueryBuilder
hasMethod()Returns a value indicating whether a method is defined.yii\base\BaseObject
hasProperty()Returns a value indicating whether a property is defined.yii\base\BaseObject
init()Initializes the object.yii\db\QueryBuilder
insert()Creates an INSERT SQL statement.QueryBuilder
renameColumn()Builds a SQL statement for renaming a column.QueryBuilder
renameTable()Builds a SQL statement for renaming a DB table.QueryBuilder
resetSequence()Creates a SQL statement for resetting the sequence value of a table’s primary key.QueryBuilder
selectExists()Creates a SELECT EXISTS() SQL statement.QueryBuilder
setConditionClasses()Setter for $conditionClasses property.yii\db\QueryBuilder
setExpressionBuilders()Setter for $expressionBuilders property.yii\db\QueryBuilder
truncateTable()Builds a SQL statement for truncating a DB table.yii\db\QueryBuilder
update()Creates an UPDATE SQL statement.QueryBuilder
upsert()Generates a MERGE statement that inserts a row or updates the matching one in a single atomic operation.QueryBuilder
buildAddCommentSql() protectedBuilds the SQL to add or update the MS_Description extended property of a table or column.QueryBuilder
buildRemoveCommentSql() protectedBuilds the SQL to remove the MS_Description extended property from a table or column.QueryBuilder
concatUnionSql() protectedConcatenates the first SELECT statement with the UNION clauses built by buildUnion().yii\db\QueryBuilder
defaultConditionClasses() protectedContains array of default condition classes. Extend this method, if you want to change default condition classes for the query builder. See $conditionClasses docs for details.yii\db\QueryBuilder
defaultExpressionBuilders() protectedContains array of default expression builders. Extend this method and override it, if you want to change default expression builders for this query builder. See $expressionBuilders docs for details.QueryBuilder
extractAlias() protectedExtracts table alias if there is one or returns falseQueryBuilder
hasLimit() protectedChecks to see if the given limit is effective.yii\db\QueryBuilder
hasOffset() protectedChecks to see if the given offset is effective.yii\db\QueryBuilder
prepareInsertSelectSubQuery() protectedPrepare select-subquery and field names for INSERT INTO … SELECT SQL statement.yii\db\QueryBuilder
prepareInsertValues() protectedPrepares a VALUES part for an INSERT SQL statement.yii\db\QueryBuilder
prepareSelectQuery() protectedPerforms driver-specific preparation after Query::prepare().QueryBuilder
prepareUpdateSets() protectedPrepares a SET parts for an UPDATE SQL statement.yii\db\QueryBuilder
prepareUpsertColumns() protectedyii\db\QueryBuilder
prepareUpsertSets() protectedPrepares the SET assignments for the update branch of an upsert statement.yii\db\QueryBuilder
ConstantValueDescriptionDefined by
PARAM_PREFIX':qp'The prefix for automatically generated query binding parameters.yii\db\QueryBuilder
public function addCommentOnColumn(mixed $table, mixed $column, mixed $comment): string

Builds a SQL command for adding comment to column.

Parameters

ParameterTypeDescription
$tablemixedThe table whose column is to be commented. The table name will be properly quoted by the method.
$columnmixedThe name of the column to be commented. The column name will be properly quoted by the method.
$commentmixedThe text of the comment to be added. The comment will be properly quoted by the method.

Returns

string: The SQL statement for adding comment on column

Since

2.0.8

public function addCommentOnTable(mixed $table, mixed $comment): string

Builds a SQL command for adding comment to table.

Parameters

ParameterTypeDescription
$tablemixedThe table whose column is to be commented. The table name will be properly quoted by the method.
$commentmixedThe text of the comment to be added. The comment will be properly quoted by the method.

Returns

string: The SQL statement for adding comment on table

Since

2.0.8

public function addDefaultValue(mixed $name, mixed $table, mixed $column, mixed $value): string

Creates a SQL command for adding a default value constraint to an existing table.

Parameters

ParameterTypeDescription
$namemixedThe name of the default value constraint. The name will be properly quoted by the method.
$tablemixedThe table that the default value constraint will be added to. The name will be properly quoted by the method.
$columnmixedThe name of the column to that the constraint will be added on. The name will be properly quoted by the method.
$valuemixedDefault value.

Returns

string: The SQL statement for adding a default value constraint to an existing table.

Throws

Since

2.0.13

public function alterColumn(string $table, string $column, string $type): string

Builds a SQL statement for changing the definition of a column.

Drops the default, check, and unique constraints attached to the column before the ALTER COLUMN statement, because SQL Server rejects altering a column while such constraints are bound to it. Default, check, and unique constraints defined by a ColumnSchemaBuilder type are re-created after the column is altered.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be changed. The table name will be properly quoted by the method.
$columnstringThe name of the column to be changed. The name will be properly quoted by the method.
$typestringThe new column type. The getColumnType() method will be invoked to convert abstract column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL. For example, ‘string’ will be turned into ‘varchar(255)’, while ‘string not null’ will become ‘varchar(255) not null’.

Returns

string: The SQL statement for changing the definition of a column.

Throws

public function buildOrderByAndLimit(mixed $sql, mixed $orderBy, mixed $limit, mixed $offset): string

Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.

Parameters

ParameterTypeDescription
$sqlmixedThe existing SQL (without ORDER BY/LIMIT/OFFSET)
$orderBymixedThe order by columns. See Query::orderBy() for more details on how to specify this parameter.
$limitmixedThe limit number. See Query::limit() for more details.
$offsetmixedThe offset number. See Query::offset() for more details.

Returns

string: The SQL completed with ORDER BY/LIMIT/OFFSET (if any)

public function buildUnionOrderByAndLimit(string $sql, array|null $orderBy, int|yii\db\ExpressionInterface|null $limit, int|yii\db\ExpressionInterface|null $offset): string

Builds the global ORDER BY and LIMIT/OFFSET clauses for a UNION query.

Parameters

ParameterTypeDescription
$sqlstringThe complete UNION SQL without global ORDER BY/LIMIT/OFFSET clauses.
$orderByarray|nullThe global order by columns.
$limitint|yii\db\ExpressionInterface|nullThe global limit.
$offsetint|yii\db\ExpressionInterface|nullThe global offset.

Returns

string: The completed UNION SQL.

Since

22.0

public function buildWithQueries(mixed $withs, mixed &$params): string

SQL Server does not support the RECURSIVE keyword for CTEs. Recursion is implicit when a CTE references itself.

Parameters

ParameterTypeDescription
$withsmixedOf configurations for each WITH query
$paramsmixedThe binding parameters to be populated

Returns

string: Compiled WITH prefix of query including nested queries

Since

2.0.35

public function checkIntegrity(bool $check = true, string $schema = '', string $table = ''): string

Builds a SQL statement for enabling or disabling integrity checks on table constraints.

Resolves the table and schema names without loading metadata, so the statement is built without opening a database connection. A single table yields a direct ALTER TABLE statement; an empty table targets every base table in the schema, enumerated server-side from sys.tables (views excluded) and run in one batch.

Enabling uses WITH CHECK CHECK CONSTRAINT ALL, re-validating existing rows and marking the constraints trusted; disabling uses NOCHECK CONSTRAINT ALL.

Parameters

ParameterTypeDescription
$checkboolWhether to enable (true) or disable (false) the integrity checks.
$schemastringThe schema of the tables. Defaults to an empty string, meaning the default schema.
$tablestringThe table name. Defaults to an empty string, meaning every table in the schema.

Returns

string: The SQL statement for enabling or disabling the integrity checks.

See also

public function delete(mixed $table, mixed $condition, mixed &$params): string

Creates a DELETE SQL statement.

Renders any rowversion in the WHERE condition as a binary literal, enabling optimistic-lock deletes.

For example,

$sql = $queryBuilder->delete('user', 'status = 0');

The method will properly escape the table and column names.

Parameters

ParameterTypeDescription
$tablemixedThe table where the data will be deleted from.
$conditionmixedThe condition that will be put in the WHERE part. Please refer to Query::where() on how to specify condition.
$paramsmixedThe binding parameters that will be modified by this method so that they can be bound to the DB command later.

Returns

string: The DELETE SQL

See also

public function dropColumn(mixed $table, mixed $column): mixed

Drop all constraints before column delete.

Parameters

ParameterTypeDescription
$tablemixed
$columnmixed

Returns

mixed

public function dropCommentFromColumn(mixed $table, mixed $column): string

Builds a SQL command for adding comment to column.

Parameters

ParameterTypeDescription
$tablemixedThe table whose column is to be commented. The table name will be properly quoted by the method.
$columnmixedThe name of the column to be commented. The column name will be properly quoted by the method.

Returns

string: The SQL statement for adding comment on column

Since

2.0.8

public function dropCommentFromTable(mixed $table): string

Builds a SQL command for adding comment to table.

Parameters

ParameterTypeDescription
$tablemixedThe table whose column is to be commented. The table name will be properly quoted by the method.

Returns

string: The SQL statement for adding comment on column

Since

2.0.8

public function dropDefaultValue(mixed $name, mixed $table): string

Creates a SQL command for dropping a default value constraint.

Parameters

ParameterTypeDescription
$namemixedThe name of the default value constraint to be dropped. The name will be properly quoted by the method.
$tablemixedThe table whose default value constraint is to be dropped. The name will be properly quoted by the method.

Returns

string: The SQL statement for dropping a default value constraint.

Throws

Since

2.0.13

See also

public function getColumnType(mixed $type): string

Converts an abstract column type into a physical column type.

The conversion is done using the type map specified in $typeMap. The following abstract column types are supported (using MySQL as an example to explain the corresponding physical types):

  • pk: an auto-incremental primary key type, will be converted into “int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY”
  • bigpk: an auto-incremental primary key type, will be converted into “bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY”
  • upk: an unsigned auto-incremental primary key type, will be converted into “int(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY”
  • char: char type, will be converted into “char(1)”
  • string: string type, will be converted into “varchar(255)”
  • text: a long string type, will be converted into “text”
  • smallint: a small integer type, will be converted into “smallint(6)”
  • integer: integer type, will be converted into “int(11)”
  • bigint: a big integer type, will be converted into “bigint(20)”
  • boolean: boolean type, will be converted into “tinyint(1)”
  • `float“: float number type, will be converted into “float”
  • decimal: decimal number type, will be converted into “decimal”
  • datetime: datetime type, will be converted into “datetime”
  • timestamp: timestamp type, will be converted into “timestamp”
  • time: time type, will be converted into “time”
  • date: date type, will be converted into “date”
  • money: money type, will be converted into “decimal(19,4)”
  • binary: binary data type, will be converted into “blob”

If the abstract type contains two or more parts separated by spaces (e.g. “string NOT NULL”), then only the first part will be converted, and the rest of the parts will be appended to the converted result. For example, ‘string NOT NULL’ is converted to ‘varchar(255) NOT NULL’.

For some of the abstract types you can also specify a length or precision constraint by appending it in round brackets directly to the type. For example string(32) will be converted into “varchar(32)” on a MySQL database. If the underlying DBMS does not support these kind of constraints for a type it will be ignored.

If a type cannot be found in $typeMap, it will be returned without any change.

Parameters

ParameterTypeDescription
$typemixedAbstract column type

Returns

string: Physical column type.

public function insert(mixed $table, mixed $columns, mixed &$params): string

Creates an INSERT SQL statement.

Wraps the INSERT with an OUTPUT INSERTED.* INTO @temporary_inserted block so that the inserted row (including computed columns and IDENTITY values) can be retrieved by the caller.

For example,

$sql = $queryBuilder->insert('user', [
'name' => 'Sam',
'age' => 30,
], $params);

The method will properly escape the table and column names.

Parameters

ParameterTypeDescription
$tablemixedThe table that new rows will be inserted into.
$columnsmixedThe column data (name => value) to be inserted into the table or instance of Query to perform INSERT INTO … SELECT SQL statement. Passing of Query is available since version 2.0.11.
$paramsmixedThe binding parameters that will be generated by this method. They should be bound to the DB command later.

Returns

string: The INSERT SQL

public function renameColumn(string $table, string $oldName, string $newName): string

Builds a SQL statement for renaming a column.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be renamed. The name will be properly quoted by the method.
$oldNamestringThe old name of the column. The name will be properly quoted by the method.
$newNamestringThe new name of the column. The name will be properly quoted by the method.

Returns

string: The SQL statement for renaming a DB column.

public function renameTable(string $oldName, string $newName): string

Builds a SQL statement for renaming a DB table.

Parameters

ParameterTypeDescription
$oldNamestringThe table to be renamed. The name will be properly quoted by the method.
$newNamestringThe new table name. The name will be properly quoted by the method.

Returns

string: The SQL statement for renaming a DB table.

public function resetSequence(string $tableName, int|null $value = null): string

Creates a SQL statement for resetting the sequence value of a table’s primary key.

The sequence will be reset such that the primary key of the next new row inserted will have the specified value or the next value after the current maximum identity value.

Parameters

ParameterTypeDescription
$tableNamestringThe name of the table whose primary key sequence will be reset.
$valueint|nullThe integer value for the primary key of the next new row inserted. If this is not set, the next new row’s primary key will have the next value after the current maximum identity value.

Returns

string: The SQL statement for resetting sequence.

Throws

See also

public function selectExists(mixed $rawSql): string

Creates a SELECT EXISTS() SQL statement.

Parameters

ParameterTypeDescription
$rawSqlmixedThe subquery in a raw form to select from.

Returns

string: The SELECT EXISTS() SQL statement.

Since

2.0.8

public function update(mixed $table, mixed $columns, mixed $condition, mixed &$params): string

Creates an UPDATE SQL statement.

Excludes server-managed rowversion columns from the SET clause and renders any rowversion in the WHERE as a binary literal, enabling a rowversion column to serve as the optimistic lock attribute.

Note: SQL Server regenerates the rowversion on every write and the in-memory attribute is not refreshed afterwards; reload the record before saving the same instance again to avoid a spurious StaleObjectException.

For example,

$params = [];
$sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);

The method will properly escape the table and column names.

Parameters

ParameterTypeDescription
$tablemixedThe table to be updated.
$columnsmixedThe column data (name => value) to be updated.
$conditionmixedThe condition that will be put in the WHERE part. Please refer to Query::where() on how to specify condition.
$paramsmixedThe binding parameters that will be modified by this method so that they can be bound to the DB command later.

Returns

string: The UPDATE SQL

See also

public function upsert(mixed $table, mixed $insertColumns, mixed $updateColumns, mixed &$params): mixed

Generates a MERGE statement that inserts a row or updates the matching one in a single atomic operation.

The WITH (HOLDLOCK) table hint serializes concurrent upserts so they cannot insert duplicate keys.

Parameters

ParameterTypeDescription
$tablemixed
$insertColumnsmixed
$updateColumnsmixed
$paramsmixed

Returns

mixed

See also

protected function buildAddCommentSql(string $comment, string $table, string|null $column = null): string

Builds the SQL to add or update the MS_Description extended property of a table or column.

Resolves the table name without loading metadata, so the statement is assembled without opening a database connection. The comment is added when the property is absent and updated otherwise, and the extended-property routines are qualified with the catalog when the name includes one.

Parameters

ParameterTypeDescription
$commentstringComment text. Escaped and wrapped as an N'...' literal by the method.
$tablestringTarget table. May be ‘catalog-’, ‘schema-’, or bracket-qualified.
$columnstring|nullTarget column, or null to comment the table itself.

Returns

string: SQL statement that adds or updates the comment.

Since

2.0.24

protected function buildRemoveCommentSql(string $table, string|null $column = null): string

Builds the SQL to remove the MS_Description extended property from a table or column.

Resolves the table name without loading metadata, so the statement is assembled without opening a database connection. The property is dropped only when present, and the extended-property routines are qualified with the catalog when the name includes one.

Parameters

ParameterTypeDescription
$tablestringTarget table. May be ‘catalog-’, ‘schema-’, or bracket-qualified.
$columnstring|nullTarget column, or null to remove the table comment.

Returns

string: SQL statement that removes the comment.

Since

2.0.24

protected function defaultExpressionBuilders(): array

Contains array of default expression builders. Extend this method and override it, if you want to change default expression builders for this query builder. See $expressionBuilders docs for details.

Returns

array

Since

2.0.14

protected function extractAlias(mixed $table): bool|array

Extracts table alias if there is one or returns false

Parameters

ParameterTypeDescription
$tablemixed

Returns

bool|array

Since

2.0.24

protected function prepareSelectQuery(yii\db\Query $query): yii\db\Query

Performs driver-specific preparation after Query::prepare().

SQL Server rejects FETCH NEXT 0 and wrapping a compound query requires every result column to have a unique name. Applying TOP (0) to every UNION operand preserves zero-row semantics without a derived table.

Implementations must not modify the given query; they must return a modified clone instead.

Parameters

ParameterTypeDescription
$queryyii\db\QueryThe prepared query.

Returns

yii\db\Query: The query to build.

Since

22.0