Insert, Updates, Deletes

INSERT, UPDATE and DELETE statements build on a hierarchy starting with UpdateBase. The Insert and Update constructs build on the intermediary ValuesBase.

DML Foundational Constructors

Top level “INSERT”, “UPDATE”, “DELETE” constructors.

Object NameDescription

delete(table)

Construct Delete object.

insert(table)

Construct an Insert object.

update(table)

Construct an Update object.

function sqlalchemy.sql.expression.delete(table: _DMLTableArgument) → Delete

Construct Delete object.

E.g.:

  1. from sqlalchemy import delete
  2. stmt = (
  3. delete(user_table).
  4. where(user_table.c.id == 5)
  5. )

Similar functionality is available via the TableClause.delete() method on Table.

  • Parameters:

    table – The table to delete rows from.

See also

Using UPDATE and DELETE Statements - in the SQLAlchemy Unified Tutorial

function sqlalchemy.sql.expression.insert(table: _DMLTableArgument) → Insert

Construct an Insert object.

E.g.:

  1. from sqlalchemy import insert
  2. stmt = (
  3. insert(user_table).
  4. values(name='username', fullname='Full Username')
  5. )

Similar functionality is available via the TableClause.insert() method on Table.

See also

Using INSERT Statements - in the SQLAlchemy Unified Tutorial

  • Parameters:

    • tableTableClause which is the subject of the insert.

    • values – collection of values to be inserted; see Insert.values() for a description of allowed formats here. Can be omitted entirely; a Insert construct will also dynamically render the VALUES clause at execution time based on the parameters passed to Connection.execute().

    • inline – if True, no attempt will be made to retrieve the SQL-generated default values to be provided within the statement; in particular, this allows SQL expressions to be rendered ‘inline’ within the statement without the need to pre-execute them beforehand; for backends that support “returning”, this turns off the “implicit returning” feature for the statement.

If both insert.values and compile-time bind parameters are present, the compile-time bind parameters override the information specified within insert.values on a per-key basis.

The keys within Insert.values can be either Column objects or their string identifiers. 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 this INSERT statement’s table, the statement will be correlated against the INSERT statement.

See also

Using INSERT Statements - in the SQLAlchemy Unified Tutorial

function sqlalchemy.sql.expression.update(table: _DMLTableArgument) → Update

Construct an Update object.

E.g.:

  1. from sqlalchemy import update
  2. stmt = (
  3. update(user_table).
  4. where(user_table.c.id == 5).
  5. values(name='user #5')
  6. )

Similar functionality is available via the TableClause.update() method on Table.

  • Parameters:

    table – A Table object representing the database table to be updated.

See also

Using UPDATE and DELETE Statements - in the SQLAlchemy Unified Tutorial

DML Class Documentation Constructors

Class documentation for the constructors listed at DML Foundational Constructors.

Object NameDescription

Delete

Represent a DELETE construct.

Insert

Represent an INSERT construct.

Update

Represent an Update construct.

UpdateBase

Form the base for INSERT, UPDATE, and DELETE statements.

ValuesBase

Supplies support for ValuesBase.values() to INSERT and UPDATE constructs.

class sqlalchemy.sql.expression.Delete

Represent a DELETE construct.

The Delete object is created using the delete() function.

Members

where(), returning()

Class signature

