Insert, Updates, Deletes
INSERT, UPDATE and DELETE statements build on a hierarchy startingwith UpdateBase
. The Insert
and Update
constructs build on the intermediary ValuesBase
.
sqlalchemy.sql.expression.
delete
(table, whereclause=None, bind=None, returning=None, prefixes=None, **dialect_kw)- Construct
Delete
object.
Similar functionality is available via thedelete()
method onTable
.
- Parameters
-
- A
ClauseElement
describing theWHERE
- condition of the
DELETE
statement. Note that thewhere()
generative method may be used instead.
- A
The WHERE clause can refer to multiple tables.For databases which support this, a DELETE..USING
or similarclause will be generated. The statementwill fail on databases that don’t have support for multi-tabledelete statements. A SQL-standard method of referring toadditional tables in the WHERE clause is to use a correlatedsubquery:
- users.delete().where(
- users.c.name==select([addresses.c.email_address]). where(addresses.c.user_id==users.c.id). as_scalar()
- )
Changed in version 1.2.0: The WHERE clause of DELETE can refer to multiple tables.
See also
Deletes - SQL Expression Tutorial
sqlalchemy.sql.expression.
insert
(table, values=None, inline=False, bind=None, prefixes=None, returning=None, return_defaults=False, **dialect_kw)- Construct an
Insert
object.
Similar functionality is available via theinsert()
method onTable
.
- Parameters
table –
TableClause
which is the subject of theinsert.values – collection of values to be inserted; see
Insert.values()
for a description of allowed formats here.Can be omitted entirely; aInsert
construct will alsodynamically render the VALUES clause at execution time based onthe parameters passed toConnection.execute()
.inline – if True, no attempt will be made to retrieve theSQL-generated default values to be provided within the statement;in particular,this allows SQL expressions to be rendered ‘inline’ within thestatement without the need to pre-execute them beforehand; forbackends that support “returning”, this turns off the “implicitreturning” feature for the statement.
If both values and compile-time bind parameters are present, thecompile-time bind parameters override the information specifiedwithin values on a per-key basis.
The keys within values can be eitherColumn
objects or their stringidentifiers. Each key may reference one of:
a literal data value (i.e. string, number, etc.);
a Column object;
a SELECT statement.
If a SELECT
statement is specified which references thisINSERT
statement’s table, the statement will be correlatedagainst the INSERT
statement.
See also
Insert Expressions - SQL Expression Tutorial
Inserts, Updates and Deletes - SQL Expression Tutorial
sqlalchemy.sql.expression.
update
(table, whereclause=None, values=None, inline=False, bind=None, prefixes=None, returning=None, return_defaults=False, preserve_parameter_order=False, **dialect_kw)- Construct an
Update
object.
E.g.:
- from sqlalchemy import update
- stmt = update(users).where(users.c.id==5).\
- values(name='user #5')
Similar functionality is available via theupdate()
method onTable
:
- stmt = users.update().\
- where(users.c.id==5).\
- values(name='user #5')
- Parameters
table – A
Table
object representing the databasetable to be updated.
Optional SQL expression describing the WHERE
condition of the UPDATE
statement. Modern applicationsmay prefer to use the generative where()
method to specify the WHERE
clause.
The WHERE clause can refer to multiple tables.For databases which support this, an UPDATE FROM
clause willbe generated, or on MySQL, a multi-table update. The statementwill fail on databases that don’t have support for multi-tableupdate statements. A SQL-standard method of referring toadditional tables in the WHERE clause is to use a correlatedsubquery:
- users.update().values(name='ed').where(
- users.c.name==select([addresses.c.email_address]).\
- where(addresses.c.user_id==users.c.id).\
- as_scalar()
- )
-
Optional dictionary which specifies the SET
conditions of theUPDATE
. If left as None
, the SET
conditions are determined from those parameters passed to thestatement during the execution and/or compilation of thestatement. When compiled standalone without any parameters,the SET
clause generates for all columns.
Modern applications may prefer to use the generativeUpdate.values()
method to set the values of theUPDATE statement.
-
inline – if True, SQL defaults present on Column
objects viathe default
keyword will be compiled ‘inline’ into the statementand not pre-executed. This means that their values will notbe available in the dictionary returned fromResultProxy.last_updated_params()
.
-
if True, the update statement isexpected to receive parameters only via theUpdate.values()
method, and they must be passed as a Pythonlist
of 2-tuples. The rendered UPDATE statement will emit the SETclause for each referenced column maintaining this order.
New in version 1.0.10.
See also
Parameter-Ordered Updates - full example of thepreserve_parameter_order
flag
If both values
and compile-time bind parameters are present, thecompile-time bind parameters override the information specifiedwithin values
on a per-key basis.
The keys within values
can be either Column
objects or their string identifiers (specifically the “key” of theColumn
, normally but not necessarily equivalent toits “name”). Normally, theColumn
objects used here are expected to bepart of the target Table
that is the tableto be updated. However when using MySQL, a multiple-tableUPDATE statement can refer to columns from any ofthe tables referred to in the WHERE clause.
The values referred to in values
are typically:
a literal data value (i.e. string, number, etc.)
a SQL expression, such as a related
Column
,a scalar-returningselect()
construct,etc.
When combining select()
constructs within the valuesclause of an update()
construct,the subquery represented by the select()
should becorrelated to the parent table, that is, providing criterionwhich links the table inside the subquery to the outer tablebeing updated:
- users.update().values(
- name=select([addresses.c.email_address]).\
- where(addresses.c.user_id==users.c.id).\
- as_scalar()
- )
See also
Inserts, Updates and Deletes - SQL ExpressionLanguage Tutorial
- class
sqlalchemy.sql.expression.
Delete
(table, whereclause=None, bind=None, returning=None, prefixes=None, **dialect_kw) - Bases:
sqlalchemy.sql.expression.UpdateBase
Represent a DELETE construct.
The Delete
object is created using the delete()
function.
inherited from the eq()
method of object
Return self==value.
init
(table, whereclause=None, bind=None, returning=None, prefixes=None, **dialect_kw)- Construct a new
Delete
object.
This constructor is mirrored as a public API function; see delete()
for a full usage and argument description.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- class
sqlalchemy.sql.expression.
Insert
(table, values=None, inline=False, bind=None, prefixes=None, returning=None, return_defaults=False, **dialect_kw) - Bases:
sqlalchemy.sql.expression.ValuesBase
Represent an INSERT construct.
The Insert
object is created using theinsert()
function.
See also
inherited from the eq()
method of object
Return self==value.
init
(table, values=None, inline=False, bind=None, prefixes=None, returning=None, return_defaults=False, **dialect_kw)- Construct a new
Insert
object.
This constructor is mirrored as a public API function; see insert()
for a full usage and argument description.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- class
sqlalchemy.sql.expression.
Update
(table, whereclause=None, values=None, inline=False, bind=None, prefixes=None, returning=None, return_defaults=False, preserve_parameter_order=False, **dialect_kw) - Bases:
sqlalchemy.sql.expression.ValuesBase
Represent an Update construct.
The Update
object is created using the update()
function.
inherited from the eq()
method of object
Return self==value.
init
(table, whereclause=None, values=None, inline=False, bind=None, prefixes=None, returning=None, return_defaults=False, preserve_parameter_order=False, **dialect_kw)- Construct a new
Update
object.
This constructor is mirrored as a public API function; see update()
for a full usage and argument description.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- class
sqlalchemy.sql.expression.
UpdateBase
- Bases:
sqlalchemy.sql.expression.HasCTE
,sqlalchemy.sql.base.DialectKWArgs
,sqlalchemy.sql.expression.HasPrefixes
,sqlalchemy.sql.expression.Executable
,sqlalchemy.sql.expression.ClauseElement
Form the base for INSERT
, UPDATE
, and DELETE
statements.
inherited from the eq()
method of object
Return self==value.
inherited from the init()
method of object
Initialize self. See help(type(self)) for accurate signature.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- class
sqlalchemy.sql.expression.
ValuesBase
(table, values, prefixes) - Bases:
sqlalchemy.sql.expression.UpdateBase
Supplies support for ValuesBase.values()
toINSERT and UPDATE constructs.
returndefaults
(*cols_)- Make use of a RETURNING clause for the purposeof fetching server-side expressions and defaults.
E.g.:
- stmt = table.insert().values(data='newdata').return_defaults()
- result = connection.execute(stmt)
- server_created_at = result.returned_defaults['created_at']
When used against a backend that supports RETURNING, all columnvalues generated by SQL expression or server-side-default will beadded to any existing RETURNING clause, provided thatUpdateBase.returning()
is not used simultaneously. The columnvalues will then be available on the result using theResultProxy.returned_defaults
accessor as a dictionary,referring to values keyed to the Column
object as well asits .key
.
This method differs from UpdateBase.returning()
in these ways:
-
ValuesBase.return_defaults()
is only intended for use withan INSERT or an UPDATE statement that matches exactly one row.While the RETURNING construct in the general sense supportsmultiple rows for a multi-row UPDATE or DELETE statement, or forspecial cases of INSERT that return multiple rows (e.g. INSERT fromSELECT, multi-valued VALUES clause),ValuesBase.return_defaults()
is intended only for an“ORM-style” single-row INSERT/UPDATE statement. The row returnedby the statement is also consumed implicitly whenValuesBase.return_defaults()
is used. By contrast,UpdateBase.returning()
leaves the RETURNING result-setintact with a collection of any number of rows.
-
It is compatible with the existing logic to fetch auto-generatedprimary key values, also known as “implicit returning”. Backendsthat support RETURNING will automatically make use of RETURNING inorder to fetch the value of newly generated primary keys; while theUpdateBase.returning()
method circumvents this behavior,ValuesBase.return_defaults()
leaves it intact.
-
It can be called against any backend. Backends that don’t supportRETURNING will skip the usage of the feature, rather than raisingan exception. The return value ofResultProxy.returned_defaults
will be None
ValuesBase.return_defaults()
is used by the ORM to providean efficient implementation for the eager_defaults
feature ofmapper()
.
- Parameters
-
cols – optional list of column key names or Column
objects. If omitted, all column expressions evaluated on the serverare added to the returning list.
New in version 0.9.0.
See also
ResultProxy.returned_defaults
values
(*args, **kwargs)- specify a fixed VALUES clause for an INSERT statement, or the SETclause for an UPDATE.
Note that the Insert
and Update
constructs supportper-execution time formatting of the VALUES and/or SET clauses,based on the arguments passed to Connection.execute()
.However, the ValuesBase.values()
method can be used to “fix” aparticular set of parameters into the statement.
Multiple calls to ValuesBase.values()
will produce a newconstruct, each one with the parameter list modified to includethe new parameters sent. In the typical case of a singledictionary of parameters, the newly passed keys will replacethe same keys in the previous construct. In the case of a list-based“multiple values” construct, each new list of values is extendedonto the existing list of values.
- Parameters
-
-
key value pairs representing the string keyof a Column
mapped to the value to be rendered into theVALUES or SET clause:
- users.insert().values(name="some name")
- users.update().where(users.c.id==5).values(name="some name")
-
As an alternative to passing key/value parameters,a dictionary, tuple, or list of dictionaries or tuples can be passedas a single positional argument in order to form the VALUES orSET clause of the statement. The forms that are accepted varybased on whether this is an Insert
or an Update
construct.
For either an Insert
or Update
construct, asingle dictionary can be passed, which works the same as that ofthe kwargs form:
- users.insert().values({"name": "some name"})
- users.update().values({"name": "some new name"})
Also for either form but more typically for the Insert
construct, a tuple that contains an entry for every column in thetable is also accepted:
- users.insert().values((5, "some name"))
The Insert
construct also supports being passed a listof dictionaries or full-table-tuples, which on the server willrender the less common SQL syntax of “multiple values” - thissyntax is supported on backends such as SQLite, PostgreSQL, MySQL,but not necessarily others:
- users.insert().values([
- {"name": "some name"},
- {"name": "some other name"},
- {"name": "yet another name"},
- ])
The above form would render a multiple VALUES statement similar to:
- INSERT INTO users (name) VALUES
- (:name_1),
- (:name_2),
- (:name_3)
It is essential to note that passing multiple values isNOT the same as using traditional executemany() form. The abovesyntax is a special syntax not typically used. To emit anINSERT statement against multiple rows, the normal method isto pass a multiple values list to the Connection.execute()
method, which is supported by all database backends and is generallymore efficient for a very large number of parameters.
See also
Executing Multiple Statements - an introduction tothe traditional Core method of multiple parameter setinvocation for INSERTs and other statements.
Changed in version 1.0.0: an INSERT that uses a multiple-VALUESclause, even a list of length one,implies that the
Insert.inline
flag is set toTrue, indicating that the statement will not attempt to fetchthe “last inserted primary key” or other defaults. Thestatement deals with an arbitrary number of rows, so theResultProxy.inserted_primary_key
accessor does notapply.Changed in version 1.0.0: A multiple-VALUES INSERT now supportscolumns with Python side default values and callables in thesame way as that of an “executemany” style of invocation; thecallable is invoked for each row. See Python-side defaults invoked for each row individually when using a multivalued insertfor other details.
The Update
construct supports a special form which is alist of 2-tuples, which when provided must be passed in conjunctionwith thepreserve_parameter_order
parameter.This form causes the UPDATE statement to render the SET clausesusing the order of parameters given to Update.values()
, ratherthan the ordering of columns given in the Table
.
New in version 1.0.10: - added support for parameter-orderedUPDATE statements via the
preserve_parameter_order
flag.See also
Parameter-Ordered Updates - full example of the
preserve_parameter_order
flag
See also
Inserts, Updates and Deletes - SQL ExpressionLanguage Tutorial
insert()
- produce an INSERT
statement
update()
- produce an UPDATE
statement