class sqlalchemy.sql.expression.Delete (sqlalchemy.sql.expression.DMLWhereBase, sqlalchemy.sql.expression.UpdateBase)

  • method sqlalchemy.sql.expression.Delete.where(*whereclause: _ColumnExpressionArgument[bool]) → SelfDMLWhereBase

    inherited from the DMLWhereBase.where() method of DMLWhereBase

    Return a new construct with the given expression(s) added to its WHERE clause, joined to the existing clause via AND, if any.

    Both Update.where() and Delete.where() support multiple-table forms, including database-specific UPDATE...FROM as well as DELETE..USING. For backends that don’t have multiple-table support, a backend agnostic approach to using multiple tables is to make use of correlated subqueries. See the linked tutorial sections below for examples.

    See also

    Correlated Updates

    UPDATE..FROM

    Multiple Table Deletes

  • method sqlalchemy.sql.expression.Delete.returning(*cols: _ColumnsClauseArgument[Any], **_UpdateBase\_kw: Any_) → UpdateBase

    inherited from the UpdateBase.returning() method of UpdateBase

    Add a RETURNING or equivalent clause to this statement.

    e.g.:

    1. >>> stmt = (
    2. ... table.update()
    3. ... .where(table.c.data == "value")
    4. ... .values(status="X")
    5. ... .returning(table.c.server_flag, table.c.updated_timestamp)
    6. ... )
    7. >>> print(stmt)
    8. UPDATE some_table SET status=:status
    9. WHERE some_table.data = :data_1
    10. RETURNING some_table.server_flag, some_table.updated_timestamp

    The method may be invoked multiple times to add new entries to the list of expressions to be returned.

    New in version 1.4.0b2: The method may be invoked multiple times to add new entries to the list of expressions to be returned.

    The given collection of column expressions should be derived from the table that is the target of the INSERT, UPDATE, or DELETE. While Column objects are typical, the elements can also be expressions:

    1. >>> stmt = table.insert().returning(
    2. ... (table.c.first_name + " " + table.c.last_name).label("fullname")
    3. ... )
    4. >>> print(stmt)
    5. INSERT INTO some_table (first_name, last_name)
    6. VALUES (:first_name, :last_name)
    7. RETURNING some_table.first_name || :first_name_1 || some_table.last_name AS fullname

    Upon compilation, a RETURNING clause, or database equivalent, will be rendered within the statement. For INSERT and UPDATE, the values are the newly inserted/updated values. For DELETE, the values are those of the rows which were deleted.

    Upon execution, the values of the columns to be returned are made available via the result set and can be iterated using CursorResult.fetchone() and similar. For DBAPIs which do not natively support returning values (i.e. cx_oracle), SQLAlchemy will approximate this behavior at the result level so that a reasonable amount of behavioral neutrality is provided.

    Note that not all databases/DBAPIs support RETURNING. For those backends with no support, an exception is raised upon compilation and/or execution. For those who do support it, the functionality across backends varies greatly, including restrictions on executemany() and other statements which return multiple rows. Please read the documentation notes for the database in use in order to determine the availability of RETURNING.

    See also

    UpdateBase.return_defaults() - an alternative method tailored towards efficient fetching of server-side defaults and triggers for single-row INSERTs or UPDATEs.

    INSERT…RETURNING - in the SQLAlchemy Unified Tutorial

class sqlalchemy.sql.expression.Insert

Represent an INSERT construct.

The Insert object is created using the insert() function.

Members

values(), returning(), from_select(), inline(), select

Class signature

class sqlalchemy.sql.expression.Insert (sqlalchemy.sql.expression.ValuesBase)

  • method sqlalchemy.sql.expression.Insert.values(*args: Union[Dict[_DMLColumnArgument, Any], Sequence[Any]], **kwargs: Any) → SelfValuesBase

    inherited from the ValuesBase.values() method of ValuesBase

    Specify a fixed VALUES clause for an INSERT statement, or the SET clause for an UPDATE.

    Note that the Insert and Update constructs support per-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” a particular set of parameters into the statement.

    Multiple calls to ValuesBase.values() will produce a new construct, each one with the parameter list modified to include the new parameters sent. In the typical case of a single dictionary of parameters, the newly passed keys will replace the same keys in the previous construct. In the case of a list-based “multiple values” construct, each new list of values is extended onto the existing list of values.

    • Parameters:

      • **kwargs

        key value pairs representing the string key of a Column mapped to the value to be rendered into the VALUES or SET clause:

        1. users.insert().values(name="some name")
        2. users.update().where(users.c.id==5).values(name="some name")
      • *args

        As an alternative to passing key/value parameters, a dictionary, tuple, or list of dictionaries or tuples can be passed as a single positional argument in order to form the VALUES or SET clause of the statement. The forms that are accepted vary based on whether this is an Insert or an Update construct.

        For either an Insert or Update construct, a single dictionary can be passed, which works the same as that of the kwargs form:

        1. users.insert().values({"name": "some name"})
        2. 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 the table is also accepted:

        1. users.insert().values((5, "some name"))

        The Insert construct also supports being passed a list of dictionaries or full-table-tuples, which on the server will render the less common SQL syntax of “multiple values” - this syntax is supported on backends such as SQLite, PostgreSQL, MySQL, but not necessarily others:

        1. users.insert().values([
        2. {"name": "some name"},
        3. {"name": "some other name"},
        4. {"name": "yet another name"},
        5. ])

        The above form would render a multiple VALUES statement similar to:

        1. INSERT INTO users (name) VALUES
        2. (:name_1),
        3. (:name_2),
        4. (:name_3)

        It is essential to note that passing multiple values is NOT the same as using traditional executemany() form. The above syntax is a special syntax not typically used. To emit an INSERT statement against multiple rows, the normal method is to pass a multiple values list to the Connection.execute() method, which is supported by all database backends and is generally more efficient for a very large number of parameters.

        See also

        Sending Multiple Parameters - an introduction to the traditional Core method of multiple parameter set invocation for INSERTs and other statements.

        Changed in version 1.0.0: an INSERT that uses a multiple-VALUES clause, even a list of length one, implies that the Insert.inline flag is set to True, indicating that the statement will not attempt to fetch the “last inserted primary key” or other defaults. The statement deals with an arbitrary number of rows, so the CursorResult.inserted_primary_key accessor does not apply.

        Changed in version 1.0.0: A multiple-VALUES INSERT now supports columns with Python side default values and callables in the same way as that of an “executemany” style of invocation; the callable is invoked for each row. See Python-side defaults invoked for each row individually when using a multivalued insert for other details.

        The UPDATE construct also supports rendering the SET parameters in a specific order. For this feature refer to the Update.ordered_values() method.

        See also

        Update.ordered_values()

  • method sqlalchemy.sql.expression.Insert.returning(*cols: _ColumnsClauseArgument[Any], **_UpdateBase\_kw: Any_) → UpdateBase

    inherited from the UpdateBase.returning() method of UpdateBase

    Add a RETURNING or equivalent clause to this statement.

    e.g.:

    1. >>> stmt = (
    2. ... table.update()
    3. ... .where(table.c.data == "value")
    4. ... .values(status="X")
    5. ... .returning(table.c.server_flag, table.c.updated_timestamp)
    6. ... )
    7. >>> print(stmt)
    8. UPDATE some_table SET status=:status
    9. WHERE some_table.data = :data_1
    10. RETURNING some_table.server_flag, some_table.updated_timestamp

    The method may be invoked multiple times to add new entries to the list of expressions to be returned.

    New in version 1.4.0b2: The method may be invoked multiple times to add new entries to the list of expressions to be returned.

    The given collection of column expressions should be derived from the table that is the target of the INSERT, UPDATE, or DELETE. While Column objects are typical, the elements can also be expressions:

    1. >>> stmt = table.insert().returning(
    2. ... (table.c.first_name + " " + table.c.last_name).label("fullname")
    3. ... )
    4. >>> print(stmt)
    5. INSERT INTO some_table (first_name, last_name)
    6. VALUES (:first_name, :last_name)
    7. RETURNING some_table.first_name || :first_name_1 || some_table.last_name AS fullname

    Upon compilation, a RETURNING clause, or database equivalent, will be rendered within the statement. For INSERT and UPDATE, the values are the newly inserted/updated values. For DELETE, the values are those of the rows which were deleted.

    Upon execution, the values of the columns to be returned are made available via the result set and can be iterated using CursorResult.fetchone() and similar. For DBAPIs which do not natively support returning values (i.e. cx_oracle), SQLAlchemy will approximate this behavior at the result level so that a reasonable amount of behavioral neutrality is provided.

    Note that not all databases/DBAPIs support RETURNING. For those backends with no support, an exception is raised upon compilation and/or execution. For those who do support it, the functionality across backends varies greatly, including restrictions on executemany() and other statements which return multiple rows. Please read the documentation notes for the database in use in order to determine the availability of RETURNING.

    See also

    UpdateBase.return_defaults() - an alternative method tailored towards efficient fetching of server-side defaults and triggers for single-row INSERTs or UPDATEs.

    INSERT…RETURNING - in the SQLAlchemy Unified Tutorial

  • method sqlalchemy.sql.expression.Insert.from_select(names: List[str], select: Selectable, include_defaults: bool = True) → SelfInsert

    Return a new Insert construct which represents an INSERT...FROM SELECT statement.

    e.g.:

    1. sel = select(table1.c.a, table1.c.b).where(table1.c.c > 5)
    2. ins = table2.insert().from_select(['a', 'b'], sel)
    • Parameters:

      • names – a sequence of string column names or Column objects representing the target columns.

      • select – a select() construct, FromClause or other construct which resolves into a FromClause, such as an ORM Query object, etc. The order of columns returned from this FROM clause should correspond to the order of columns sent as the names parameter; while this is not checked before passing along to the database, the database would normally raise an exception if these column lists don’t correspond.

      • include_defaults

        if True, non-server default values and SQL expressions as specified on Column objects (as documented in Column INSERT/UPDATE Defaults) not otherwise specified in the list of names will be rendered into the INSERT and SELECT statements, so that these values are also included in the data to be inserted.

        Note

        A Python-side default that uses a Python callable function will only be invoked once for the whole statement, and not per row.

        New in version 1.0.0: - Insert.from_select() now renders Python-side and SQL expression column defaults into the SELECT statement for columns otherwise not included in the list of column names.

  1. Changed in version 1.0.0: an INSERT that uses FROM SELECT implies that the [insert.inline](#sqlalchemy.sql.expression.insert.params.inline "sqlalchemy.sql.expression.insert") flag is set to True, indicating that the statement will not attempt to fetch the last inserted primary key or other defaults. The statement deals with an arbitrary number of rows, so the [CursorResult.inserted\_primary\_key]($3743e3464fa80ce7.md#sqlalchemy.engine.CursorResult.inserted_primary_key "sqlalchemy.engine.CursorResult.inserted_primary_key") accessor does not apply.
  • method sqlalchemy.sql.expression.Insert.inline() → SelfInsert

    Make this Insert construct “inline” .

    When set, no attempt will be made to retrieve the SQL-generated default values to be provided within the statement; in particular, this allows SQL expressions to be rendered ‘inline’ within the statement without the need to pre-execute them beforehand; for backends that support “returning”, this turns off the “implicit returning” feature for the statement.

    Changed in version 1.4: the Insert.inline parameter is now superseded by the Insert.inline() method.

  • attribute sqlalchemy.sql.expression.Insert.select: Optional[Select[Any]] = None

    SELECT statement for INSERT .. FROM SELECT

class sqlalchemy.sql.expression.Update

Represent an Update construct.

The Update object is created using the update() function.

Members

returning(), where(), values(), inline(), ordered_values()

Class signature

class sqlalchemy.sql.expression.Update (sqlalchemy.sql.expression.DMLWhereBase, sqlalchemy.sql.expression.ValuesBase)

  • method sqlalchemy.sql.expression.Update.returning(*cols: _ColumnsClauseArgument[Any], **_UpdateBase\_kw: Any_) → UpdateBase

    inherited from the UpdateBase.returning() method of UpdateBase

    Add a RETURNING or equivalent clause to this statement.

    e.g.:

    1. >>> stmt = (
    2. ... table.update()
    3. ... .where(table.c.data == "value")
    4. ... .values(status="X")
    5. ... .returning(table.c.server_flag, table.c.updated_timestamp)
    6. ... )
    7. >>> print(stmt)
    8. UPDATE some_table SET status=:status
    9. WHERE some_table.data = :data_1
    10. RETURNING some_table.server_flag, some_table.updated_timestamp

    The method may be invoked multiple times to add new entries to the list of expressions to be returned.

    New in version 1.4.0b2: The method may be invoked multiple times to add new entries to the list of expressions to be returned.

    The given collection of column expressions should be derived from the table that is the target of the INSERT, UPDATE, or DELETE. While Column objects are typical, the elements can also be expressions:

    1. >>> stmt = table.insert().returning(
    2. ... (table.c.first_name + " " + table.c.last_name).label("fullname")
    3. ... )
    4. >>> print(stmt)
    5. INSERT INTO some_table (first_name, last_name)
    6. VALUES (:first_name, :last_name)
    7. RETURNING some_table.first_name || :first_name_1 || some_table.last_name AS fullname

    Upon compilation, a RETURNING clause, or database equivalent, will be rendered within the statement. For INSERT and UPDATE, the values are the newly inserted/updated values. For DELETE, the values are those of the rows which were deleted.

    Upon execution, the values of the columns to be returned are made available via the result set and can be iterated using CursorResult.fetchone() and similar. For DBAPIs which do not natively support returning values (i.e. cx_oracle), SQLAlchemy will approximate this behavior at the result level so that a reasonable amount of behavioral neutrality is provided.

    Note that not all databases/DBAPIs support RETURNING. For those backends with no support, an exception is raised upon compilation and/or execution. For those who do support it, the functionality across backends varies greatly, including restrictions on executemany() and other statements which return multiple rows. Please read the documentation notes for the database in use in order to determine the availability of RETURNING.

    See also

    UpdateBase.return_defaults() - an alternative method tailored towards efficient fetching of server-side defaults and triggers for single-row INSERTs or UPDATEs.

    INSERT…RETURNING - in the SQLAlchemy Unified Tutorial

  • method sqlalchemy.sql.expression.Update.where(*whereclause: _ColumnExpressionArgument[bool]) → SelfDMLWhereBase

    inherited from the DMLWhereBase.where() method of DMLWhereBase

    Return a new construct with the given expression(s) added to its WHERE clause, joined to the existing clause via AND, if any.

    Both Update.where() and Delete.where() support multiple-table forms, including database-specific UPDATE...FROM as well as DELETE..USING. For backends that don’t have multiple-table support, a backend agnostic approach to using multiple tables is to make use of correlated subqueries. See the linked tutorial sections below for examples.

    See also

    Correlated Updates

    UPDATE..FROM

    Multiple Table Deletes

  • method sqlalchemy.sql.expression.Update.values(*args: Union[Dict[_DMLColumnArgument, Any], Sequence[Any]], **kwargs: Any) → SelfValuesBase

    inherited from the ValuesBase.values() method of ValuesBase

    Specify a fixed VALUES clause for an INSERT statement, or the SET clause for an UPDATE.

    Note that the Insert and Update constructs support per-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” a particular set of parameters into the statement.

    Multiple calls to ValuesBase.values() will produce a new construct, each one with the parameter list modified to include the new parameters sent. In the typical case of a single dictionary of parameters, the newly passed keys will replace the same keys in the previous construct. In the case of a list-based “multiple values” construct, each new list of values is extended onto the existing list of values.

    • Parameters:

      • **kwargs

        key value pairs representing the string key of a Column mapped to the value to be rendered into the VALUES or SET clause:

        1. users.insert().values(name="some name")
        2. users.update().where(users.c.id==5).values(name="some name")
      • *args

        As an alternative to passing key/value parameters, a dictionary, tuple, or list of dictionaries or tuples can be passed as a single positional argument in order to form the VALUES or SET clause of the statement. The forms that are accepted vary based on whether this is an Insert or an Update construct.

        For either an Insert or Update construct, a single dictionary can be passed, which works the same as that of the kwargs form:

        1. users.insert().values({"name": "some name"})
        2. 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 the table is also accepted:

        1. users.insert().values((5, "some name"))

        The Insert construct also supports being passed a list of dictionaries or full-table-tuples, which on the server will render the less common SQL syntax of “multiple values” - this syntax is supported on backends such as SQLite, PostgreSQL, MySQL, but not necessarily others:

        1. users.insert().values([
        2. {"name": "some name"},
        3. {"name": "some other name"},
        4. {"name": "yet another name"},
        5. ])

        The above form would render a multiple VALUES statement similar to:

        1. INSERT INTO users (name) VALUES
        2. (:name_1),
        3. (:name_2),
        4. (:name_3)

        It is essential to note that passing multiple values is NOT the same as using traditional executemany() form. The above syntax is a special syntax not typically used. To emit an INSERT statement against multiple rows, the normal method is to pass a multiple values list to the Connection.execute() method, which is supported by all database backends and is generally more efficient for a very large number of parameters.

        See also

        Sending Multiple Parameters - an introduction to the traditional Core method of multiple parameter set invocation for INSERTs and other statements.

        Changed in version 1.0.0: an INSERT that uses a multiple-VALUES clause, even a list of length one, implies that the Insert.inline flag is set to True, indicating that the statement will not attempt to fetch the “last inserted primary key” or other defaults. The statement deals with an arbitrary number of rows, so the CursorResult.inserted_primary_key accessor does not apply.

        Changed in version 1.0.0: A multiple-VALUES INSERT now supports columns with Python side default values and callables in the same way as that of an “executemany” style of invocation; the callable is invoked for each row. See Python-side defaults invoked for each row individually when using a multivalued insert for other details.

        The UPDATE construct also supports rendering the SET parameters in a specific order. For this feature refer to the Update.ordered_values() method.

        See also

        Update.ordered_values()

class sqlalchemy.sql.expression.UpdateBase

Form the base for INSERT, UPDATE, and DELETE statements.

Members

entity_description, exported_columns, params(), return_defaults(), returning(), returning_column_descriptions, with_dialect_options(), with_hint()

Class signature

class sqlalchemy.sql.expression.UpdateBase (sqlalchemy.sql.roles.DMLRole, sqlalchemy.sql.expression.HasCTE, sqlalchemy.sql.expression.HasCompileState, sqlalchemy.sql.base.DialectKWArgs, sqlalchemy.sql.expression.HasPrefixes, sqlalchemy.sql.expression.Generative, sqlalchemy.sql.expression.ExecutableReturnsRows, sqlalchemy.sql.expression.ClauseElement)

  1. See also
  2. [UpdateBase.returning()](#sqlalchemy.sql.expression.UpdateBase.returning "sqlalchemy.sql.expression.UpdateBase.returning")
  3. [CursorResult.returned\_defaults]($3743e3464fa80ce7.md#sqlalchemy.engine.CursorResult.returned_defaults "sqlalchemy.engine.CursorResult.returned_defaults")
  4. [CursorResult.returned\_defaults\_rows]($3743e3464fa80ce7.md#sqlalchemy.engine.CursorResult.returned_defaults_rows "sqlalchemy.engine.CursorResult.returned_defaults_rows")
  5. [CursorResult.inserted\_primary\_key]($3743e3464fa80ce7.md#sqlalchemy.engine.CursorResult.inserted_primary_key "sqlalchemy.engine.CursorResult.inserted_primary_key")
  6. [CursorResult.inserted\_primary\_key\_rows]($3743e3464fa80ce7.md#sqlalchemy.engine.CursorResult.inserted_primary_key_rows "sqlalchemy.engine.CursorResult.inserted_primary_key_rows")
  • method sqlalchemy.sql.expression.UpdateBase.returning(*cols: _ColumnsClauseArgument[Any], **_UpdateBase\_kw: Any_) → UpdateBase

    Add a RETURNING or equivalent clause to this statement.

    e.g.:

    1. >>> stmt = (
    2. ... table.update()
    3. ... .where(table.c.data == "value")
    4. ... .values(status="X")
    5. ... .returning(table.c.server_flag, table.c.updated_timestamp)
    6. ... )
    7. >>> print(stmt)
    8. UPDATE some_table SET status=:status
    9. WHERE some_table.data = :data_1
    10. RETURNING some_table.server_flag, some_table.updated_timestamp

    The method may be invoked multiple times to add new entries to the list of expressions to be returned.

    New in version 1.4.0b2: The method may be invoked multiple times to add new entries to the list of expressions to be returned.

    The given collection of column expressions should be derived from the table that is the target of the INSERT, UPDATE, or DELETE. While Column objects are typical, the elements can also be expressions:

    1. >>> stmt = table.insert().returning(
    2. ... (table.c.first_name + " " + table.c.last_name).label("fullname")
    3. ... )
    4. >>> print(stmt)
    5. INSERT INTO some_table (first_name, last_name)
    6. VALUES (:first_name, :last_name)
    7. RETURNING some_table.first_name || :first_name_1 || some_table.last_name AS fullname

    Upon compilation, a RETURNING clause, or database equivalent, will be rendered within the statement. For INSERT and UPDATE, the values are the newly inserted/updated values. For DELETE, the values are those of the rows which were deleted.

    Upon execution, the values of the columns to be returned are made available via the result set and can be iterated using CursorResult.fetchone() and similar. For DBAPIs which do not natively support returning values (i.e. cx_oracle), SQLAlchemy will approximate this behavior at the result level so that a reasonable amount of behavioral neutrality is provided.

    Note that not all databases/DBAPIs support RETURNING. For those backends with no support, an exception is raised upon compilation and/or execution. For those who do support it, the functionality across backends varies greatly, including restrictions on executemany() and other statements which return multiple rows. Please read the documentation notes for the database in use in order to determine the availability of RETURNING.

    See also

    UpdateBase.return_defaults() - an alternative method tailored towards efficient fetching of server-side defaults and triggers for single-row INSERTs or UPDATEs.

    INSERT…RETURNING - in the SQLAlchemy Unified Tutorial

  • attribute sqlalchemy.sql.expression.UpdateBase.returning_column_descriptions

    Return a plugin-enabled description of the columns which this DML construct is RETURNING against, in other words the expressions established as part of UpdateBase.returning().

    This attribute is generally useful when using the ORM, as an extended structure which includes information about mapped entities is returned. The section Inspecting entities and columns from ORM-enabled SELECT and DML statements contains more background.

    For a Core statement, the structure returned by this accessor is derived from the same objects that are returned by the UpdateBase.exported_columns accessor:

    1. >>> stmt = insert(user_table).returning(user_table.c.id, user_table.c.name)
    2. >>> stmt.entity_description
    3. [
    4. {
    5. "name": "id",
    6. "type": Integer,
    7. "expr": Column("id", Integer(), table=<user>, ...)
    8. },
    9. {
    10. "name": "name",
    11. "type": String(),
    12. "expr": Column("name", String(), table=<user>, ...)
    13. },
    14. ]

    New in version 1.4.33.

    See also

    UpdateBase.entity_description

    Select.column_descriptions - entity information for a select() construct

    Inspecting entities and columns from ORM-enabled SELECT and DML statements - ORM background

  • method sqlalchemy.sql.expression.UpdateBase.with_dialect_options(**opt: Any) → SelfUpdateBase

    Add dialect options to this INSERT/UPDATE/DELETE object.

    e.g.:

    1. upd = table.update().dialect_options(mysql_limit=10)
  • method sqlalchemy.sql.expression.UpdateBase.with_hint(text: str, selectable: Optional[_DMLTableArgument] = None, dialect_name: str = ‘*‘) → SelfUpdateBase

    Add a table hint for a single table to this INSERT/UPDATE/DELETE statement.

    Note

    UpdateBase.with_hint() currently applies only to Microsoft SQL Server. For MySQL INSERT/UPDATE/DELETE hints, use UpdateBase.prefix_with().

    The text of the hint is rendered in the appropriate location for the database backend in use, relative to the Table that is the subject of this statement, or optionally to that of the given Table passed as the selectable argument.

    The dialect_name option will limit the rendering of a particular hint to a particular backend. Such as, to add a hint that only takes effect for SQL Server:

    1. mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql")
    • Parameters:

      • text – Text of the hint.

      • selectable – optional Table that specifies an element of the FROM clause within an UPDATE or DELETE to be the subject of the hint - applies only to certain backends.

      • dialect_name – defaults to *, if specified as the name of a particular dialect, will apply these hints only when that dialect is in use.

class sqlalchemy.sql.expression.ValuesBase

Supplies support for ValuesBase.values() to INSERT and UPDATE constructs.

Members

select, values()

Class signature

class sqlalchemy.sql.expression.ValuesBase (sqlalchemy.sql.expression.UpdateBase)

  • attribute sqlalchemy.sql.expression.ValuesBase.select: Optional[Select[Any]] = None

    SELECT statement for INSERT .. FROM SELECT

  • method sqlalchemy.sql.expression.ValuesBase.values(*args: Union[Dict[_DMLColumnArgument, Any], Sequence[Any]], **kwargs: Any) → SelfValuesBase

    Specify a fixed VALUES clause for an INSERT statement, or the SET clause for an UPDATE.

    Note that the Insert and Update constructs support per-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” a particular set of parameters into the statement.

    Multiple calls to ValuesBase.values() will produce a new construct, each one with the parameter list modified to include the new parameters sent. In the typical case of a single dictionary of parameters, the newly passed keys will replace the same keys in the previous construct. In the case of a list-based “multiple values” construct, each new list of values is extended onto the existing list of values.

    • Parameters:

      • **kwargs

        key value pairs representing the string key of a Column mapped to the value to be rendered into the VALUES or SET clause:

        1. users.insert().values(name="some name")
        2. users.update().where(users.c.id==5).values(name="some name")
      • *args

        As an alternative to passing key/value parameters, a dictionary, tuple, or list of dictionaries or tuples can be passed as a single positional argument in order to form the VALUES or SET clause of the statement. The forms that are accepted vary based on whether this is an Insert or an Update construct.

        For either an Insert or Update construct, a single dictionary can be passed, which works the same as that of the kwargs form:

        1. users.insert().values({"name": "some name"})
        2. 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 the table is also accepted:

        1. users.insert().values((5, "some name"))

        The Insert construct also supports being passed a list of dictionaries or full-table-tuples, which on the server will render the less common SQL syntax of “multiple values” - this syntax is supported on backends such as SQLite, PostgreSQL, MySQL, but not necessarily others:

        1. users.insert().values([
        2. {"name": "some name"},
        3. {"name": "some other name"},
        4. {"name": "yet another name"},
        5. ])

        The above form would render a multiple VALUES statement similar to:

        1. INSERT INTO users (name) VALUES
        2. (:name_1),
        3. (:name_2),
        4. (:name_3)

        It is essential to note that passing multiple values is NOT the same as using traditional executemany() form. The above syntax is a special syntax not typically used. To emit an INSERT statement against multiple rows, the normal method is to pass a multiple values list to the Connection.execute() method, which is supported by all database backends and is generally more efficient for a very large number of parameters.

        See also

        Sending Multiple Parameters - an introduction to the traditional Core method of multiple parameter set invocation for INSERTs and other statements.

        Changed in version 1.0.0: an INSERT that uses a multiple-VALUES clause, even a list of length one, implies that the Insert.inline flag is set to True, indicating that the statement will not attempt to fetch the “last inserted primary key” or other defaults. The statement deals with an arbitrary number of rows, so the CursorResult.inserted_primary_key accessor does not apply.

        Changed in version 1.0.0: A multiple-VALUES INSERT now supports columns with Python side default values and callables in the same way as that of an “executemany” style of invocation; the callable is invoked for each row. See Python-side defaults invoked for each row individually when using a multivalued insert for other details.

        The UPDATE construct also supports rendering the SET parameters in a specific order. For this feature refer to the Update.ordered_values() method.

        See also

        Update.ordered_values()