SELECT and Related Constructs

    Top level “FROM clause” and “SELECT” constructors.

    function sqlalchemy.sql.expression.except_(*selects: _SelectStatementForCompoundArgument) →

    Return an EXCEPT of multiple selectables.

    The returned object is an instance of CompoundSelect.

    • Parameters:

      *selects – a list of instances.

    function sqlalchemy.sql.expression.except_all(*selects: _SelectStatementForCompoundArgument) → CompoundSelect

    Return an EXCEPT ALL of multiple selectables.

    The returned object is an instance of .

    • Parameters:

      *selects – a list of Select instances.

    function sqlalchemy.sql.expression.exists(\_argument: Optional[Union[_ColumnsClauseArgument[Any], , ScalarSelect[Any]]] = None_) →

    Construct a new Exists construct.

    The can be invoked by itself to produce an Exists construct, which will accept simple WHERE criteria:

    However, for greater flexibility in constructing the SELECT, an existing construct may be converted to an Exists, most conveniently by making use of the method:

    1. exists_criteria = (
    2. select(table2.c.col2).
    3. where(table1.c.col1 == table2.c.col2).
    4. exists()
    5. )

    The EXISTS criteria is then used inside of an enclosing SELECT:

    1. stmt = select(table1.c.col1).where(exists_criteria)

    The above statement will then be of the form:

    1. SELECT col1 FROM table1 WHERE EXISTS
    2. (SELECT table2.col2 FROM table2 WHERE table2.col2 = table1.col1)

    See also

    EXISTS subqueries - in the tutorial.

    SelectBase.exists() - method to transform a SELECT to an EXISTS clause.

    function sqlalchemy.sql.expression.intersect(*selects: _SelectStatementForCompoundArgument) →

    Return an INTERSECT of multiple selectables.

    The returned object is an instance of CompoundSelect.

    • Parameters:

      *selects – a list of instances.

    function sqlalchemy.sql.expression.intersect_all(*selects: _SelectStatementForCompoundArgument) → CompoundSelect

    Return an INTERSECT ALL of multiple selectables.

    The returned object is an instance of .

    • Parameters:

      *selects – a list of Select instances.

    function sqlalchemy.sql.expression.select(*entities: _ColumnsClauseArgument[Any], **\_kw: Any_) → [Any]

    Construct a new Select.

    New in version 1.4: - The function now accepts column arguments positionally. The top-level select() function will automatically use the 1.x or 2.x style API based on the incoming arguments; using from the sqlalchemy.future module will enforce that only the 2.x style constructor is used.

    Similar functionality is also available via the FromClause.select() method on any .

    See also

    Using SELECT Statements - in the

    • Parameters:

      *entities

      Entities to SELECT from. For Core usage, this is typically a series of ColumnElement and / or objects which will form the columns clause of the resulting statement. For those objects that are instances of FromClause (typically or Alias objects), the collection is extracted to form a collection of ColumnElement objects.

      This parameter will also accept constructs as given, as well as ORM-mapped classes.

    function sqlalchemy.sql.expression.table(name: str, *columns: ColumnClause[Any], **kw: Any) →

    Produce a new TableClause.

    The object returned is an instance of , which represents the “syntactical” portion of the schema-level Table object. It may be used to construct lightweight table constructs.

    Changed in version 1.0.0: can now be imported from the plain sqlalchemy namespace like any other SQL element.

    • Parameters:

      • name – Name of the table.

      • columns – A collection of column() constructs.

      • schema

        The schema name for this table.

        New in version 1.3.18: can now accept a schema argument.

    function sqlalchemy.sql.expression.union(*selects: _SelectStatementForCompoundArgument) → CompoundSelect

    Return a UNION of multiple selectables.

    The returned object is an instance of .

    A similar union() method is available on all subclasses.

    • Parameters:

      • *selects – a list of Select instances.

      • **kwargs – available keyword arguments are the same as those of .

    function sqlalchemy.sql.expression.union_all(*selects: _SelectStatementForCompoundArgument) → CompoundSelect

    Return a UNION ALL of multiple selectables.

    The returned object is an instance of .

    A similar union_all() method is available on all subclasses.

    • Parameters:

      *selects – a list of Select instances.

    function sqlalchemy.sql.expression.values(*columns: [Any], name: Optional[str] = None, literal_binds: bool = False) → Values

    Construct a construct.

    The column expressions and the actual data for Values are given in two separate steps. The constructor receives the column expressions typically as constructs, and the data is then passed via the Values.data() method as a list, which can be called multiple times to add more data, e.g.:

    1. from sqlalchemy import column
    2. from sqlalchemy import values
    3. value_expr = values(
    4. column('id', Integer),
    5. column('name', String),
    6. name="my_values"
    7. ).data(
    8. [(1, 'name1'), (2, 'name2'), (3, 'name3')]
    9. )
    • Parameters:

      • *columns – column expressions, typically composed using objects.

      • name – the name for this VALUES construct. If omitted, the VALUES construct will be unnamed in a SQL expression. Different backends may have different requirements here.

      • literal_binds – Defaults to False. Whether or not to render the data values inline in the SQL output, rather than using bound parameters.

    Functions listed here are more commonly available as methods from and Selectable elements, for example, the function is usually invoked via the FromClause.alias() method.

    function sqlalchemy.sql.expression.alias(selectable: , name: Optional[str] = None, flat: bool = False) → NamedFromClause

    Return a named alias of the given FromClause.

    For and Join objects, the return type is the object. Other kinds of NamedFromClause objects may be returned for other kinds of FromClause objects.

    The named alias represents any with an alternate name assigned within SQL, typically using the AS clause when generated, e.g. SELECT * FROM table AS aliasname.

    Equivalent functionality is available via the FromClause.alias() method available on all objects.

    • Parameters:

      • selectable – any FromClause subclass, such as a table, select statement, etc.

      • name – string name to be assigned as the alias. If None, a name will be deterministically generated at compile time. Deterministic means the name is guaranteed to be unique against other constructs used in the same statement, and will also be the same name for each successive compilation of the same statement object.

      • flat – Will be passed through to if the given selectable is an instance of - see Join.alias() for details.

    function sqlalchemy.sql.expression.cte(selectable: HasCTE, name: Optional[str] = None, recursive: bool = False) →

    Return a new CTE, or Common Table Expression instance.

    Please see for detail on CTE usage.

    function sqlalchemy.sql.expression.join(left: _FromClauseArgument, right: _FromClauseArgument, onclause: Optional[_OnClauseArgument] = None, isouter: bool = False, full: bool = False) → Join

    Produce a object, given two FromClause expressions.

    E.g.:

    1. j = join(user_table, address_table,
    2. user_table.c.id == address_table.c.user_id)
    3. stmt = select(user_table).select_from(j)

    would emit SQL along the lines of:

    1. SELECT user.id, user.name FROM user
    2. JOIN address ON user.id = address.user_id

    Similar functionality is available given any object (e.g. such as a Table) using the method.

    • Parameters:

      • left – The left side of the join.

      • right – the right side of the join; this is any FromClause object such as a object, and may also be a selectable-compatible object such as an ORM-mapped class.

      • onclause – a SQL expression representing the ON clause of the join. If left at None, FromClause.join() will attempt to join the two tables based on a foreign key relationship.

      • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.

      • full

        if True, render a FULL OUTER JOIN, instead of JOIN.

        New in version 1.1.

    See also

    - method form, based on a given left side.

    Join - the type of object produced.

    function sqlalchemy.sql.expression.lateral(selectable: Union[, _FromClauseArgument], name: Optional[str] = None) → LateralFromClause

    Return a Lateral object.

    is an Alias subclass that represents a subquery with the LATERAL keyword applied to it.

    The special behavior of a LATERAL subquery is that it appears in the FROM clause of an enclosing SELECT, but may correlate to other FROM clauses of that SELECT. It is a special case of subquery only supported by a small number of backends, currently more recent PostgreSQL versions.

    New in version 1.1.

    See also

    - overview of usage.

    function sqlalchemy.sql.expression.outerjoin(left: _FromClauseArgument, right: _FromClauseArgument, onclause: Optional[_OnClauseArgument] = None, full: bool = False) → Join

    Return an OUTER JOIN clause element.

    The returned object is an instance of .

    Similar functionality is also available via the FromClause.outerjoin() method on any .

    • Parameters:

      • left – The left side of the join.

      • right – The right side of the join.

      • onclause – Optional criterion for the ON clause, is derived from foreign key relationships established between left and right otherwise.

    To chain joins together, use the FromClause.join() or methods on the resulting Join object.

    function sqlalchemy.sql.expression.tablesample(selectable: _FromClauseArgument, sampling: Union[float, [Any]], name: Optional[str] = None, seed: Optional[roles.ExpressionElementRole[Any]] = None) → TableSample

    Return a object.

    TableSample is an subclass that represents a table with the TABLESAMPLE clause applied to it. tablesample() is also available from the class via the FromClause.tablesample() method.

    The TABLESAMPLE clause allows selecting a randomly selected approximate percentage of rows from a table. It supports multiple sampling methods, most commonly BERNOULLI and SYSTEM.

    e.g.:

    1. from sqlalchemy import func
    2. selectable = people.tablesample(
    3. func.bernoulli(1),
    4. name='alias',
    5. seed=func.random())
    6. stmt = select(selectable.c.people_id)

    Assuming people with a column people_id, the above statement would render as:

    1. SELECT alias.people_id FROM
    2. people AS alias TABLESAMPLE bernoulli(:bernoulli_1)
    3. REPEATABLE (random())

    New in version 1.1.

    • Parameters:

      • sampling – a float percentage between 0 and 100 or .

      • name – optional alias name

      • seed – any real-valued SQL expression. When specified, the REPEATABLE sub-clause is also rendered.

    The classes here are generated using the constructors listed at and Selectable Modifier Constructors.

    class sqlalchemy.sql.expression.Alias

    Represents an table or selectable alias (AS).

    Represents an alias, as typically applied to any table or sub-select within a SQL statement using the AS keyword (or without the keyword on certain databases such as Oracle).

    This object is constructed from the module level function as well as the FromClause.alias() method available on all subclasses.

    See also

    FromClause.alias()

    Members

    Class signature

    class sqlalchemy.sql.expression.Alias (sqlalchemy.sql.roles.DMLTableRole, sqlalchemy.sql.expression.FromClauseAlias)

    • attribute inherit_cache: Optional[bool] = True

      Indicate if this HasCacheKey instance should make use of the cache key generation scheme used by its immediate superclass.

      The attribute defaults to None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value to False, except that a warning is also emitted.

      This flag can be set to True on a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.

      See also

      - General guideslines for setting the HasCacheKey.inherit_cache attribute for third-party or user defined SQL constructs.

    class sqlalchemy.sql.expression.AliasedReturnsRows

    Base class of aliases against tables, subqueries, and other selectables.

    Members

    , is_derived_from(),

    Class signature

    class sqlalchemy.sql.expression.AliasedReturnsRows (sqlalchemy.sql.expression.NoInit, sqlalchemy.sql.expression.NamedFromClause)

    • attribute description

    • method sqlalchemy.sql.expression.AliasedReturnsRows.is_derived_from(fromclause: Optional[]) → bool

      Return True if this FromClause is ‘derived’ from the given FromClause.

      An example would be an Alias of a Table is derived from that Table.

    • attribute original

      Legacy for dialects that are referring to Alias.original.

    class sqlalchemy.sql.expression.CompoundSelect

    Forms the basis of UNION, UNION ALL, and other SELECT-based set operations.

    See also

    union()

    intersect()

    except()

    except_all()

    Members

    , alias(), , c, , cte(), , exists(), , fetch(), , get_label_style(), , is_derived_from(), , lateral(), , offset(), , order_by(), , scalar_subquery(), , selected_columns, , set_label_style(), , subquery(),

    Class signature

    class sqlalchemy.sql.expression.CompoundSelect (sqlalchemy.sql.expression.HasCompileState, , sqlalchemy.sql.expression.ExecutableReturnsRows)

    • method sqlalchemy.sql.expression.CompoundSelect.add_cte(*ctes: , nest_here: bool = False) → SelfHasCTE

      inherited from the HasCTE.add_cte() method of

      Add one or more CTE constructs to this statement.

      This method will associate the given constructs with the parent statement such that they will each be unconditionally rendered in the WITH clause of the final statement, even if not referenced elsewhere within the statement or any sub-selects.

      The optional HasCTE.add_cte.nest_here parameter when set to True will have the effect that each given will render in a WITH clause rendered directly along with this statement, rather than being moved to the top of the ultimate rendered statement, even if this statement is rendered as a subquery within a larger statement.

      This method has two general uses. One is to embed CTE statements that serve some purpose without being referenced explicitly, such as the use case of embedding a DML statement such as an INSERT or UPDATE as a CTE inline with a primary statement that may draw from its results indirectly. The other is to provide control over the exact placement of a particular series of CTE constructs that should remain rendered directly in terms of a particular statement that may be nested in a larger statement.

      E.g.:

      1. from sqlalchemy import table, column, select
      2. t = table('t', column('c1'), column('c2'))
      3. ins = t.insert().values({"c1": "x", "c2": "y"}).cte()
      4. stmt = select(t).add_cte(ins)

      Would render:

      1. WITH anon_1 AS
      2. (INSERT INTO t (c1, c2) VALUES (:param_1, :param_2))
      3. SELECT t.c1, t.c2
      4. FROM t

      Above, the “anon_1” CTE is not referred towards in the SELECT statement, however still accomplishes the task of running an INSERT statement.

      Similarly in a DML-related context, using the PostgreSQL Insert construct to generate an “upsert”:

      1. from sqlalchemy import table, column
      2. from sqlalchemy.dialects.postgresql import insert
      3. t = table("t", column("c1"), column("c2"))
      4. delete_statement_cte = (
      5. t.delete().where(t.c.c1 < 1).cte("deletions")
      6. )
      7. insert_stmt = insert(t).values({"c1": 1, "c2": 2})
      8. update_statement = insert_stmt.on_conflict_do_update(
      9. index_elements=[t.c.c1],
      10. set_={
      11. "c1": insert_stmt.excluded.c1,
      12. "c2": insert_stmt.excluded.c2,
      13. },
      14. ).add_cte(delete_statement_cte)
      15. print(update_statement)

      The above statement renders as:

      1. WITH deletions AS
      2. (DELETE FROM t WHERE t.c1 < %(c1_1)s)
      3. INSERT INTO t (c1, c2) VALUES (%(c1)s, %(c2)s)
      4. ON CONFLICT (c1) DO UPDATE SET c1 = excluded.c1, c2 = excluded.c2

      New in version 1.4.21.

      • Parameters:

        • *ctes

          zero or more constructs.

          Changed in version 2.0: Multiple CTE instances are accepted

        • nest_here

          if True, the given CTE or CTEs will be rendered as though they specified the HasCTE.cte.nesting flag to True when they were added to this . Assuming the given CTEs are not referenced in an outer-enclosing statement as well, the CTEs given should render at the level of this statement when this flag is given.

          New in version 2.0.

          See also

          HasCTE.cte.nesting

    • method alias(name: Optional[str] = None, flat: bool = False) → Subquery

      inherited from the method of SelectBase

      Return a named subquery against this .

      For a SelectBase (as opposed to a ), this returns a Subquery object which behaves mostly the same as the object that is used with a FromClause.

      Changed in version 1.4: The method is now a synonym for the SelectBase.subquery() method.

    • method as_scalar() → ScalarSelect[Any]

      inherited from the method of SelectBase

      Deprecated since version 1.4: The method is deprecated and will be removed in a future release. Please refer to SelectBase.scalar_subquery().

    • attribute c

      inherited from the SelectBase.c attribute of

      Deprecated since version 1.4: The SelectBase.c and SelectBase.columns attributes are deprecated and will be removed in a future release; these attributes implicitly create a subquery that should be explicit. Please call first in order to create a subquery, which then contains this attribute. To access the columns that this SELECT object SELECTs from, use the SelectBase.selected_columns attribute.

    • method corresponding_column(column: KeyedColumnElement[Any], require_embedded: bool = False) → Optional[KeyedColumnElement[Any]]

      inherited from the Selectable.corresponding_column() method of

      Given a ColumnElement, return the exported object from the Selectable.exported_columns collection of this which corresponds to that original ColumnElement via a common ancestor column.

      • Parameters:

        • column – the target to be matched.

        • require_embedded – only return corresponding columns for the given ColumnElement, if the given is actually present within a sub-element of this Selectable. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this .

    1. See also
    2. [Selectable.exported\_columns](#sqlalchemy.sql.expression.Selectable.exported_columns "sqlalchemy.sql.expression.Selectable.exported_columns") - the [ColumnCollection]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnCollection "sqlalchemy.sql.expression.ColumnCollection") that is used for the operation.
    3. [ColumnCollection.corresponding\_column()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnCollection.corresponding_column "sqlalchemy.sql.expression.ColumnCollection.corresponding_column") - implementation method.
    • method sqlalchemy.sql.expression.CompoundSelect.cte(name: Optional[str] = None, recursive: bool = False, nesting: bool = False) →

      inherited from the HasCTE.cte() method of

      Return a new CTE, or Common Table Expression instance.

      Common table expressions are a SQL standard whereby SELECT statements can draw upon secondary statements specified along with the primary statement, using a clause called “WITH”. Special semantics regarding UNION can also be employed to allow “recursive” queries, where a SELECT statement can draw upon the set of rows that have previously been selected.

      CTEs can also be applied to DML constructs UPDATE, INSERT and DELETE on some databases, both as a source of CTE rows when combined with RETURNING, as well as a consumer of CTE rows.

      Changed in version 1.1: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.

      SQLAlchemy detects objects, which are treated similarly to Alias objects, as special elements to be delivered to the FROM clause of the statement as well as to a WITH clause at the top of the statement.

      For special prefixes such as PostgreSQL “MATERIALIZED” and “NOT MATERIALIZED”, the CTE.prefix_with() method may be used to establish these.

      Changed in version 1.3.13: Added support for prefixes. In particular - MATERIALIZED and NOT MATERIALIZED.

      • Parameters:

        • name – name given to the common table expression. Like , the name can be left as None in which case an anonymous symbol will be used at query compile time.

        • recursive – if True, will render WITH RECURSIVE. A recursive common table expression is intended to be used in conjunction with UNION ALL in order to derive rows from those already selected.

        • nesting

          if True, will render the CTE locally to the statement in which it is referenced. For more complex scenarios, the HasCTE.add_cte() method using the parameter may also be used to more carefully control the exact placement of a particular CTE.

          New in version 1.4.24.

          See also

          HasCTE.add_cte()

    1. The following examples include two from PostgreSQLs documentation at [https://www.postgresql.org/docs/current/static/queries-with.html](https://www.postgresql.org/docs/current/static/queries-with.html), as well as additional examples.
    2. Example 1, non recursive:
    3. ```
    4. from sqlalchemy import (Table, Column, String, Integer,
    5. MetaData, select, func)
    6. metadata = MetaData()
    7. orders = Table('orders', metadata,
    8. Column('region', String),
    9. Column('amount', Integer),
    10. Column('product', String),
    11. Column('quantity', Integer)
    12. )
    13. regional_sales = select(
    14. orders.c.region,
    15. func.sum(orders.c.amount).label('total_sales')
    16. ).group_by(orders.c.region).cte("regional_sales")
    17. top_regions = select(regional_sales.c.region).\
    18. where(
    19. regional_sales.c.total_sales >
    20. select(
    21. func.sum(regional_sales.c.total_sales) / 10
    22. )
    23. ).cte("top_regions")
    24. statement = select(
    25. orders.c.region,
    26. orders.c.product,
    27. func.sum(orders.c.quantity).label("product_units"),
    28. func.sum(orders.c.amount).label("product_sales")
    29. ).where(orders.c.region.in_(
    30. select(top_regions.c.region)
    31. )).group_by(orders.c.region, orders.c.product)
    32. result = conn.execute(statement).fetchall()
    33. ```
    34. Example 2, WITH RECURSIVE:
    35. ```
    36. from sqlalchemy import (Table, Column, String, Integer,
    37. MetaData, select, func)
    38. metadata = MetaData()
    39. parts = Table('parts', metadata,
    40. Column('part', String),
    41. Column('sub_part', String),
    42. Column('quantity', Integer),
    43. )
    44. included_parts = select(\
    45. parts.c.sub_part, parts.c.part, parts.c.quantity\
    46. ).\
    47. where(parts.c.part=='our part').\
    48. cte(recursive=True)
    49. incl_alias = included_parts.alias()
    50. parts_alias = parts.alias()
    51. included_parts = included_parts.union_all(
    52. select(
    53. parts_alias.c.sub_part,
    54. parts_alias.c.part,
    55. parts_alias.c.quantity
    56. ).\
    57. where(parts_alias.c.part==incl_alias.c.sub_part)
    58. )
    59. statement = select(
    60. included_parts.c.sub_part,
    61. func.sum(included_parts.c.quantity).
    62. label('total_quantity')
    63. ).\
    64. group_by(included_parts.c.sub_part)
    65. result = conn.execute(statement).fetchall()
    66. ```
    67. Example 3, an upsert using UPDATE and INSERT with CTEs:
    68. ```
    69. from datetime import date
    70. from sqlalchemy import (MetaData, Table, Column, Integer,
    71. Date, select, literal, and_, exists)
    72. metadata = MetaData()
    73. visitors = Table('visitors', metadata,
    74. Column('product_id', Integer, primary_key=True),
    75. Column('date', Date, primary_key=True),
    76. Column('count', Integer),
    77. )
    78. # add 5 visitors for the product_id == 1
    79. product_id = 1
    80. day = date.today()
    81. count = 5
    82. update_cte = (
    83. visitors.update()
    84. .where(and_(visitors.c.product_id == product_id,
    85. visitors.c.date == day))
    86. .values(count=visitors.c.count + count)
    87. .returning(literal(1))
    88. .cte('update_cte')
    89. )
    90. upsert = visitors.insert().from_select(
    91. [visitors.c.product_id, visitors.c.date, visitors.c.count],
    92. select(literal(product_id), literal(day), literal(count))
    93. .where(~exists(update_cte.select()))
    94. )
    95. connection.execute(upsert)
    96. ```
    97. Example 4, Nesting CTE (SQLAlchemy 1.4.24 and above):
    98. ```
    99. value_a = select(
    100. literal("root").label("n")
    101. ).cte("value_a")
    102. # A nested CTE with the same name as the root one
    103. value_a_nested = select(
    104. literal("nesting").label("n")
    105. ).cte("value_a", nesting=True)
    106. # Nesting CTEs takes ascendency locally
    107. # over the CTEs at a higher level
    108. value_b = select(value_a_nested.c.n).cte("value_b")
    109. value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
    110. ```
    111. The above query will render the second CTE nested inside the first, shown with inline parameters below as:
    112. ```
    113. WITH
    114. value_a AS
    115. (SELECT 'root' AS n),
    116. value_b AS
    117. (WITH value_a AS
    118. (SELECT 'nesting' AS n)
    119. SELECT value_a.n AS n FROM value_a)
    120. SELECT value_a.n AS a, value_b.n AS b
    121. FROM value_a, value_b
    122. ```
    123. The same CTE can be set up using the [HasCTE.add\_cte()](#sqlalchemy.sql.expression.HasCTE.add_cte "sqlalchemy.sql.expression.HasCTE.add_cte") method as follows (SQLAlchemy 2.0 and above):
    124. ```
    125. value_a = select(
    126. literal("root").label("n")
    127. ).cte("value_a")
    128. # A nested CTE with the same name as the root one
    129. value_a_nested = select(
    130. literal("nesting").label("n")
    131. ).cte("value_a")
    132. # Nesting CTEs takes ascendency locally
    133. # over the CTEs at a higher level
    134. value_b = (
    135. select(value_a_nested.c.n).
    136. add_cte(value_a_nested, nest_here=True).
    137. cte("value_b")
    138. )
    139. value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
    140. ```
    141. Example 5, Non-Linear CTE (SQLAlchemy 1.4.28 and above):
    142. ```
    143. edge = Table(
    144. "edge",
    145. metadata,
    146. Column("id", Integer, primary_key=True),
    147. Column("left", Integer),
    148. Column("right", Integer),
    149. )
    150. root_node = select(literal(1).label("node")).cte(
    151. "nodes", recursive=True
    152. )
    153. left_edge = select(edge.c.left).join(
    154. root_node, edge.c.right == root_node.c.node
    155. )
    156. right_edge = select(edge.c.right).join(
    157. root_node, edge.c.left == root_node.c.node
    158. )
    159. subgraph_cte = root_node.union(left_edge, right_edge)
    160. subgraph = select(subgraph_cte)
    161. ```
    162. The above query will render 2 UNIONs inside the recursive CTE:
    163. ```
    164. WITH RECURSIVE nodes(node) AS (
    165. SELECT 1 AS node
    166. UNION
    167. SELECT edge."left" AS "left"
    168. FROM edge JOIN nodes ON edge."right" = nodes.node
    169. UNION
    170. SELECT edge."right" AS "right"
    171. FROM edge JOIN nodes ON edge."left" = nodes.node
    172. )
    173. SELECT nodes.node FROM nodes
    174. ```
    175. See also
    176. [Query.cte()]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query.cte "sqlalchemy.orm.Query.cte") - ORM version of [HasCTE.cte()](#sqlalchemy.sql.expression.HasCTE.cte "sqlalchemy.sql.expression.HasCTE.cte").
    • method execution_options(**kw: Any) → SelfExecutable

      inherited from the Executable.execution_options() method of

      Set non-SQL options for the statement which take effect during execution.

      Execution options can be set at many scopes, including per-statement, per-connection, or per execution, using methods such as Connection.execution_options() and parameters which accept a dictionary of options such as and Session.execute.execution_options.

      The primary characteristic of an execution option, as opposed to other kinds of options such as ORM loader options, is that execution options never affect the compiled SQL of a query, only things that affect how the SQL statement itself is invoked or how results are fetched. That is, execution options are not part of what’s accommodated by SQL compilation nor are they considered part of the cached state of a statement.

      The method is generative, as is the case for the method as applied to the and Query objects, which means when the method is called, a copy of the object is returned, which applies the given parameters to that new copy, but leaves the original unchanged:

      1. statement = select(table.c.x, table.c.y)
      2. new_statement = statement.execution_options(my_option=True)

      An exception to this behavior is the object, where the Connection.execution_options() method is explicitly not generative.

      The kinds of options that may be passed to and other related methods and parameter dictionaries include parameters that are explicitly consumed by SQLAlchemy Core or ORM, as well as arbitrary keyword arguments not defined by SQLAlchemy, which means the methods and/or parameter dictionaries may be used for user-defined parameters that interact with custom code, which may access the parameters using methods such as Executable.get_execution_options() and , or within selected event hooks using a dedicated execution_options event parameter such as ConnectionEvents.before_execute.execution_options or , e.g.:

      1. from sqlalchemy import event
      2. @event.listens_for(some_engine, "before_execute")
      3. def _process_opt(conn, statement, multiparams, params, execution_options):
      4. "run a SQL function before invoking a statement"
      5. if execution_options.get("do_special_thing", False):
      6. conn.exec_driver_sql("run_special_function()")

      Within the scope of options that are explicitly recognized by SQLAlchemy, most apply to specific classes of objects and not others. The most common execution options include:

      See also

      Connection.execution_options()

      Session.execute.execution_options

      - documentation on all ORM-specific execution options

    • method sqlalchemy.sql.expression.CompoundSelect.exists() →

      inherited from the SelectBase.exists() method of

      Return an Exists representation of this selectable, which can be used as a column expression.

      The returned object is an instance of .

      See also

      exists()

      - in the 2.0 style tutorial.

      New in version 1.4.

    • attribute exported_columns

      inherited from the SelectBase.exported_columns attribute of

      A ColumnCollection that represents the “exported” columns of this , not including TextClause constructs.

      The “exported” columns for a object are synonymous with the SelectBase.selected_columns collection.

      New in version 1.4.

      See also

      Selectable.exported_columns

    • method sqlalchemy.sql.expression.CompoundSelect.fetch(count: Union[int, _ColumnExpressionArgument[int]], with_ties: bool = False, percent: bool = False) → SelfGenerativeSelect

      inherited from the method of GenerativeSelect

      Return a new selectable with the given FETCH FIRST criterion applied.

      This is a numeric value which usually renders as FETCH {FIRST | NEXT} [ count ] {ROW | ROWS} {ONLY | WITH TIES} expression in the resulting select. This functionality is is currently implemented for Oracle, PostgreSQL, MSSQL.

      Use to specify the offset.

      Note

      The GenerativeSelect.fetch() method will replace any clause applied with .

      New in version 1.4.

      • Parameters:

        • count – an integer COUNT parameter, or a SQL expression that provides an integer result. When percent=True this will represent the percentage of rows to return, not the absolute value. Pass None to reset it.

        • with_ties – When True, the WITH TIES option is used to return any additional rows that tie for the last place in the result set according to the ORDER BY clause. The ORDER BY may be mandatory in this case. Defaults to False

        • percent – When True, count represents the percentage of the total number of selected rows to return. Defaults to False

    1. See also
    2. [GenerativeSelect.limit()](#sqlalchemy.sql.expression.GenerativeSelect.limit "sqlalchemy.sql.expression.GenerativeSelect.limit")
    3. [GenerativeSelect.offset()](#sqlalchemy.sql.expression.GenerativeSelect.offset "sqlalchemy.sql.expression.GenerativeSelect.offset")
    • method sqlalchemy.sql.expression.CompoundSelect.get_execution_options() → _ExecuteOptions

      inherited from the method of Executable

      Get the non-SQL options which will take effect during execution.

      New in version 1.3.

      See also

    • method sqlalchemy.sql.expression.CompoundSelect.get_label_style() →

      inherited from the GenerativeSelect.get_label_style() method of

      Retrieve the current label style.

      New in version 1.4.

    • method sqlalchemy.sql.expression.CompoundSelect.group_by(_GenerativeSelect\_first: Union[Literal[None, _NoArg.NO_ARG], _ColumnExpressionOrStrLabelArgument[Any]] = _NoArg.NO_ARG, *clauses: _ColumnExpressionOrStrLabelArgument[Any]_) → SelfGenerativeSelect

      inherited from the method of GenerativeSelect

      Return a new selectable with the given list of GROUP BY criterion applied.

      All existing GROUP BY settings can be suppressed by passing None.

      e.g.:

      1. stmt = select(table.c.name, func.max(table.c.stat)).\
      2. group_by(table.c.name)
      • Parameters:

        *clauses – a series of constructs which will be used to generate an GROUP BY clause.

      See also

      Aggregate functions with GROUP BY / HAVING - in the

      Ordering or Grouping by a Label - in the

    • method sqlalchemy.sql.expression.CompoundSelect.is_derived_from(fromclause: Optional[]) → bool

      Return True if this ReturnsRows is ‘derived’ from the given .

      An example would be an Alias of a Table is derived from that Table.

    • method sqlalchemy.sql.expression.CompoundSelect.label(name: Optional[str]) → [Any]

      inherited from the SelectBase.label() method of

      Return a ‘scalar’ representation of this selectable, embedded as a subquery with a label.

      See also

      SelectBase.as_scalar().

    • method lateral(name: Optional[str] = None) → LateralFromClause

      inherited from the SelectBase.lateral() method of

      Return a LATERAL alias of this Selectable.

      The return value is the construct also provided by the top-level lateral() function.

      New in version 1.1.

      See also

      - overview of usage.

    • method sqlalchemy.sql.expression.CompoundSelect.limit(limit: Union[int, _ColumnExpressionArgument[int]]) → SelfGenerativeSelect

      inherited from the method of GenerativeSelect

      Return a new selectable with the given LIMIT criterion applied.

      This is a numerical value which usually renders as a LIMIT expression in the resulting select. Backends that don’t support LIMIT will attempt to provide similar functionality.

      Note

      The method will replace any clause applied with GenerativeSelect.fetch().

      Changed in version 1.0.0: - can now accept arbitrary SQL expressions as well as integer values.

      • Parameters:

        limit – an integer LIMIT parameter, or a SQL expression that provides an integer result. Pass None to reset it.

      See also

      GenerativeSelect.fetch()

    • method sqlalchemy.sql.expression.CompoundSelect.offset(offset: Union[int, _ColumnExpressionArgument[int]]) → SelfGenerativeSelect

      inherited from the method of GenerativeSelect

      Return a new selectable with the given OFFSET criterion applied.

      This is a numeric value which usually renders as an OFFSET expression in the resulting select. Backends that don’t support OFFSET will attempt to provide similar functionality.

      Changed in version 1.0.0: - can now accept arbitrary SQL expressions as well as integer values.

      • Parameters:

        offset – an integer OFFSET parameter, or a SQL expression that provides an integer result. Pass None to reset it.

      See also

      GenerativeSelect.limit()

    • method sqlalchemy.sql.expression.CompoundSelect.options(*options: ExecutableOption) → SelfExecutable

      inherited from the method of Executable

      Apply options to this statement.

      In the general sense, options are any kind of Python object that can be interpreted by the SQL compiler for the statement. These options can be consumed by specific dialects or specific kinds of compilers.

      The most commonly known kind of option are the ORM level options that apply “eager load” and other loading behaviors to an ORM query. However, options can theoretically be used for many other purposes.

      For background on specific kinds of options for specific kinds of statements, refer to the documentation for those option objects.

      Changed in version 1.4: - added to Core statement objects towards the goal of allowing unified Core / ORM querying capabilities.

      See also

      Column Loading Options - refers to options specific to the usage of ORM queries

      - refers to options specific to the usage of ORM queries

    • method sqlalchemy.sql.expression.CompoundSelect.order_by(_GenerativeSelect\_first: Union[Literal[None, _NoArg.NO_ARG], _ColumnExpressionOrStrLabelArgument[Any]] = _NoArg.NO_ARG, *clauses: _ColumnExpressionOrStrLabelArgument[Any]_) → SelfGenerativeSelect

      inherited from the method of GenerativeSelect

      Return a new selectable with the given list of ORDER BY criteria applied.

      e.g.:

      1. stmt = select(table).order_by(table.c.id, table.c.name)

      Calling this method multiple times is equivalent to calling it once with all the clauses concatenated. All existing ORDER BY criteria may be cancelled by passing None by itself. New ORDER BY criteria may then be added by invoking again, e.g.:

      1. # will erase all ORDER BY and ORDER BY new_col alone
      2. stmt = stmt.order_by(None).order_by(new_col)
      • Parameters:

        *clauses – a series of ColumnElement constructs which will be used to generate an ORDER BY clause.

      See also

      - in the SQLAlchemy Unified Tutorial

      - in the SQLAlchemy Unified Tutorial

    • method replace_selectable(old: FromClause, alias: ) → SelfSelectable

      inherited from the Selectable.replace_selectable() method of

      Replace all occurrences of FromClause ‘old’ with the given object, returning a copy of this FromClause.

      Deprecated since version 1.4: The method is deprecated, and will be removed in a future release. Similar functionality is available via the sqlalchemy.sql.visitors module.

    • method sqlalchemy.sql.expression.CompoundSelect.scalar_subquery() → [Any]

      inherited from the SelectBase.scalar_subquery() method of

      Return a ‘scalar’ representation of this selectable, which can be used as a column expression.

      The returned object is an instance of ScalarSelect.

      Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression. The scalar subquery can then be used in the WHERE clause or columns clause of an enclosing SELECT.

      Note that the scalar subquery differentiates from the FROM-level subquery that can be produced using the method.

      See also

      Scalar and Correlated Subqueries - in the 2.0 tutorial

    • method select(*arg: Any, **kw: Any) → Select

      inherited from the method of SelectBase

      Deprecated since version 1.4: The method is deprecated and will be removed in a future release; this method implicitly creates a subquery that should be explicit. Please call SelectBase.subquery() first in order to create a subquery, which then can be selected.

    • attribute selected_columns

      A ColumnCollection representing the columns that this SELECT statement or similar construct returns in its result set, not including constructs.

      For a CompoundSelect, the attribute returns the selected columns of the first SELECT statement contained within the series of statements within the set operation.

      See also

      Select.selected_columns

      New in version 1.4.

    • method self_group(against: Optional[OperatorType] = None) → GroupedElement

      Apply a ‘grouping’ to this ClauseElement.

      This method is overridden by subclasses to return a “grouping” construct, i.e. parenthesis. In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by constructs when placed into the FROM clause of another select(). (Note that subqueries should be normally created using the method, as many platforms require nested SELECT statements to be named).

      As expressions are composed together, the application of self_group() is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression like x OR (y AND z) - AND takes precedence over OR.

      The base method of ClauseElement just returns self.

    • method set_label_style(style: SelectLabelStyle) →

      Return a new selectable with the specified label style.

      There are three “label styles” available, SelectLabelStyle.LABEL_STYLE_DISAMBIGUATE_ONLY, , and SelectLabelStyle.LABEL_STYLE_NONE. The default style is .

      In modern SQLAlchemy, there is not generally a need to change the labeling style, as per-expression labels are more effectively used by making use of the ColumnElement.label() method. In past versions, LABEL_STYLE_TABLENAME_PLUS_COL was used to disambiguate same-named columns from different tables, aliases, or subqueries; the newer LABEL_STYLE_DISAMBIGUATE_ONLY now applies labels only to names that conflict with an existing name so that the impact of this labeling is minimal.

      The rationale for disambiguation is mostly so that all column expressions are available from a given collection when a subquery is created.

      New in version 1.4: - the GenerativeSelect.set_label_style() method replaces the previous combination of .apply_labels(), .with_labels() and use_labels=True methods and/or parameters.

      See also

      LABEL_STYLE_DISAMBIGUATE_ONLY

      LABEL_STYLE_TABLENAME_PLUS_COL

      LABEL_STYLE_NONE

      LABEL_STYLE_DEFAULT

    • method slice(start: int, stop: int) → SelfGenerativeSelect

      inherited from the GenerativeSelect.slice() method of

      Apply LIMIT / OFFSET to this statement based on a slice.

      The start and stop indices behave like the argument to Python’s built-in range() function. This method provides an alternative to using LIMIT/OFFSET to get a slice of the query.

      For example,

      1. stmt = select(User).order_by(User).id.slice(1, 3)

      renders as

      1. SELECT users.id AS users_id,
      2. users.name AS users_name
      3. FROM users ORDER BY users.id
      4. LIMIT ? OFFSET ?
      5. (2, 1)

      Note

      The GenerativeSelect.slice() method will replace any clause applied with .

      New in version 1.4: Added the GenerativeSelect.slice() method generalized from the ORM.

      See also

      GenerativeSelect.offset()

    • method sqlalchemy.sql.expression.CompoundSelect.subquery(name: Optional[str] = None) →

      inherited from the SelectBase.subquery() method of

      Return a subquery of this SelectBase.

      A subquery is from a SQL perspective a parenthesized, named construct that can be placed in the FROM clause of another SELECT statement.

      Given a SELECT statement such as:

      1. stmt = select(table.c.id, table.c.name)

      The above statement might look like:

      1. SELECT table.id, table.name FROM table

      The subquery form by itself renders the same way, however when embedded into the FROM clause of another SELECT statement, it becomes a named sub-element:

      1. subq = stmt.subquery()
      2. new_stmt = select(subq)

      The above renders as:

      1. SELECT anon_1.id, anon_1.name
      2. FROM (SELECT table.id, table.name FROM table) AS anon_1

      Historically, is equivalent to calling the FromClause.alias() method on a FROM object; however, as a object is not directly FROM object, the SelectBase.subquery() method provides clearer semantics.

      New in version 1.4.

    • method with_for_update(*, nowait: bool = False, read: bool = False, of: Optional[_ForUpdateOfArgument] = None, skip_locked: bool = False, key_share: bool = False) → SelfGenerativeSelect

      inherited from the GenerativeSelect.with_for_update() method of

      Specify a FOR UPDATE clause for this GenerativeSelect.

      E.g.:

      1. stmt = select(table).with_for_update(nowait=True)

      On a database like PostgreSQL or Oracle, the above would render a statement like:

      1. SELECT table.a, table.b FROM table FOR UPDATE NOWAIT

      on other backends, the nowait option is ignored and instead would produce:

      1. SELECT table.a, table.b FROM table FOR UPDATE

      When called with no arguments, the statement will render with the suffix FOR UPDATE. Additional arguments can then be provided which allow for common database-specific variants.

      • Parameters:

        • nowait – boolean; will render FOR UPDATE NOWAIT on Oracle and PostgreSQL dialects.

        • read – boolean; will render LOCK IN SHARE MODE on MySQL, FOR SHARE on PostgreSQL. On PostgreSQL, when combined with nowait, will render FOR SHARE NOWAIT.

        • of – SQL expression or list of SQL expression elements, (typically objects or a compatible expression, for some backends may also be a table expression) which will render into a FOR UPDATE OF clause; supported by PostgreSQL, Oracle, some MySQL versions and possibly others. May render as a table or as a column depending on backend.

        • skip_locked – boolean, will render FOR UPDATE SKIP LOCKED on Oracle and PostgreSQL dialects or FOR SHARE SKIP LOCKED if read=True is also specified.

        • key_share – boolean, will render FOR NO KEY UPDATE, or if combined with read=True will render FOR KEY SHARE, on the PostgreSQL dialect.

    class sqlalchemy.sql.expression.CTE

    Represent a Common Table Expression.

    The CTE object is obtained using the method from any SELECT statement. A less often available syntax also allows use of the HasCTE.cte() method present on constructs such as Insert, and Delete. See the method for usage details on CTEs.

    See also

    Subqueries and CTEs - in the 2.0 tutorial

    - examples of calling styles

    Members

    alias(), , union_all()

    Class signature

    class (sqlalchemy.sql.roles.DMLTableRole, sqlalchemy.sql.roles.IsCTERole, sqlalchemy.sql.expression.Generative, sqlalchemy.sql.expression.HasPrefixes, , sqlalchemy.sql.expression.AliasedReturnsRows)

    • method alias(name: Optional[str] = None, flat: bool = False) → CTE

      Return an of this CTE.

      This method is a CTE-specific specialization of the method.

      See also

      Using Aliases

    • method sqlalchemy.sql.expression.CTE.union(*other: _SelectStatementForCompoundArgument) →

      Return a new CTE with a SQL UNION of the original CTE against the given selectables provided as positional arguments.

      • Parameters:

        *other

        one or more elements with which to create a UNION.

        Changed in version 1.4.28: multiple elements are now accepted.

      See also

      - examples of calling styles

    • method sqlalchemy.sql.expression.CTE.union_all(*other: _SelectStatementForCompoundArgument) →

      Return a new CTE with a SQL UNION ALL of the original CTE against the given selectables provided as positional arguments.

      • Parameters:

        *other

        one or more elements with which to create a UNION.

        Changed in version 1.4.28: multiple elements are now accepted.

      See also

      - examples of calling styles

    class sqlalchemy.sql.expression.Executable

    Mark a ClauseElement as supporting execution.

    is a superclass for all “statement” types of objects, including select(), , update(), , text().

    Members

    , get_execution_options(),

    Class signature

    class sqlalchemy.sql.expression.Executable (sqlalchemy.sql.roles.StatementRole)

    • method execution_options(**kw: Any) → SelfExecutable

      Set non-SQL options for the statement which take effect during execution.

      Execution options can be set at many scopes, including per-statement, per-connection, or per execution, using methods such as Connection.execution_options() and parameters which accept a dictionary of options such as and Session.execute.execution_options.

      The primary characteristic of an execution option, as opposed to other kinds of options such as ORM loader options, is that execution options never affect the compiled SQL of a query, only things that affect how the SQL statement itself is invoked or how results are fetched. That is, execution options are not part of what’s accommodated by SQL compilation nor are they considered part of the cached state of a statement.

      The method is generative, as is the case for the method as applied to the and Query objects, which means when the method is called, a copy of the object is returned, which applies the given parameters to that new copy, but leaves the original unchanged:

      1. statement = select(table.c.x, table.c.y)
      2. new_statement = statement.execution_options(my_option=True)

      An exception to this behavior is the object, where the Connection.execution_options() method is explicitly not generative.

      The kinds of options that may be passed to and other related methods and parameter dictionaries include parameters that are explicitly consumed by SQLAlchemy Core or ORM, as well as arbitrary keyword arguments not defined by SQLAlchemy, which means the methods and/or parameter dictionaries may be used for user-defined parameters that interact with custom code, which may access the parameters using methods such as Executable.get_execution_options() and , or within selected event hooks using a dedicated execution_options event parameter such as ConnectionEvents.before_execute.execution_options or , e.g.:

      1. from sqlalchemy import event
      2. @event.listens_for(some_engine, "before_execute")
      3. def _process_opt(conn, statement, multiparams, params, execution_options):
      4. "run a SQL function before invoking a statement"
      5. if execution_options.get("do_special_thing", False):
      6. conn.exec_driver_sql("run_special_function()")

      Within the scope of options that are explicitly recognized by SQLAlchemy, most apply to specific classes of objects and not others. The most common execution options include:

      See also

      Connection.execution_options()

      Session.execute.execution_options

      - documentation on all ORM-specific execution options

    • method sqlalchemy.sql.expression.Executable.get_execution_options() → _ExecuteOptions

      Get the non-SQL options which will take effect during execution.

      New in version 1.3.

      See also

    • method sqlalchemy.sql.expression.Executable.options(*options: ExecutableOption) → SelfExecutable

      Apply options to this statement.

      In the general sense, options are any kind of Python object that can be interpreted by the SQL compiler for the statement. These options can be consumed by specific dialects or specific kinds of compilers.

      The most commonly known kind of option are the ORM level options that apply “eager load” and other loading behaviors to an ORM query. However, options can theoretically be used for many other purposes.

      For background on specific kinds of options for specific kinds of statements, refer to the documentation for those option objects.

      Changed in version 1.4: - added to Core statement objects towards the goal of allowing unified Core / ORM querying capabilities.

      See also

      Column Loading Options - refers to options specific to the usage of ORM queries

      - refers to options specific to the usage of ORM queries

    class sqlalchemy.sql.expression.Exists

    Represent an EXISTS clause.

    See exists() for a description of usage.

    An EXISTS clause can also be constructed from a instance by calling SelectBase.exists().

    Members

    , correlate_except(), , select(), , where()

    Class signature

    class (sqlalchemy.sql.expression.UnaryExpression)

    • method correlate(*fromclauses: Union[Literal[None, False], _FromClauseArgument]) → SelfExists

      Apply correlation to the subquery noted by this Exists.

      See also

    • method sqlalchemy.sql.expression.Exists.correlate_except(*fromclauses: Union[Literal[None, False], _FromClauseArgument]) → SelfExists

      Apply correlation to the subquery noted by this .

      See also

      ScalarSelect.correlate_except()

    • attribute inherit_cache: Optional[bool] = True

      Indicate if this HasCacheKey instance should make use of the cache key generation scheme used by its immediate superclass.

      The attribute defaults to None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value to False, except that a warning is also emitted.

      This flag can be set to True on a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.

      See also

      - General guideslines for setting the HasCacheKey.inherit_cache attribute for third-party or user defined SQL constructs.

    • method select() → Select

      Return a SELECT of this .

      e.g.:

      1. stmt = exists(some_table.c.id).where(some_table.c.id == 5).select()

      This will produce a statement resembling:

      1. SELECT EXISTS (SELECT id FROM some_table WHERE some_table = :param) AS anon_1

      See also

      select() - general purpose method which allows for arbitrary column lists.

    • method select_from(*froms: FromClause) → SelfExists

      Return a new construct, applying the given expression to the Select.select_from() method of the select statement contained.

      Note

      it is typically preferable to build a statement first, including the desired WHERE clause, then use the SelectBase.exists() method to produce an object at once.

    • method sqlalchemy.sql.expression.Exists.where(*clause: _ColumnExpressionArgument[bool]) → SelfExists

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

      Note

      it is typically preferable to build a Select statement first, including the desired WHERE clause, then use the method to produce an Exists object at once.

    class sqlalchemy.sql.expression.FromClause

    Represent an element that can be used within the FROM clause of a SELECT statement.

    The most common forms of are the Table and the constructs. Key features common to all FromClause objects include:

    • a collection, which provides per-name access to a collection of ColumnElement objects.

    • a attribute, which is a collection of all those ColumnElement objects that indicate the primary_key flag.

    • Methods to generate various derivations of a “from” clause, including , FromClause.join(), .

    Members

    alias(), , columns, , entity_namespace, , foreign_keys, , join(), , primary_key, , select(),

    Class signature

    class sqlalchemy.sql.expression.FromClause (sqlalchemy.sql.roles.AnonymizedFromClauseRole, )

    • method sqlalchemy.sql.expression.FromClause.alias(name: Optional[str] = None, flat: bool = False) → NamedFromClause

      Return an alias of this .

      E.g.:

      1. a2 = some_table.alias('a2')

      The above code creates an Alias object which can be used as a FROM clause in any SELECT statement.

      See also

      alias()

    • attribute c

      A synonym for FromClause.columns

      • Returns:

        a

    • attribute sqlalchemy.sql.expression.FromClause.columns

      A named-based collection of objects maintained by this FromClause.

      The , or c collection, is the gateway to the construction of SQL expressions using table-bound or other selectable-bound columns:

      1. select(mytable).where(mytable.c.somecolumn == 5)
      • Returns:

        a object.

    • attribute sqlalchemy.sql.expression.FromClause.description

      A brief description of this .

      Used primarily for error message formatting.

    • attribute sqlalchemy.sql.expression.FromClause.entity_namespace

      Return a namespace used for name-based access in SQL expressions.

      This is the namespace that is used to resolve “filter_by()” type expressions, such as:

      1. stmt.filter_by(address='some address')

      It defaults to the .c collection, however internally it can be overridden using the “entity_namespace” annotation to deliver alternative results.

    • attribute exported_columns

      A ColumnCollection that represents the “exported” columns of this .

      The “exported” columns for a FromClause object are synonymous with the collection.

      New in version 1.4.

      See also

      Selectable.exported_columns

    • attribute sqlalchemy.sql.expression.FromClause.foreign_keys

      Return the collection of marker objects which this FromClause references.

      Each ForeignKey is a member of a -wide ForeignKeyConstraint.

      See also

    • method sqlalchemy.sql.expression.FromClause.is_derived_from(fromclause: Optional[]) → bool

      Return True if this FromClause is ‘derived’ from the given FromClause.

      An example would be an Alias of a Table is derived from that Table.

    • method join(right: _FromClauseArgument, onclause: Optional[_ColumnExpressionArgument[bool]] = None, isouter: bool = False, full: bool = False) → Join

      Return a from this FromClause to another .

      E.g.:

      1. from sqlalchemy import join
      2. j = user_table.join(address_table,
      3. user_table.c.id == address_table.c.user_id)
      4. stmt = select(user_table).select_from(j)

      would emit SQL along the lines of:

      1. SELECT user.id, user.name FROM user
      2. JOIN address ON user.id = address.user_id
      • Parameters:

        • right – the right side of the join; this is any FromClause object such as a object, and may also be a selectable-compatible object such as an ORM-mapped class.

        • onclause – a SQL expression representing the ON clause of the join. If left at None, FromClause.join() will attempt to join the two tables based on a foreign key relationship.

        • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.

        • full

          if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. Implies .

          New in version 1.1.

    1. See also
    2. [join()](#sqlalchemy.sql.expression.join "sqlalchemy.sql.expression.join") - standalone function
    3. [Join](#sqlalchemy.sql.expression.Join "sqlalchemy.sql.expression.Join") - the type of object produced
    • method sqlalchemy.sql.expression.FromClause.outerjoin(right: _FromClauseArgument, onclause: Optional[_ColumnExpressionArgument[bool]] = None, full: bool = False) →

      Return a Join from this to another FromClause, with the “isouter” flag set to True.

      E.g.:

      1. from sqlalchemy import outerjoin
      2. j = user_table.outerjoin(address_table,
      3. user_table.c.id == address_table.c.user_id)

      The above is equivalent to:

      1. j = user_table.join(
      2. address_table,
      3. user_table.c.id == address_table.c.user_id,
      4. isouter=True)
      • Parameters:

        • right – the right side of the join; this is any object such as a Table object, and may also be a selectable-compatible object such as an ORM-mapped class.

        • onclause – a SQL expression representing the ON clause of the join. If left at None, will attempt to join the two tables based on a foreign key relationship.

        • full

          if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN.

          New in version 1.1.

    1. See also
    2. [FromClause.join()](#sqlalchemy.sql.expression.FromClause.join "sqlalchemy.sql.expression.FromClause.join")
    3. [Join](#sqlalchemy.sql.expression.Join "sqlalchemy.sql.expression.Join")
    • attribute sqlalchemy.sql.expression.FromClause.primary_key

      Return the iterable collection of objects which comprise the primary key of this _selectable.FromClause.

      For a Table object, this collection is represented by the which itself is an iterable collection of Column objects.

    • attribute schema: Optional[str] = None

      Define the ‘schema’ attribute for this FromClause.

      This is typically None for most objects except that of , where it is taken as the value of the Table.schema argument.

    • method select() → Select

      Return a SELECT of this .

      e.g.:

      1. stmt = some_table.select().where(some_table.c.id == 5)

      See also

      select() - general purpose method which allows for arbitrary column lists.

    • method tablesample(sampling: Union[float, Function[Any]], name: Optional[str] = None, seed: Optional[roles.ExpressionElementRole[Any]] = None) →

      Return a TABLESAMPLE alias of this FromClause.

      The return value is the construct also provided by the top-level tablesample() function.

      New in version 1.1.

      See also

      - usage guidelines and parameters

    class sqlalchemy.sql.expression.GenerativeSelect

    Base class for SELECT statements where additional elements can be added.

    This serves as the base for Select and where elements such as ORDER BY, GROUP BY can be added and column rendering can be controlled. Compare to TextualSelect, which, while it subclasses and is also a SELECT construct, represents a fixed textual string which cannot be altered at this level, only wrapped as a subquery.

    Members

    fetch(), , group_by(), , offset(), , set_label_style(), , with_for_update()

    Class signature

    class (sqlalchemy.sql.expression.SelectBase, sqlalchemy.sql.expression.Generative)

    • method fetch(count: Union[int, _ColumnExpressionArgument[int]], with_ties: bool = False, percent: bool = False) → SelfGenerativeSelect

      Return a new selectable with the given FETCH FIRST criterion applied.

      This is a numeric value which usually renders as FETCH {FIRST | NEXT} [ count ] {ROW | ROWS} {ONLY | WITH TIES} expression in the resulting select. This functionality is is currently implemented for Oracle, PostgreSQL, MSSQL.

      Use GenerativeSelect.offset() to specify the offset.

      Note

      The method will replace any clause applied with GenerativeSelect.limit().

      New in version 1.4.

      • Parameters:

        • count – an integer COUNT parameter, or a SQL expression that provides an integer result. When percent=True this will represent the percentage of rows to return, not the absolute value. Pass None to reset it.

        • with_ties – When True, the WITH TIES option is used to return any additional rows that tie for the last place in the result set according to the ORDER BY clause. The ORDER BY may be mandatory in this case. Defaults to False

    1. See also
    2. [GenerativeSelect.limit()](#sqlalchemy.sql.expression.GenerativeSelect.limit "sqlalchemy.sql.expression.GenerativeSelect.limit")
    3. [GenerativeSelect.offset()](#sqlalchemy.sql.expression.GenerativeSelect.offset "sqlalchemy.sql.expression.GenerativeSelect.offset")
    • method get_label_style() → SelectLabelStyle

      Retrieve the current label style.

      New in version 1.4.

    • method group_by(_GenerativeSelect\_first: Union[Literal[None, _NoArg.NO_ARG], _ColumnExpressionOrStrLabelArgument[Any]] = _NoArg.NO_ARG, *clauses: _ColumnExpressionOrStrLabelArgument[Any]_) → SelfGenerativeSelect

      Return a new selectable with the given list of GROUP BY criterion applied.

      All existing GROUP BY settings can be suppressed by passing None.

      e.g.:

      1. stmt = select(table.c.name, func.max(table.c.stat)).\
      2. group_by(table.c.name)
      • Parameters:

        *clauses – a series of ColumnElement constructs which will be used to generate an GROUP BY clause.

      See also

      - in the SQLAlchemy Unified Tutorial

      - in the SQLAlchemy Unified Tutorial

    • method limit(limit: Union[int, _ColumnExpressionArgument[int]]) → SelfGenerativeSelect

      Return a new selectable with the given LIMIT criterion applied.

      This is a numerical value which usually renders as a LIMIT expression in the resulting select. Backends that don’t support LIMIT will attempt to provide similar functionality.

      Note

      The GenerativeSelect.limit() method will replace any clause applied with .

      Changed in version 1.0.0: - Select.limit() can now accept arbitrary SQL expressions as well as integer values.

      • Parameters:

        limit – an integer LIMIT parameter, or a SQL expression that provides an integer result. Pass None to reset it.

      See also

      GenerativeSelect.offset()

    • method offset(offset: Union[int, _ColumnExpressionArgument[int]]) → SelfGenerativeSelect

      Return a new selectable with the given OFFSET criterion applied.

      This is a numeric value which usually renders as an OFFSET expression in the resulting select. Backends that don’t support OFFSET will attempt to provide similar functionality.

      Changed in version 1.0.0: - Select.offset() can now accept arbitrary SQL expressions as well as integer values.

      • Parameters:

        offset – an integer OFFSET parameter, or a SQL expression that provides an integer result. Pass None to reset it.

      See also

      GenerativeSelect.fetch()

    • method order_by(_GenerativeSelect\_first: Union[Literal[None, _NoArg.NO_ARG], _ColumnExpressionOrStrLabelArgument[Any]] = _NoArg.NO_ARG, *clauses: _ColumnExpressionOrStrLabelArgument[Any]_) → SelfGenerativeSelect

      Return a new selectable with the given list of ORDER BY criteria applied.

      e.g.:

      1. stmt = select(table).order_by(table.c.id, table.c.name)

      Calling this method multiple times is equivalent to calling it once with all the clauses concatenated. All existing ORDER BY criteria may be cancelled by passing None by itself. New ORDER BY criteria may then be added by invoking Query.order_by() again, e.g.:

      1. # will erase all ORDER BY and ORDER BY new_col alone
      2. stmt = stmt.order_by(None).order_by(new_col)
      • Parameters:

        *clauses – a series of constructs which will be used to generate an ORDER BY clause.

      See also

      ORDER BY - in the

      Ordering or Grouping by a Label - in the

    • method sqlalchemy.sql.expression.GenerativeSelect.set_label_style(style: ) → SelfGenerativeSelect

      Return a new selectable with the specified label style.

      There are three “label styles” available, SelectLabelStyle.LABEL_STYLE_DISAMBIGUATE_ONLY, , and SelectLabelStyle.LABEL_STYLE_NONE. The default style is .

      In modern SQLAlchemy, there is not generally a need to change the labeling style, as per-expression labels are more effectively used by making use of the ColumnElement.label() method. In past versions, LABEL_STYLE_TABLENAME_PLUS_COL was used to disambiguate same-named columns from different tables, aliases, or subqueries; the newer LABEL_STYLE_DISAMBIGUATE_ONLY now applies labels only to names that conflict with an existing name so that the impact of this labeling is minimal.

      The rationale for disambiguation is mostly so that all column expressions are available from a given collection when a subquery is created.

      New in version 1.4: - the GenerativeSelect.set_label_style() method replaces the previous combination of .apply_labels(), .with_labels() and use_labels=True methods and/or parameters.

      See also

      LABEL_STYLE_DISAMBIGUATE_ONLY

      LABEL_STYLE_TABLENAME_PLUS_COL

      LABEL_STYLE_NONE

      LABEL_STYLE_DEFAULT

    • method slice(start: int, stop: int) → SelfGenerativeSelect

      Apply LIMIT / OFFSET to this statement based on a slice.

      The start and stop indices behave like the argument to Python’s built-in range() function. This method provides an alternative to using LIMIT/OFFSET to get a slice of the query.

      For example,

      1. stmt = select(User).order_by(User).id.slice(1, 3)

      renders as

      1. SELECT users.id AS users_id,
      2. users.name AS users_name
      3. FROM users ORDER BY users.id
      4. LIMIT ? OFFSET ?
      5. (2, 1)

      Note

      The GenerativeSelect.slice() method will replace any clause applied with .

      New in version 1.4: Added the GenerativeSelect.slice() method generalized from the ORM.

      See also

      GenerativeSelect.offset()

    • method sqlalchemy.sql.expression.GenerativeSelect.with_for_update(*, nowait: bool = False, read: bool = False, of: Optional[_ForUpdateOfArgument] = None, skip_locked: bool = False, key_share: bool = False) → SelfGenerativeSelect

      Specify a FOR UPDATE clause for this .

      E.g.:

      1. stmt = select(table).with_for_update(nowait=True)

      On a database like PostgreSQL or Oracle, the above would render a statement like:

      1. SELECT table.a, table.b FROM table FOR UPDATE NOWAIT

      on other backends, the nowait option is ignored and instead would produce:

      When called with no arguments, the statement will render with the suffix FOR UPDATE. Additional arguments can then be provided which allow for common database-specific variants.

      • Parameters:

        • nowait – boolean; will render FOR UPDATE NOWAIT on Oracle and PostgreSQL dialects.

        • read – boolean; will render LOCK IN SHARE MODE on MySQL, FOR SHARE on PostgreSQL. On PostgreSQL, when combined with nowait, will render FOR SHARE NOWAIT.

        • of – SQL expression or list of SQL expression elements, (typically Column objects or a compatible expression, for some backends may also be a table expression) which will render into a FOR UPDATE OF clause; supported by PostgreSQL, Oracle, some MySQL versions and possibly others. May render as a table or as a column depending on backend.

        • skip_locked – boolean, will render FOR UPDATE SKIP LOCKED on Oracle and PostgreSQL dialects or FOR SHARE SKIP LOCKED if read=True is also specified.

        • key_share – boolean, will render FOR NO KEY UPDATE, or if combined with read=True will render FOR KEY SHARE, on the PostgreSQL dialect.

    class sqlalchemy.sql.expression.HasCTE

    Mixin that declares a class to include CTE support.

    New in version 1.1.

    Members

    , cte()

    Class signature

    class (sqlalchemy.sql.roles.HasCTERole, sqlalchemy.sql.expression.SelectsRows)

    • method sqlalchemy.sql.expression.HasCTE.add_cte(*ctes: , nest_here: bool = False) → SelfHasCTE

      Add one or more CTE constructs to this statement.

      This method will associate the given constructs with the parent statement such that they will each be unconditionally rendered in the WITH clause of the final statement, even if not referenced elsewhere within the statement or any sub-selects.

      The optional HasCTE.add_cte.nest_here parameter when set to True will have the effect that each given will render in a WITH clause rendered directly along with this statement, rather than being moved to the top of the ultimate rendered statement, even if this statement is rendered as a subquery within a larger statement.

      This method has two general uses. One is to embed CTE statements that serve some purpose without being referenced explicitly, such as the use case of embedding a DML statement such as an INSERT or UPDATE as a CTE inline with a primary statement that may draw from its results indirectly. The other is to provide control over the exact placement of a particular series of CTE constructs that should remain rendered directly in terms of a particular statement that may be nested in a larger statement.

      E.g.:

      1. from sqlalchemy import table, column, select
      2. t = table('t', column('c1'), column('c2'))
      3. ins = t.insert().values({"c1": "x", "c2": "y"}).cte()
      4. stmt = select(t).add_cte(ins)

      Would render:

      1. WITH anon_1 AS
      2. (INSERT INTO t (c1, c2) VALUES (:param_1, :param_2))
      3. SELECT t.c1, t.c2
      4. FROM t

      Above, the “anon_1” CTE is not referred towards in the SELECT statement, however still accomplishes the task of running an INSERT statement.

      Similarly in a DML-related context, using the PostgreSQL Insert construct to generate an “upsert”:

      1. from sqlalchemy import table, column
      2. from sqlalchemy.dialects.postgresql import insert
      3. t = table("t", column("c1"), column("c2"))
      4. delete_statement_cte = (
      5. t.delete().where(t.c.c1 < 1).cte("deletions")
      6. )
      7. insert_stmt = insert(t).values({"c1": 1, "c2": 2})
      8. update_statement = insert_stmt.on_conflict_do_update(
      9. index_elements=[t.c.c1],
      10. set_={
      11. "c1": insert_stmt.excluded.c1,
      12. "c2": insert_stmt.excluded.c2,
      13. },
      14. ).add_cte(delete_statement_cte)
      15. print(update_statement)

      The above statement renders as:

      1. WITH deletions AS
      2. (DELETE FROM t WHERE t.c1 < %(c1_1)s)
      3. INSERT INTO t (c1, c2) VALUES (%(c1)s, %(c2)s)
      4. ON CONFLICT (c1) DO UPDATE SET c1 = excluded.c1, c2 = excluded.c2

      New in version 1.4.21.

      • Parameters:

        • *ctes

          zero or more constructs.

          Changed in version 2.0: Multiple CTE instances are accepted

        • nest_here

          if True, the given CTE or CTEs will be rendered as though they specified the HasCTE.cte.nesting flag to True when they were added to this . Assuming the given CTEs are not referenced in an outer-enclosing statement as well, the CTEs given should render at the level of this statement when this flag is given.

          New in version 2.0.

          See also

          HasCTE.cte.nesting

    • method cte(name: Optional[str] = None, recursive: bool = False, nesting: bool = False) → CTE

      Return a new , or Common Table Expression instance.

      Common table expressions are a SQL standard whereby SELECT statements can draw upon secondary statements specified along with the primary statement, using a clause called “WITH”. Special semantics regarding UNION can also be employed to allow “recursive” queries, where a SELECT statement can draw upon the set of rows that have previously been selected.

      CTEs can also be applied to DML constructs UPDATE, INSERT and DELETE on some databases, both as a source of CTE rows when combined with RETURNING, as well as a consumer of CTE rows.

      Changed in version 1.1: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.

      SQLAlchemy detects CTE objects, which are treated similarly to objects, as special elements to be delivered to the FROM clause of the statement as well as to a WITH clause at the top of the statement.

      For special prefixes such as PostgreSQL “MATERIALIZED” and “NOT MATERIALIZED”, the CTE.prefix_with() method may be used to establish these.

      Changed in version 1.3.13: Added support for prefixes. In particular - MATERIALIZED and NOT MATERIALIZED.

      • Parameters:

        • name – name given to the common table expression. Like FromClause.alias(), the name can be left as None in which case an anonymous symbol will be used at query compile time.

        • recursive – if True, will render WITH RECURSIVE. A recursive common table expression is intended to be used in conjunction with UNION ALL in order to derive rows from those already selected.

        • nesting

          if True, will render the CTE locally to the statement in which it is referenced. For more complex scenarios, the method using the HasCTE.add_cte.nest_here parameter may also be used to more carefully control the exact placement of a particular CTE.

          New in version 1.4.24.

          See also

    1. The following examples include two from PostgreSQLs documentation at [https://www.postgresql.org/docs/current/static/queries-with.html](https://www.postgresql.org/docs/current/static/queries-with.html), as well as additional examples.
    2. Example 1, non recursive:
    3. ```
    4. from sqlalchemy import (Table, Column, String, Integer,
    5. MetaData, select, func)
    6. metadata = MetaData()
    7. orders = Table('orders', metadata,
    8. Column('region', String),
    9. Column('amount', Integer),
    10. Column('product', String),
    11. Column('quantity', Integer)
    12. )
    13. regional_sales = select(
    14. orders.c.region,
    15. func.sum(orders.c.amount).label('total_sales')
    16. ).group_by(orders.c.region).cte("regional_sales")
    17. top_regions = select(regional_sales.c.region).\
    18. where(
    19. regional_sales.c.total_sales >
    20. select(
    21. func.sum(regional_sales.c.total_sales) / 10
    22. )
    23. ).cte("top_regions")
    24. statement = select(
    25. orders.c.region,
    26. orders.c.product,
    27. func.sum(orders.c.quantity).label("product_units"),
    28. func.sum(orders.c.amount).label("product_sales")
    29. ).where(orders.c.region.in_(
    30. select(top_regions.c.region)
    31. )).group_by(orders.c.region, orders.c.product)
    32. result = conn.execute(statement).fetchall()
    33. ```
    34. Example 2, WITH RECURSIVE:
    35. ```
    36. from sqlalchemy import (Table, Column, String, Integer,
    37. MetaData, select, func)
    38. metadata = MetaData()
    39. parts = Table('parts', metadata,
    40. Column('part', String),
    41. Column('sub_part', String),
    42. Column('quantity', Integer),
    43. )
    44. included_parts = select(\
    45. parts.c.sub_part, parts.c.part, parts.c.quantity\
    46. ).\
    47. where(parts.c.part=='our part').\
    48. cte(recursive=True)
    49. incl_alias = included_parts.alias()
    50. parts_alias = parts.alias()
    51. included_parts = included_parts.union_all(
    52. select(
    53. parts_alias.c.sub_part,
    54. parts_alias.c.part,
    55. parts_alias.c.quantity
    56. ).\
    57. where(parts_alias.c.part==incl_alias.c.sub_part)
    58. )
    59. statement = select(
    60. included_parts.c.sub_part,
    61. func.sum(included_parts.c.quantity).
    62. label('total_quantity')
    63. ).\
    64. group_by(included_parts.c.sub_part)
    65. result = conn.execute(statement).fetchall()
    66. ```
    67. Example 3, an upsert using UPDATE and INSERT with CTEs:
    68. ```
    69. from datetime import date
    70. from sqlalchemy import (MetaData, Table, Column, Integer,
    71. Date, select, literal, and_, exists)
    72. metadata = MetaData()
    73. visitors = Table('visitors', metadata,
    74. Column('product_id', Integer, primary_key=True),
    75. Column('date', Date, primary_key=True),
    76. )
    77. # add 5 visitors for the product_id == 1
    78. product_id = 1
    79. day = date.today()
    80. count = 5
    81. update_cte = (
    82. visitors.update()
    83. .where(and_(visitors.c.product_id == product_id,
    84. visitors.c.date == day))
    85. .values(count=visitors.c.count + count)
    86. .returning(literal(1))
    87. .cte('update_cte')
    88. )
    89. upsert = visitors.insert().from_select(
    90. [visitors.c.product_id, visitors.c.date, visitors.c.count],
    91. select(literal(product_id), literal(day), literal(count))
    92. .where(~exists(update_cte.select()))
    93. )
    94. connection.execute(upsert)
    95. ```
    96. Example 4, Nesting CTE (SQLAlchemy 1.4.24 and above):
    97. ```
    98. value_a = select(
    99. literal("root").label("n")
    100. ).cte("value_a")
    101. # A nested CTE with the same name as the root one
    102. value_a_nested = select(
    103. literal("nesting").label("n")
    104. ).cte("value_a", nesting=True)
    105. # Nesting CTEs takes ascendency locally
    106. # over the CTEs at a higher level
    107. value_b = select(value_a_nested.c.n).cte("value_b")
    108. value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
    109. ```
    110. The above query will render the second CTE nested inside the first, shown with inline parameters below as:
    111. ```
    112. WITH
    113. value_a AS
    114. (SELECT 'root' AS n),
    115. value_b AS
    116. (WITH value_a AS
    117. (SELECT 'nesting' AS n)
    118. SELECT value_a.n AS n FROM value_a)
    119. SELECT value_a.n AS a, value_b.n AS b
    120. FROM value_a, value_b
    121. ```
    122. The same CTE can be set up using the [HasCTE.add\_cte()](#sqlalchemy.sql.expression.HasCTE.add_cte "sqlalchemy.sql.expression.HasCTE.add_cte") method as follows (SQLAlchemy 2.0 and above):
    123. ```
    124. value_a = select(
    125. literal("root").label("n")
    126. ).cte("value_a")
    127. # A nested CTE with the same name as the root one
    128. value_a_nested = select(
    129. literal("nesting").label("n")
    130. ).cte("value_a")
    131. # Nesting CTEs takes ascendency locally
    132. # over the CTEs at a higher level
    133. value_b = (
    134. select(value_a_nested.c.n).
    135. add_cte(value_a_nested, nest_here=True).
    136. cte("value_b")
    137. )
    138. value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
    139. ```
    140. Example 5, Non-Linear CTE (SQLAlchemy 1.4.28 and above):
    141. ```
    142. edge = Table(
    143. "edge",
    144. metadata,
    145. Column("id", Integer, primary_key=True),
    146. Column("left", Integer),
    147. Column("right", Integer),
    148. )
    149. root_node = select(literal(1).label("node")).cte(
    150. "nodes", recursive=True
    151. )
    152. left_edge = select(edge.c.left).join(
    153. root_node, edge.c.right == root_node.c.node
    154. )
    155. right_edge = select(edge.c.right).join(
    156. root_node, edge.c.left == root_node.c.node
    157. )
    158. subgraph_cte = root_node.union(left_edge, right_edge)
    159. subgraph = select(subgraph_cte)
    160. ```
    161. The above query will render 2 UNIONs inside the recursive CTE:
    162. ```
    163. WITH RECURSIVE nodes(node) AS (
    164. SELECT 1 AS node
    165. UNION
    166. SELECT edge."left" AS "left"
    167. FROM edge JOIN nodes ON edge."right" = nodes.node
    168. UNION
    169. SELECT edge."right" AS "right"
    170. FROM edge JOIN nodes ON edge."left" = nodes.node
    171. )
    172. SELECT nodes.node FROM nodes
    173. ```
    174. See also
    175. [Query.cte()]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query.cte "sqlalchemy.orm.Query.cte") - ORM version of [HasCTE.cte()](#sqlalchemy.sql.expression.HasCTE.cte "sqlalchemy.sql.expression.HasCTE.cte").

    class sqlalchemy.sql.expression.HasPrefixes

    Members

    prefix_with()

    • method prefix_with(*prefixes: _TextCoercedExpressionArgument[Any], dialect: str = ‘*‘) → SelfHasPrefixes

      Add one or more expressions following the statement keyword, i.e. SELECT, INSERT, UPDATE, or DELETE. Generative.

      This is used to support backend-specific prefix keywords such as those provided by MySQL.

      E.g.:

      1. stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")
      2. # MySQL 5.7 optimizer hints
      3. stmt = select(table).prefix_with(
      4. "/*+ BKA(t1) */", dialect="mysql")

      Multiple prefixes can be specified by multiple calls to HasPrefixes.prefix_with().

      • Parameters:

        • *prefixes – textual or construct which will be rendered following the INSERT, UPDATE, or DELETE keyword.

        • dialect – optional string dialect name which will limit rendering of this prefix to only that dialect.

    class sqlalchemy.sql.expression.HasSuffixes

    Members

    suffix_with()

    • method suffix_with(*suffixes: _TextCoercedExpressionArgument[Any], dialect: str = ‘*‘) → SelfHasSuffixes

      Add one or more expressions following the statement as a whole.

      This is used to support backend-specific suffix keywords on certain constructs.

      E.g.:

      1. stmt = select(col1, col2).cte().suffix_with(
      2. "cycle empno set y_cycle to 1 default 0", dialect="oracle")

      Multiple suffixes can be specified by multiple calls to HasSuffixes.suffix_with().

      • Parameters:

        • *suffixes – textual or construct which will be rendered following the target clause.

        • dialect – Optional string dialect name which will limit rendering of this suffix to only that dialect.

    class sqlalchemy.sql.expression.Join

    Represent a JOIN construct between two FromClause elements.

    The public constructor function for is the module-level join() function, as well as the method of any FromClause (e.g. such as ).

    See also

    join()

    Members

    __init__(), , is_derived_from(), , self_group()

    Class signature

    class (sqlalchemy.sql.roles.DMLTableRole, sqlalchemy.sql.expression.FromClause)

    • method __init__(left: _FromClauseArgument, right: _FromClauseArgument, onclause: Optional[_OnClauseArgument] = None, isouter: bool = False, full: bool = False)

      Construct a new Join.

      The usual entrypoint here is the function or the FromClause.join() method of any object.

    • attribute sqlalchemy.sql.expression.Join.description

    • method is_derived_from(fromclause: Optional[FromClause]) → bool

      Return True if this is ‘derived’ from the given FromClause.

      An example would be an Alias of a Table is derived from that Table.

    • method sqlalchemy.sql.expression.Join.select() →

      Create a Select from this .

      E.g.:

      1. stmt = table_a.join(table_b, table_a.c.id == table_b.c.a_id)
      2. stmt = stmt.select()

      The above will produce a SQL string resembling:

      1. SELECT table_a.id, table_a.col, table_b.id, table_b.a_id
      2. FROM table_a JOIN table_b ON table_a.id = table_b.a_id
    • method sqlalchemy.sql.expression.Join.self_group(against: Optional[OperatorType] = None) → FromGrouping

      Apply a ‘grouping’ to this .

      This method is overridden by subclasses to return a “grouping” construct, i.e. parenthesis. In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by select() constructs when placed into the FROM clause of another . (Note that subqueries should be normally created using the Select.alias() method, as many platforms require nested SELECT statements to be named).

      As expressions are composed together, the application of is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression like x OR (y AND z) - AND takes precedence over OR.

      The base self_group() method of just returns self.

    class sqlalchemy.sql.expression.Lateral

    Represent a LATERAL subquery.

    This object is constructed from the lateral() module level function as well as the FromClause.lateral() method available on all subclasses.

    While LATERAL is part of the SQL standard, currently only more recent PostgreSQL versions provide support for this keyword.

    New in version 1.1.

    See also

    LATERAL correlation - overview of usage.

    Members

    Class signature

    class sqlalchemy.sql.expression.Lateral (sqlalchemy.sql.expression.FromClauseAlias, sqlalchemy.sql.expression.LateralFromClause)

    • attribute inherit_cache: Optional[bool] = True

      Indicate if this HasCacheKey instance should make use of the cache key generation scheme used by its immediate superclass.

      The attribute defaults to None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value to False, except that a warning is also emitted.

      This flag can be set to True on a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.

      See also

      - General guideslines for setting the HasCacheKey.inherit_cache attribute for third-party or user defined SQL constructs.

    class sqlalchemy.sql.expression.ReturnsRows

    The base-most class for Core constructs that have some concept of columns that can represent rows.

    While the SELECT statement and TABLE are the primary things we think of in this category, DML like INSERT, UPDATE and DELETE can also specify RETURNING which means they can be used in CTEs and other forms, and PostgreSQL has functions that return rows also.

    New in version 1.4.

    Members

    , is_derived_from()

    Class signature

    class (sqlalchemy.sql.roles.ReturnsRowsRole, sqlalchemy.sql.expression.DQLDMLClauseElement)

    • attribute sqlalchemy.sql.expression.ReturnsRows.exported_columns

      A that represents the “exported” columns of this ReturnsRows.

      The “exported” columns represent the collection of expressions that are rendered by this SQL construct. There are primary varieties which are the “FROM clause columns” of a FROM clause, such as a table, join, or subquery, the “SELECTed columns”, which are the columns in the “columns clause” of a SELECT statement, and the RETURNING columns in a DML statement..

      New in version 1.4.

      See also

      FromClause.exported_columns

    • method sqlalchemy.sql.expression.ReturnsRows.is_derived_from(fromclause: Optional[]) → bool

      Return True if this ReturnsRows is ‘derived’ from the given .

      An example would be an Alias of a Table is derived from that Table.

    class sqlalchemy.sql.expression.ScalarSelect

    Represent a scalar subquery.

    A ScalarSelect is created by invoking the method. The object then participates in other SQL expressions as a SQL column expression within the ColumnElement hierarchy.

    See also

    Scalar and Correlated Subqueries - in the 2.0 tutorial

    Members

    , correlate_except(), , self_group(),

    Class signature

    class sqlalchemy.sql.expression.ScalarSelect (sqlalchemy.sql.roles.InElementRole, sqlalchemy.sql.expression.Generative, sqlalchemy.sql.expression.GroupedElement, )

    • method sqlalchemy.sql.expression.ScalarSelect.correlate(*fromclauses: Union[Literal[None, False], _FromClauseArgument]) → SelfScalarSelect

      Return a new which will correlate the given FROM clauses to that of an enclosing Select.

      This method is mirrored from the method of the underlying Select. The method applies the :meth:_sql.Select.correlate` method, then returns a new against that statement.

      New in version 1.4: Previously, the ScalarSelect.correlate() method was only available from .

      • Parameters:

        *fromclauses – a list of one or more FromClause constructs, or other compatible constructs (i.e. ORM-mapped classes) to become part of the correlate collection.

      See also

      Scalar and Correlated Subqueries - in the 2.0 tutorial

    • method correlate_except(*fromclauses: Union[Literal[None, False], _FromClauseArgument]) → SelfScalarSelect

      Return a new ScalarSelect which will omit the given FROM clauses from the auto-correlation process.

      This method is mirrored from the method of the underlying Select. The method applies the :meth:_sql.Select.correlate_except` method, then returns a new against that statement.

      New in version 1.4: Previously, the ScalarSelect.correlate_except() method was only available from .

      • Parameters:

        *fromclauses – a list of one or more FromClause constructs, or other compatible constructs (i.e. ORM-mapped classes) to become part of the correlate-exception collection.

      See also

      Scalar and Correlated Subqueries - in the 2.0 tutorial

    • attribute inherit_cache: Optional[bool] = True

      Indicate if this HasCacheKey instance should make use of the cache key generation scheme used by its immediate superclass.

      The attribute defaults to None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value to False, except that a warning is also emitted.

      This flag can be set to True on a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.

      See also

      - General guideslines for setting the HasCacheKey.inherit_cache attribute for third-party or user defined SQL constructs.

    • method self_group(against: Optional[OperatorType] = None) → ColumnElement[Any]

      Apply a ‘grouping’ to this .

      This method is overridden by subclasses to return a “grouping” construct, i.e. parenthesis. In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by select() constructs when placed into the FROM clause of another . (Note that subqueries should be normally created using the Select.alias() method, as many platforms require nested SELECT statements to be named).

      As expressions are composed together, the application of is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression like x OR (y AND z) - AND takes precedence over OR.

      The base self_group() method of just returns self.

    • method sqlalchemy.sql.expression.ScalarSelect.where(crit: _ColumnExpressionArgument[bool]) → SelfScalarSelect

      Apply a WHERE clause to the SELECT statement referred to by this .

    class sqlalchemy.sql.expression.Select

    Represents a SELECT statement.

    The Select object is normally constructed using the function. See that function for details.

    See also

    select()

    - in the 2.0 tutorial

    Members

    __init__(), , add_cte(), , as_scalar(), , column(), , columns_clause_froms, , correlate_except(), , cte(), , except_(), , execution_options(), , exported_columns, , filter(), , from_statement(), , get_children(), , get_final_froms(), , group_by(), , inherit_cache, , intersect(), , is_derived_from(), , join_from(), , lateral(), , offset(), , order_by(), , outerjoin_from(), , reduce_columns(), , scalar_subquery(), , select_from(), , self_group(), , slice(), , suffix_with(), , union_all(), , whereclause, , with_hint(), , with_statement_hint()

    Class signature

    class (sqlalchemy.sql.expression.HasPrefixes, , sqlalchemy.sql.expression.HasHints, sqlalchemy.sql.expression.HasCompileState, sqlalchemy.sql.expression._SelectFromElements, sqlalchemy.sql.expression.GenerativeSelect, sqlalchemy.sql.expression.TypedReturnsRows)

    • method __init__(*entities: _ColumnsClauseArgument[Any])

      Construct a new Select.

      The public constructor for is the select() function.

    • method add_columns(*entities: _ColumnsClauseArgument[Any]) → Select[Any]

      Return a new construct with the given entities appended to its columns clause.

      E.g.:

      1. my_select = my_select.add_columns(table.c.new_column)

      The original expressions in the columns clause remain in place. To replace the original expressions with new ones, see the method Select.with_only_columns().

      • Parameters:

        *entities – column, table, or other entity expressions to be added to the columns clause

      See also

      - replaces existing expressions rather than appending.

      Selecting Multiple ORM Entities Simultaneously - ORM-centric example

    • method add_cte(*ctes: CTE, nest_here: bool = False) → SelfHasCTE

      inherited from the method of HasCTE

      Add one or more constructs to this statement.

      This method will associate the given CTE constructs with the parent statement such that they will each be unconditionally rendered in the WITH clause of the final statement, even if not referenced elsewhere within the statement or any sub-selects.

      The optional parameter when set to True will have the effect that each given CTE will render in a WITH clause rendered directly along with this statement, rather than being moved to the top of the ultimate rendered statement, even if this statement is rendered as a subquery within a larger statement.

      This method has two general uses. One is to embed CTE statements that serve some purpose without being referenced explicitly, such as the use case of embedding a DML statement such as an INSERT or UPDATE as a CTE inline with a primary statement that may draw from its results indirectly. The other is to provide control over the exact placement of a particular series of CTE constructs that should remain rendered directly in terms of a particular statement that may be nested in a larger statement.

      E.g.:

      1. from sqlalchemy import table, column, select
      2. t = table('t', column('c1'), column('c2'))
      3. ins = t.insert().values({"c1": "x", "c2": "y"}).cte()
      4. stmt = select(t).add_cte(ins)

      Would render:

      1. WITH anon_1 AS
      2. (INSERT INTO t (c1, c2) VALUES (:param_1, :param_2))
      3. SELECT t.c1, t.c2
      4. FROM t

      Above, the “anon_1” CTE is not referred towards in the SELECT statement, however still accomplishes the task of running an INSERT statement.

      Similarly in a DML-related context, using the PostgreSQL construct to generate an “upsert”:

      1. from sqlalchemy import table, column
      2. from sqlalchemy.dialects.postgresql import insert
      3. t = table("t", column("c1"), column("c2"))
      4. delete_statement_cte = (
      5. t.delete().where(t.c.c1 < 1).cte("deletions")
      6. )
      7. insert_stmt = insert(t).values({"c1": 1, "c2": 2})
      8. update_statement = insert_stmt.on_conflict_do_update(
      9. index_elements=[t.c.c1],
      10. set_={
      11. "c1": insert_stmt.excluded.c1,
      12. "c2": insert_stmt.excluded.c2,
      13. },
      14. ).add_cte(delete_statement_cte)
      15. print(update_statement)

      The above statement renders as:

      1. WITH deletions AS
      2. (DELETE FROM t WHERE t.c1 < %(c1_1)s)
      3. INSERT INTO t (c1, c2) VALUES (%(c1)s, %(c2)s)
      4. ON CONFLICT (c1) DO UPDATE SET c1 = excluded.c1, c2 = excluded.c2

      New in version 1.4.21.

      • Parameters:

        • *ctes

          zero or more CTE constructs.

          Changed in version 2.0: Multiple CTE instances are accepted

        • nest_here

          if True, the given CTE or CTEs will be rendered as though they specified the flag to True when they were added to this HasCTE. Assuming the given CTEs are not referenced in an outer-enclosing statement as well, the CTEs given should render at the level of this statement when this flag is given.

          New in version 2.0.

          See also

    • method sqlalchemy.sql.expression.Select.alias(name: Optional[str] = None, flat: bool = False) →

      inherited from the SelectBase.alias() method of

      Return a named subquery against this SelectBase.

      For a (as opposed to a FromClause), this returns a object which behaves mostly the same as the Alias object that is used with a .

      Changed in version 1.4: The SelectBase.alias() method is now a synonym for the method.

    • method sqlalchemy.sql.expression.Select.as_scalar() → [Any]

      inherited from the SelectBase.as_scalar() method of

      Deprecated since version 1.4: The SelectBase.as_scalar() method is deprecated and will be removed in a future release. Please refer to .

    • attribute sqlalchemy.sql.expression.Select.c

      inherited from the attribute of SelectBase

      Deprecated since version 1.4: The and SelectBase.columns attributes are deprecated and will be removed in a future release; these attributes implicitly create a subquery that should be explicit. Please call SelectBase.subquery() first in order to create a subquery, which then contains this attribute. To access the columns that this SELECT object SELECTs from, use the attribute.

    • method sqlalchemy.sql.expression.Select.column(column: _ColumnsClauseArgument[Any]) → [Any]

      Return a new select() construct with the given column expression added to its columns clause.

      Deprecated since version 1.4: The method is deprecated and will be removed in a future release. Please use Select.add_columns()

      E.g.:

      1. my_select = my_select.column(table.c.new_column)

      See the documentation for for guidelines on adding /replacing the columns of a Select object.

    • attribute column_descriptions

      Return a plugin-enabled ‘column descriptions’ structure referring to the columns which are SELECTed by this statement.

      This attribute is generally useful when using the ORM, as an extended structure which includes information about mapped entities is returned. The section contains more background.

      For a Core-only statement, the structure returned by this accessor is derived from the same objects that are returned by the Select.selected_columns accessor, formatted as a list of dictionaries which contain the keys name, type and expr, which indicate the column expressions to be selected:

      1. >>> stmt = select(user_table)
      2. >>> stmt.column_descriptions
      3. [
      4. {
      5. 'name': 'id',
      6. 'type': Integer(),
      7. 'expr': Column('id', Integer(), ...)},
      8. {
      9. 'name': 'name',
      10. 'type': String(length=30),
      11. 'expr': Column('name', String(length=30), ...)}
      12. ]

      Changed in version 1.4.33: The attribute returns a structure for a Core-only set of entities, not just ORM-only entities.

      See also

      UpdateBase.entity_description - entity information for an , update(), or

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

    • attribute columns_clause_froms

      Return the set of FromClause objects implied by the columns clause of this SELECT statement.

      New in version 1.4.23.

      See also

      - “final” FROM list taking the full statement into account

      Select.with_only_columns() - makes use of this collection to set up a new FROM list

    • method correlate(*fromclauses: Union[Literal[None, False], _FromClauseArgument]) → SelfSelect

      Return a new Select which will correlate the given FROM clauses to that of an enclosing .

      Calling this method turns off the Select object’s default behavior of “auto-correlation”. Normally, FROM elements which appear in a that encloses this one via its WHERE clause, ORDER BY, HAVING or will be omitted from this Select object’s . Setting an explicit correlation collection using the Select.correlate() method provides a fixed list of FROM objects that can potentially take place in this process.

      When is used to apply specific FROM clauses for correlation, the FROM elements become candidates for correlation regardless of how deeply nested this Select object is, relative to an enclosing which refers to the same FROM object. This is in contrast to the behavior of “auto-correlation” which only correlates to an immediate enclosing Select. Multi-level correlation ensures that the link between enclosed and enclosing is always via at least one WHERE/ORDER BY/HAVING/columns clause in order for correlation to take place.

      If None is passed, the Select object will correlate none of its FROM entries, and all will render unconditionally in the local FROM clause.

      • Parameters:

        *fromclauses – one or more or other FROM-compatible construct such as an ORM mapped entity to become part of the correlate collection; alternatively pass a single value None to remove all existing correlations.

      See also

      Select.correlate_except()

    • method sqlalchemy.sql.expression.Select.correlate_except(*fromclauses: Union[Literal[None, False], _FromClauseArgument]) → SelfSelect

      Return a new which will omit the given FROM clauses from the auto-correlation process.

      Calling Select.correlate_except() turns off the object’s default behavior of “auto-correlation” for the given FROM elements. An element specified here will unconditionally appear in the FROM list, while all other FROM elements remain subject to normal auto-correlation behaviors.

      If None is passed, or no arguments are passed, the Select object will correlate all of its FROM entries.

      • Parameters:

        *fromclauses – a list of one or more constructs, or other compatible constructs (i.e. ORM-mapped classes) to become part of the correlate-exception collection.

      See also

      Select.correlate()

    • method sqlalchemy.sql.expression.Select.corresponding_column(column: KeyedColumnElement[Any], require_embedded: bool = False) → Optional[KeyedColumnElement[Any]]

      inherited from the method of Selectable

      Given a , return the exported ColumnElement object from the collection of this Selectable which corresponds to that original via a common ancestor column.

      • Parameters:

        • column – the target ColumnElement to be matched.

        • require_embedded – only return corresponding columns for the given , if the given ColumnElement is actually present within a sub-element of this . Normally the column will match if it merely shares a common ancestor with one of the exported columns of this Selectable.

    1. See also
    2. [Selectable.exported\_columns](#sqlalchemy.sql.expression.Selectable.exported_columns "sqlalchemy.sql.expression.Selectable.exported_columns") - the [ColumnCollection]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnCollection "sqlalchemy.sql.expression.ColumnCollection") that is used for the operation.
    3. [ColumnCollection.corresponding\_column()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnCollection.corresponding_column "sqlalchemy.sql.expression.ColumnCollection.corresponding_column") - implementation method.
    • method cte(name: Optional[str] = None, recursive: bool = False, nesting: bool = False) → CTE

      inherited from the method of HasCTE

      Return a new , or Common Table Expression instance.

      Common table expressions are a SQL standard whereby SELECT statements can draw upon secondary statements specified along with the primary statement, using a clause called “WITH”. Special semantics regarding UNION can also be employed to allow “recursive” queries, where a SELECT statement can draw upon the set of rows that have previously been selected.

      CTEs can also be applied to DML constructs UPDATE, INSERT and DELETE on some databases, both as a source of CTE rows when combined with RETURNING, as well as a consumer of CTE rows.

      Changed in version 1.1: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.

      SQLAlchemy detects CTE objects, which are treated similarly to objects, as special elements to be delivered to the FROM clause of the statement as well as to a WITH clause at the top of the statement.

      For special prefixes such as PostgreSQL “MATERIALIZED” and “NOT MATERIALIZED”, the CTE.prefix_with() method may be used to establish these.

      Changed in version 1.3.13: Added support for prefixes. In particular - MATERIALIZED and NOT MATERIALIZED.

      • Parameters:

        • name – name given to the common table expression. Like FromClause.alias(), the name can be left as None in which case an anonymous symbol will be used at query compile time.

        • recursive – if True, will render WITH RECURSIVE. A recursive common table expression is intended to be used in conjunction with UNION ALL in order to derive rows from those already selected.

        • nesting

          if True, will render the CTE locally to the statement in which it is referenced. For more complex scenarios, the method using the HasCTE.add_cte.nest_here parameter may also be used to more carefully control the exact placement of a particular CTE.

          New in version 1.4.24.

          See also

    1. The following examples include two from PostgreSQLs documentation at [https://www.postgresql.org/docs/current/static/queries-with.html](https://www.postgresql.org/docs/current/static/queries-with.html), as well as additional examples.
    2. Example 1, non recursive:
    3. ```
    4. from sqlalchemy import (Table, Column, String, Integer,
    5. MetaData, select, func)
    6. metadata = MetaData()
    7. orders = Table('orders', metadata,
    8. Column('region', String),
    9. Column('amount', Integer),
    10. Column('product', String),
    11. Column('quantity', Integer)
    12. )
    13. regional_sales = select(
    14. orders.c.region,
    15. func.sum(orders.c.amount).label('total_sales')
    16. ).group_by(orders.c.region).cte("regional_sales")
    17. top_regions = select(regional_sales.c.region).\
    18. where(
    19. regional_sales.c.total_sales >
    20. select(
    21. func.sum(regional_sales.c.total_sales) / 10
    22. )
    23. ).cte("top_regions")
    24. statement = select(
    25. orders.c.region,
    26. orders.c.product,
    27. func.sum(orders.c.quantity).label("product_units"),
    28. func.sum(orders.c.amount).label("product_sales")
    29. ).where(orders.c.region.in_(
    30. select(top_regions.c.region)
    31. )).group_by(orders.c.region, orders.c.product)
    32. result = conn.execute(statement).fetchall()
    33. ```
    34. Example 2, WITH RECURSIVE:
    35. ```
    36. from sqlalchemy import (Table, Column, String, Integer,
    37. MetaData, select, func)
    38. metadata = MetaData()
    39. parts = Table('parts', metadata,
    40. Column('part', String),
    41. Column('sub_part', String),
    42. Column('quantity', Integer),
    43. )
    44. included_parts = select(\
    45. parts.c.sub_part, parts.c.part, parts.c.quantity\
    46. ).\
    47. where(parts.c.part=='our part').\
    48. cte(recursive=True)
    49. incl_alias = included_parts.alias()
    50. parts_alias = parts.alias()
    51. included_parts = included_parts.union_all(
    52. select(
    53. parts_alias.c.sub_part,
    54. parts_alias.c.part,
    55. parts_alias.c.quantity
    56. ).\
    57. where(parts_alias.c.part==incl_alias.c.sub_part)
    58. )
    59. statement = select(
    60. included_parts.c.sub_part,
    61. func.sum(included_parts.c.quantity).
    62. label('total_quantity')
    63. ).\
    64. group_by(included_parts.c.sub_part)
    65. result = conn.execute(statement).fetchall()
    66. ```
    67. Example 3, an upsert using UPDATE and INSERT with CTEs:
    68. ```
    69. from datetime import date
    70. from sqlalchemy import (MetaData, Table, Column, Integer,
    71. Date, select, literal, and_, exists)
    72. metadata = MetaData()
    73. visitors = Table('visitors', metadata,
    74. Column('product_id', Integer, primary_key=True),
    75. Column('date', Date, primary_key=True),
    76. Column('count', Integer),
    77. )
    78. # add 5 visitors for the product_id == 1
    79. product_id = 1
    80. day = date.today()
    81. count = 5
    82. update_cte = (
    83. visitors.update()
    84. .where(and_(visitors.c.product_id == product_id,
    85. visitors.c.date == day))
    86. .values(count=visitors.c.count + count)
    87. .returning(literal(1))
    88. .cte('update_cte')
    89. )
    90. upsert = visitors.insert().from_select(
    91. [visitors.c.product_id, visitors.c.date, visitors.c.count],
    92. select(literal(product_id), literal(day), literal(count))
    93. .where(~exists(update_cte.select()))
    94. )
    95. connection.execute(upsert)
    96. ```
    97. Example 4, Nesting CTE (SQLAlchemy 1.4.24 and above):
    98. ```
    99. value_a = select(
    100. literal("root").label("n")
    101. ).cte("value_a")
    102. # A nested CTE with the same name as the root one
    103. value_a_nested = select(
    104. literal("nesting").label("n")
    105. ).cte("value_a", nesting=True)
    106. # Nesting CTEs takes ascendency locally
    107. # over the CTEs at a higher level
    108. value_b = select(value_a_nested.c.n).cte("value_b")
    109. value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
    110. ```
    111. The above query will render the second CTE nested inside the first, shown with inline parameters below as:
    112. ```
    113. WITH
    114. value_a AS
    115. (SELECT 'root' AS n),
    116. value_b AS
    117. (WITH value_a AS
    118. (SELECT 'nesting' AS n)
    119. SELECT value_a.n AS n FROM value_a)
    120. SELECT value_a.n AS a, value_b.n AS b
    121. FROM value_a, value_b
    122. ```
    123. The same CTE can be set up using the [HasCTE.add\_cte()](#sqlalchemy.sql.expression.HasCTE.add_cte "sqlalchemy.sql.expression.HasCTE.add_cte") method as follows (SQLAlchemy 2.0 and above):
    124. ```
    125. value_a = select(
    126. literal("root").label("n")
    127. ).cte("value_a")
    128. # A nested CTE with the same name as the root one
    129. value_a_nested = select(
    130. literal("nesting").label("n")
    131. ).cte("value_a")
    132. # Nesting CTEs takes ascendency locally
    133. # over the CTEs at a higher level
    134. value_b = (
    135. select(value_a_nested.c.n).
    136. add_cte(value_a_nested, nest_here=True).
    137. cte("value_b")
    138. )
    139. value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
    140. ```
    141. Example 5, Non-Linear CTE (SQLAlchemy 1.4.28 and above):
    142. ```
    143. edge = Table(
    144. "edge",
    145. metadata,
    146. Column("id", Integer, primary_key=True),
    147. Column("left", Integer),
    148. Column("right", Integer),
    149. )
    150. root_node = select(literal(1).label("node")).cte(
    151. "nodes", recursive=True
    152. )
    153. left_edge = select(edge.c.left).join(
    154. root_node, edge.c.right == root_node.c.node
    155. )
    156. right_edge = select(edge.c.right).join(
    157. root_node, edge.c.left == root_node.c.node
    158. )
    159. subgraph_cte = root_node.union(left_edge, right_edge)
    160. subgraph = select(subgraph_cte)
    161. ```
    162. The above query will render 2 UNIONs inside the recursive CTE:
    163. ```
    164. WITH RECURSIVE nodes(node) AS (
    165. SELECT 1 AS node
    166. UNION
    167. SELECT edge."left" AS "left"
    168. FROM edge JOIN nodes ON edge."right" = nodes.node
    169. UNION
    170. SELECT edge."right" AS "right"
    171. FROM edge JOIN nodes ON edge."left" = nodes.node
    172. )
    173. SELECT nodes.node FROM nodes
    174. ```
    175. See also
    176. [Query.cte()]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query.cte "sqlalchemy.orm.Query.cte") - ORM version of [HasCTE.cte()](#sqlalchemy.sql.expression.HasCTE.cte "sqlalchemy.sql.expression.HasCTE.cte").
    • method sqlalchemy.sql.expression.Select.distinct(*expr: _ColumnExpressionArgument[Any]) → SelfSelect

      Return a new construct which will apply DISTINCT to its columns clause.

      • Parameters:

        *expr

        optional column expressions. When present, the PostgreSQL dialect will render a DISTINCT ON (<expressions>>) construct.

        Deprecated since version 1.4: Using *expr in other dialects is deprecated and will raise CompileError in a future version.

    • method except_(*other: _SelectStatementForCompoundArgument) → CompoundSelect

      Return a SQL EXCEPT of this select() construct against the given selectable provided as positional arguments.

      • Parameters:

        *other

        one or more elements with which to create a UNION.

        Changed in version 1.4.28: multiple elements are now accepted.

    • method except_all(*other: _SelectStatementForCompoundArgument) → CompoundSelect

      Return a SQL EXCEPT ALL of this select() construct against the given selectables provided as positional arguments.

      • Parameters:

        *other

        one or more elements with which to create a UNION.

        Changed in version 1.4.28: multiple elements are now accepted.

    • method execution_options(**kw: Any) → SelfExecutable

      inherited from the Executable.execution_options() method of

      Set non-SQL options for the statement which take effect during execution.

      Execution options can be set at many scopes, including per-statement, per-connection, or per execution, using methods such as Connection.execution_options() and parameters which accept a dictionary of options such as and Session.execute.execution_options.

      The primary characteristic of an execution option, as opposed to other kinds of options such as ORM loader options, is that execution options never affect the compiled SQL of a query, only things that affect how the SQL statement itself is invoked or how results are fetched. That is, execution options are not part of what’s accommodated by SQL compilation nor are they considered part of the cached state of a statement.

      The method is generative, as is the case for the method as applied to the and Query objects, which means when the method is called, a copy of the object is returned, which applies the given parameters to that new copy, but leaves the original unchanged:

      1. statement = select(table.c.x, table.c.y)
      2. new_statement = statement.execution_options(my_option=True)

      An exception to this behavior is the object, where the Connection.execution_options() method is explicitly not generative.

      The kinds of options that may be passed to and other related methods and parameter dictionaries include parameters that are explicitly consumed by SQLAlchemy Core or ORM, as well as arbitrary keyword arguments not defined by SQLAlchemy, which means the methods and/or parameter dictionaries may be used for user-defined parameters that interact with custom code, which may access the parameters using methods such as Executable.get_execution_options() and , or within selected event hooks using a dedicated execution_options event parameter such as ConnectionEvents.before_execute.execution_options or , e.g.:

      1. from sqlalchemy import event
      2. @event.listens_for(some_engine, "before_execute")
      3. def _process_opt(conn, statement, multiparams, params, execution_options):
      4. "run a SQL function before invoking a statement"
      5. if execution_options.get("do_special_thing", False):
      6. conn.exec_driver_sql("run_special_function()")

      Within the scope of options that are explicitly recognized by SQLAlchemy, most apply to specific classes of objects and not others. The most common execution options include:

      See also

      Connection.execution_options()

      Session.execute.execution_options

      - documentation on all ORM-specific execution options

    • method sqlalchemy.sql.expression.Select.exists() →

      inherited from the SelectBase.exists() method of

      Return an Exists representation of this selectable, which can be used as a column expression.

      The returned object is an instance of .

      See also

      exists()

      - in the 2.0 style tutorial.

      New in version 1.4.

    • attribute exported_columns

      inherited from the SelectBase.exported_columns attribute of

      A ColumnCollection that represents the “exported” columns of this , not including TextClause constructs.

      The “exported” columns for a object are synonymous with the SelectBase.selected_columns collection.

      New in version 1.4.

      See also

      Selectable.exported_columns

    • method sqlalchemy.sql.expression.Select.fetch(count: Union[int, _ColumnExpressionArgument[int]], with_ties: bool = False, percent: bool = False) → SelfGenerativeSelect

      inherited from the method of GenerativeSelect

      Return a new selectable with the given FETCH FIRST criterion applied.

      This is a numeric value which usually renders as FETCH {FIRST | NEXT} [ count ] {ROW | ROWS} {ONLY | WITH TIES} expression in the resulting select. This functionality is is currently implemented for Oracle, PostgreSQL, MSSQL.

      Use to specify the offset.

      Note

      The GenerativeSelect.fetch() method will replace any clause applied with .

      New in version 1.4.

      • Parameters:

        • count – an integer COUNT parameter, or a SQL expression that provides an integer result. When percent=True this will represent the percentage of rows to return, not the absolute value. Pass None to reset it.

        • with_ties – When True, the WITH TIES option is used to return any additional rows that tie for the last place in the result set according to the ORDER BY clause. The ORDER BY may be mandatory in this case. Defaults to False

        • percent – When True, count represents the percentage of the total number of selected rows to return. Defaults to False

    1. See also
    2. [GenerativeSelect.limit()](#sqlalchemy.sql.expression.GenerativeSelect.limit "sqlalchemy.sql.expression.GenerativeSelect.limit")
    3. [GenerativeSelect.offset()](#sqlalchemy.sql.expression.GenerativeSelect.offset "sqlalchemy.sql.expression.GenerativeSelect.offset")
    • method sqlalchemy.sql.expression.Select.filter(*criteria: _ColumnExpressionArgument[bool]) → SelfSelect

      A synonym for the method.

    • method sqlalchemy.sql.expression.Select.filter_by(**kwargs: Any) → SelfSelect

      apply the given filtering criterion as a WHERE clause to this select.

    • method from_statement(statement: ExecutableReturnsRows) → ExecutableReturnsRows

      Apply the columns which this Select would select onto another statement.

      This operation is and will raise a not supported exception if this Select does not select from plugin-enabled entities.

      The statement is typically either a or select() construct, and should return the set of columns appropriate to the entities represented by this .

      See also

      Getting ORM Results from Textual Statements - usage examples in the ORM Querying Guide

    • attribute froms

      Return the displayed list of FromClause elements.

      Deprecated since version 1.4.23: The attribute is moved to the Select.get_final_froms() method.

    • method get_children(**kw: Any) → Iterable[ClauseElement]

      Return immediate child HasTraverseInternals elements of this HasTraverseInternals.

      This is used for visit traversal.

      **kw may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).

    • method get_execution_options() → _ExecuteOptions

      inherited from the Executable.get_execution_options() method of

      Get the non-SQL options which will take effect during execution.

      New in version 1.3.

      See also

      Executable.execution_options()

    • method get_final_froms() → Sequence[FromClause]

      Compute the final displayed list of elements.

      This method will run through the full computation required to determine what FROM elements will be displayed in the resulting SELECT statement, including shadowing individual tables with JOIN objects, as well as full computation for ORM use cases including eager loading clauses.

      For ORM use, this accessor returns the post compilation list of FROM objects; this collection will include elements such as eagerly loaded tables and joins. The objects will not be ORM enabled and not work as a replacement for the Select.select_froms() collection; additionally, the method is not well performing for an ORM enabled statement as it will incur the full ORM construction process.

      To retrieve the FROM list that’s implied by the “columns” collection passed to the Select originally, use the accessor.

      To select from an alternative set of columns while maintaining the FROM list, use the Select.with_only_columns() method and pass the parameter.

      New in version 1.4.23: - the Select.get_final_froms() method replaces the previous accessor, which is deprecated.

      See also

      Select.columns_clause_froms

    • method get_label_style() → SelectLabelStyle

      inherited from the method of GenerativeSelect

      Retrieve the current label style.

      New in version 1.4.

    • method group_by(_GenerativeSelect\_first: Union[Literal[None, _NoArg.NO_ARG], _ColumnExpressionOrStrLabelArgument[Any]] = _NoArg.NO_ARG, *clauses: _ColumnExpressionOrStrLabelArgument[Any]_) → SelfGenerativeSelect

      inherited from the GenerativeSelect.group_by() method of

      Return a new selectable with the given list of GROUP BY criterion applied.

      All existing GROUP BY settings can be suppressed by passing None.

      e.g.:

      1. stmt = select(table.c.name, func.max(table.c.stat)).\
      2. group_by(table.c.name)
      • Parameters:

        *clauses – a series of ColumnElement constructs which will be used to generate an GROUP BY clause.

      See also

      - in the SQLAlchemy Unified Tutorial

      - in the SQLAlchemy Unified Tutorial

    • method having(*having: _ColumnExpressionArgument[bool]) → SelfSelect

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

    • attribute inherit_cache: Optional[bool] = None

      inherited from the HasCacheKey.inherit_cache attribute of HasCacheKey

      Indicate if this instance should make use of the cache key generation scheme used by its immediate superclass.

      The attribute defaults to None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value to False, except that a warning is also emitted.

      This flag can be set to True on a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.

      See also

      Enabling Caching Support for Custom Constructs - General guideslines for setting the attribute for third-party or user defined SQL constructs.

    • attribute sqlalchemy.sql.expression.Select.inner_columns

      An iterator of all expressions which would be rendered into the columns clause of the resulting SELECT statement.

      This method is legacy as of 1.4 and is superseded by the Select.exported_columns collection.

    • method intersect(*other: _SelectStatementForCompoundArgument) → CompoundSelect

      Return a SQL INTERSECT of this select() construct against the given selectables provided as positional arguments.

      • Parameters:

        • *other

          one or more elements with which to create a UNION.

          Changed in version 1.4.28: multiple elements are now accepted.

        • **kwargs – keyword arguments are forwarded to the constructor for the newly created object.

    • method sqlalchemy.sql.expression.Select.intersect_all(*other: _SelectStatementForCompoundArgument) →

      Return a SQL INTERSECT ALL of this select() construct against the given selectables provided as positional arguments.

      • Parameters:

        • *other

          one or more elements with which to create a UNION.

          Changed in version 1.4.28: multiple elements are now accepted.

        • **kwargs – keyword arguments are forwarded to the constructor for the newly created CompoundSelect object.

    • method is_derived_from(fromclause: Optional[FromClause]) → bool

      Return True if this is ‘derived’ from the given FromClause.

      An example would be an Alias of a Table is derived from that Table.

    • method join(target: _JoinTargetArgument, onclause: Optional[_OnClauseArgument] = None, *, isouter: bool = False, full: bool = False) → SelfSelect

      Create a SQL JOIN against this Select object’s criterion and apply generatively, returning the newly resulting .

      E.g.:

      1. stmt = select(user_table).join(address_table, user_table.c.id == address_table.c.user_id)

      The above statement generates SQL similar to:

      1. SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id

      Changed in version 1.4: Select.join() now creates a object between a FromClause source that is within the FROM clause of the existing SELECT, and a given target , and then adds this Join to the FROM clause of the newly generated SELECT statement. This is completely reworked from the behavior in 1.3, which would instead create a subquery of the entire and then join that subquery to the target.

      This is a backwards incompatible change as the previous behavior was mostly useless, producing an unnamed subquery rejected by most databases in any case. The new behavior is modeled after that of the very successful Query.join() method in the ORM, in order to support the functionality of being available by using a Select object with an .

      See the notes for this change at select().join() and outerjoin() add JOIN criteria to the current query, rather than creating a subquery.

      • Parameters:

        • target – target table to join towards

        • onclause – ON clause of the join. If omitted, an ON clause is generated automatically based on the linkages between the two tables, if one can be unambiguously determined, otherwise an error is raised.

        • isouter – if True, generate LEFT OUTER join. Same as Select.outerjoin().

        • full – if True, generate FULL OUTER join.

    1. See also
    2. [Explicit FROM clauses and JOINs]($93605e6ef77d4344.md#tutorial-select-join) - in the [SQLAlchemy Unified Tutorial]($4406c4fa3e52f66b.md)
    3. [Joins]($b3109e359428cd80.md#orm-queryguide-joins) - in the [ORM Querying Guide]($86681c2576bdda58.md)
    4. [Select.join\_from()](#sqlalchemy.sql.expression.Select.join_from "sqlalchemy.sql.expression.Select.join_from")
    5. [Select.outerjoin()](#sqlalchemy.sql.expression.Select.outerjoin "sqlalchemy.sql.expression.Select.outerjoin")
    • method join_from(from\: _FromClauseArgument, _target: _JoinTargetArgument, onclause: Optional[_OnClauseArgument] = None, *, isouter: bool = False, full: bool = False) → SelfSelect

      Create a SQL JOIN against this Select object’s criterion and apply generatively, returning the newly resulting .

      E.g.:

      1. stmt = select(user_table, address_table).join_from(
      2. user_table, address_table, user_table.c.id == address_table.c.user_id
      3. )

      The above statement generates SQL similar to:

      1. SELECT user.id, user.name, address.id, address.email, address.user_id
      2. FROM user JOIN address ON user.id = address.user_id

      New in version 1.4.

      • Parameters:

        • from_ – the left side of the join, will be rendered in the FROM clause and is roughly equivalent to using the Select.select_from() method.

        • target – target table to join towards

        • onclause – ON clause of the join.

        • isouter – if True, generate LEFT OUTER join. Same as .

        • full – if True, generate FULL OUTER join.

    1. See also
    2. [Explicit FROM clauses and JOINs]($93605e6ef77d4344.md#tutorial-select-join) - in the [SQLAlchemy Unified Tutorial]($4406c4fa3e52f66b.md)
    3. [Joins]($b3109e359428cd80.md#orm-queryguide-joins) - in the [ORM Querying Guide]($86681c2576bdda58.md)
    4. [Select.join()](#sqlalchemy.sql.expression.Select.join "sqlalchemy.sql.expression.Select.join")
    • method sqlalchemy.sql.expression.Select.label(name: Optional[str]) → [Any]

      inherited from the SelectBase.label() method of

      Return a ‘scalar’ representation of this selectable, embedded as a subquery with a label.

      See also

      SelectBase.as_scalar().

    • method lateral(name: Optional[str] = None) → LateralFromClause

      inherited from the SelectBase.lateral() method of

      Return a LATERAL alias of this Selectable.

      The return value is the construct also provided by the top-level lateral() function.

      New in version 1.1.

      See also

      - overview of usage.

    • method sqlalchemy.sql.expression.Select.limit(limit: Union[int, _ColumnExpressionArgument[int]]) → SelfGenerativeSelect

      inherited from the method of GenerativeSelect

      Return a new selectable with the given LIMIT criterion applied.

      This is a numerical value which usually renders as a LIMIT expression in the resulting select. Backends that don’t support LIMIT will attempt to provide similar functionality.

      Note

      The method will replace any clause applied with GenerativeSelect.fetch().

      Changed in version 1.0.0: - can now accept arbitrary SQL expressions as well as integer values.

      • Parameters:

        limit – an integer LIMIT parameter, or a SQL expression that provides an integer result. Pass None to reset it.

      See also

      GenerativeSelect.fetch()

    • method sqlalchemy.sql.expression.Select.offset(offset: Union[int, _ColumnExpressionArgument[int]]) → SelfGenerativeSelect

      inherited from the method of GenerativeSelect

      Return a new selectable with the given OFFSET criterion applied.

      This is a numeric value which usually renders as an OFFSET expression in the resulting select. Backends that don’t support OFFSET will attempt to provide similar functionality.

      Changed in version 1.0.0: - can now accept arbitrary SQL expressions as well as integer values.

      • Parameters:

        offset – an integer OFFSET parameter, or a SQL expression that provides an integer result. Pass None to reset it.

      See also

      GenerativeSelect.limit()

    • method sqlalchemy.sql.expression.Select.options(*options: ExecutableOption) → SelfExecutable

      inherited from the method of Executable

      Apply options to this statement.

      In the general sense, options are any kind of Python object that can be interpreted by the SQL compiler for the statement. These options can be consumed by specific dialects or specific kinds of compilers.

      The most commonly known kind of option are the ORM level options that apply “eager load” and other loading behaviors to an ORM query. However, options can theoretically be used for many other purposes.

      For background on specific kinds of options for specific kinds of statements, refer to the documentation for those option objects.

      Changed in version 1.4: - added to Core statement objects towards the goal of allowing unified Core / ORM querying capabilities.

      See also

      Column Loading Options - refers to options specific to the usage of ORM queries

      - refers to options specific to the usage of ORM queries

    • method sqlalchemy.sql.expression.Select.order_by(_GenerativeSelect\_first: Union[Literal[None, _NoArg.NO_ARG], _ColumnExpressionOrStrLabelArgument[Any]] = _NoArg.NO_ARG, *clauses: _ColumnExpressionOrStrLabelArgument[Any]_) → SelfGenerativeSelect

      inherited from the method of GenerativeSelect

      Return a new selectable with the given list of ORDER BY criteria applied.

      e.g.:

      1. stmt = select(table).order_by(table.c.id, table.c.name)

      Calling this method multiple times is equivalent to calling it once with all the clauses concatenated. All existing ORDER BY criteria may be cancelled by passing None by itself. New ORDER BY criteria may then be added by invoking again, e.g.:

      1. # will erase all ORDER BY and ORDER BY new_col alone
      2. stmt = stmt.order_by(None).order_by(new_col)
      • Parameters:

        *clauses – a series of ColumnElement constructs which will be used to generate an ORDER BY clause.

      See also

      - in the SQLAlchemy Unified Tutorial

      - in the SQLAlchemy Unified Tutorial

    • method outerjoin(target: _JoinTargetArgument, onclause: Optional[_OnClauseArgument] = None, *, full: bool = False) → SelfSelect

      Create a left outer join.

      Parameters are the same as that of Select.join().

      Changed in version 1.4: now creates a Join object between a source that is within the FROM clause of the existing SELECT, and a given target FromClause, and then adds this to the FROM clause of the newly generated SELECT statement. This is completely reworked from the behavior in 1.3, which would instead create a subquery of the entire Select and then join that subquery to the target.

      This is a backwards incompatible change as the previous behavior was mostly useless, producing an unnamed subquery rejected by most databases in any case. The new behavior is modeled after that of the very successful method in the ORM, in order to support the functionality of Query being available by using a object with an Session.

      See the notes for this change at .

      See also

      Explicit FROM clauses and JOINs - in the

      Joins - in the

      Select.join()

    • method outerjoin_from(from\: _FromClauseArgument, _target: _JoinTargetArgument, onclause: Optional[_OnClauseArgument] = None, *, full: bool = False) → SelfSelect

      Create a SQL LEFT OUTER JOIN against this Select object’s criterion and apply generatively, returning the newly resulting .

      Usage is the same as that of Select.join_from().

    • method sqlalchemy.sql.expression.Select.prefix_with(*prefixes: _TextCoercedExpressionArgument[Any], dialect: str = ‘*‘) → SelfHasPrefixes

      inherited from the method of HasPrefixes

      Add one or more expressions following the statement keyword, i.e. SELECT, INSERT, UPDATE, or DELETE. Generative.

      This is used to support backend-specific prefix keywords such as those provided by MySQL.

      E.g.:

      1. stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")
      2. # MySQL 5.7 optimizer hints
      3. stmt = select(table).prefix_with(
      4. "/*+ BKA(t1) */", dialect="mysql")

      Multiple prefixes can be specified by multiple calls to .

      • Parameters:

        • *prefixes – textual or ClauseElement construct which will be rendered following the INSERT, UPDATE, or DELETE keyword.

        • dialect – optional string dialect name which will limit rendering of this prefix to only that dialect.

    • method reduce_columns(only_synonyms: bool = True) → Select

      Return a new construct with redundantly named, equivalently-valued columns removed from the columns clause.

      “Redundant” here means two columns where one refers to the other either based on foreign key, or via a simple equality comparison in the WHERE clause of the statement. The primary purpose of this method is to automatically construct a select statement with all uniquely-named columns, without the need to use table-qualified labels as Select.set_label_style() does.

      When columns are omitted based on foreign key, the referred-to column is the one that’s kept. When columns are omitted based on WHERE equivalence, the first column in the columns clause is the one that’s kept.

      • Parameters:

        only_synonyms – when True, limit the removal of columns to those which have the same name as the equivalent. Otherwise, all columns that are equivalent to another are removed.

    • method replace_selectable(old: FromClause, alias: ) → SelfSelectable

      inherited from the Selectable.replace_selectable() method of

      Replace all occurrences of FromClause ‘old’ with the given object, returning a copy of this FromClause.

      Deprecated since version 1.4: The method is deprecated, and will be removed in a future release. Similar functionality is available via the sqlalchemy.sql.visitors module.

    • method sqlalchemy.sql.expression.Select.scalar_subquery() → [Any]

      inherited from the SelectBase.scalar_subquery() method of

      Return a ‘scalar’ representation of this selectable, which can be used as a column expression.

      The returned object is an instance of ScalarSelect.

      Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression. The scalar subquery can then be used in the WHERE clause or columns clause of an enclosing SELECT.

      Note that the scalar subquery differentiates from the FROM-level subquery that can be produced using the method.

      See also

      Scalar and Correlated Subqueries - in the 2.0 tutorial

    • method select(*arg: Any, **kw: Any) → Select

      inherited from the method of SelectBase

      Deprecated since version 1.4: The method is deprecated and will be removed in a future release; this method implicitly creates a subquery that should be explicit. Please call SelectBase.subquery() first in order to create a subquery, which then can be selected.

    • method select_from(*froms: _FromClauseArgument) → SelfSelect

      Return a new select() construct with the given FROM expression(s) merged into its list of FROM objects.

      E.g.:

      1. table1 = table('t1', column('a'))
      2. table2 = table('t2', column('b'))
      3. s = select(table1.c.a).\
      4. select_from(
      5. table1.join(table2, table1.c.a==table2.c.b)
      6. )

      The “from” list is a unique set on the identity of each element, so adding an already present or other selectable will have no effect. Passing a Join that refers to an already present or other selectable will have the effect of concealing the presence of that selectable as an individual element in the rendered FROM list, instead rendering it into a JOIN clause.

      While the typical purpose of Select.select_from() is to replace the default, derived FROM clause with a join, it can also be called with individual table elements, multiple times if desired, in the case that the FROM clause cannot be fully derived from the columns clause:

      1. select(func.count('*')).select_from(table1)
    • attribute selected_columns

      A ColumnCollection representing the columns that this SELECT statement or similar construct returns in its result set, not including constructs.

      This collection differs from the FromClause.columns collection of a in that the columns within this collection cannot be directly nested inside another SELECT statement; a subquery must be applied first which provides for the necessary parenthesization required by SQL.

      For a select() construct, the collection here is exactly what would be rendered inside the “SELECT” statement, and the objects are directly present as they were given, e.g.:

      1. col1 = column('q', Integer)
      2. col2 = column('p', Integer)
      3. stmt = select(col1, col2)

      Above, stmt.selected_columns would be a collection that contains the col1 and col2 objects directly. For a statement that is against a Table or other , the collection will use the ColumnElement objects that are in the collection of the from element.

      Note

      The Select.selected_columns collection does not include expressions established in the columns clause using the construct; these are silently omitted from the collection. To use plain textual column expressions inside of a Select construct, use the construct.

      New in version 1.4.

    • method sqlalchemy.sql.expression.Select.self_group(against: Optional[OperatorType] = None) → Union[SelectStatementGrouping, Self]

      Apply a ‘grouping’ to this .

      This method is overridden by subclasses to return a “grouping” construct, i.e. parenthesis. In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by select() constructs when placed into the FROM clause of another . (Note that subqueries should be normally created using the Select.alias() method, as many platforms require nested SELECT statements to be named).

      As expressions are composed together, the application of is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression like x OR (y AND z) - AND takes precedence over OR.

      The base self_group() method of just returns self.

    • method sqlalchemy.sql.expression.Select.set_label_style(style: ) → SelfGenerativeSelect

      inherited from the GenerativeSelect.set_label_style() method of

      Return a new selectable with the specified label style.

      There are three “label styles” available, SelectLabelStyle.LABEL_STYLE_DISAMBIGUATE_ONLY, , and SelectLabelStyle.LABEL_STYLE_NONE. The default style is .

      In modern SQLAlchemy, there is not generally a need to change the labeling style, as per-expression labels are more effectively used by making use of the ColumnElement.label() method. In past versions, LABEL_STYLE_TABLENAME_PLUS_COL was used to disambiguate same-named columns from different tables, aliases, or subqueries; the newer LABEL_STYLE_DISAMBIGUATE_ONLY now applies labels only to names that conflict with an existing name so that the impact of this labeling is minimal.

      The rationale for disambiguation is mostly so that all column expressions are available from a given collection when a subquery is created.

      New in version 1.4: - the GenerativeSelect.set_label_style() method replaces the previous combination of .apply_labels(), .with_labels() and use_labels=True methods and/or parameters.

      See also

      LABEL_STYLE_DISAMBIGUATE_ONLY

      LABEL_STYLE_TABLENAME_PLUS_COL

      LABEL_STYLE_NONE

      LABEL_STYLE_DEFAULT

    • method slice(start: int, stop: int) → SelfGenerativeSelect

      inherited from the GenerativeSelect.slice() method of

      Apply LIMIT / OFFSET to this statement based on a slice.

      The start and stop indices behave like the argument to Python’s built-in range() function. This method provides an alternative to using LIMIT/OFFSET to get a slice of the query.

      For example,

      1. stmt = select(User).order_by(User).id.slice(1, 3)

      renders as

      1. SELECT users.id AS users_id,
      2. users.name AS users_name
      3. FROM users ORDER BY users.id
      4. LIMIT ? OFFSET ?
      5. (2, 1)

      Note

      The GenerativeSelect.slice() method will replace any clause applied with .

      New in version 1.4: Added the GenerativeSelect.slice() method generalized from the ORM.

      See also

      GenerativeSelect.offset()

    • method sqlalchemy.sql.expression.Select.subquery(name: Optional[str] = None) →

      inherited from the SelectBase.subquery() method of

      Return a subquery of this SelectBase.

      A subquery is from a SQL perspective a parenthesized, named construct that can be placed in the FROM clause of another SELECT statement.

      Given a SELECT statement such as:

      1. stmt = select(table.c.id, table.c.name)

      The above statement might look like:

      1. SELECT table.id, table.name FROM table

      The subquery form by itself renders the same way, however when embedded into the FROM clause of another SELECT statement, it becomes a named sub-element:

      1. subq = stmt.subquery()
      2. new_stmt = select(subq)

      The above renders as:

      1. SELECT anon_1.id, anon_1.name
      2. FROM (SELECT table.id, table.name FROM table) AS anon_1

      Historically, is equivalent to calling the FromClause.alias() method on a FROM object; however, as a object is not directly FROM object, the SelectBase.subquery() method provides clearer semantics.

      New in version 1.4.

    • method suffix_with(*suffixes: _TextCoercedExpressionArgument[Any], dialect: str = ‘*‘) → SelfHasSuffixes

      inherited from the HasSuffixes.suffix_with() method of

      Add one or more expressions following the statement as a whole.

      This is used to support backend-specific suffix keywords on certain constructs.

      E.g.:

      1. stmt = select(col1, col2).cte().suffix_with(
      2. "cycle empno set y_cycle to 1 default 0", dialect="oracle")

      Multiple suffixes can be specified by multiple calls to HasSuffixes.suffix_with().

      • Parameters:

        • *suffixes – textual or construct which will be rendered following the target clause.

        • dialect – Optional string dialect name which will limit rendering of this suffix to only that dialect.

    • method sqlalchemy.sql.expression.Select.union(*other: _SelectStatementForCompoundArgument) →

      Return a SQL UNION of this select() construct against the given selectables provided as positional arguments.

      • Parameters:

        • *other

          one or more elements with which to create a UNION.

          Changed in version 1.4.28: multiple elements are now accepted.

        • **kwargs – keyword arguments are forwarded to the constructor for the newly created CompoundSelect object.

    • method union_all(*other: _SelectStatementForCompoundArgument) → CompoundSelect

      Return a SQL UNION ALL of this select() construct against the given selectables provided as positional arguments.

      • Parameters:

        • *other

          one or more elements with which to create a UNION.

          Changed in version 1.4.28: multiple elements are now accepted.

        • **kwargs – keyword arguments are forwarded to the constructor for the newly created object.

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

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

    • attribute sqlalchemy.sql.expression.Select.whereclause

      Return the completed WHERE clause for this statement.

      This assembles the current collection of WHERE criteria into a single BooleanClauseList construct.

      New in version 1.4.

    • method sqlalchemy.sql.expression.Select.with_for_update(*, nowait: bool = False, read: bool = False, of: Optional[_ForUpdateOfArgument] = None, skip_locked: bool = False, key_share: bool = False) → SelfGenerativeSelect

      inherited from the method of GenerativeSelect

      Specify a FOR UPDATE clause for this .

      E.g.:

      1. stmt = select(table).with_for_update(nowait=True)

      On a database like PostgreSQL or Oracle, the above would render a statement like:

      1. SELECT table.a, table.b FROM table FOR UPDATE NOWAIT

      on other backends, the nowait option is ignored and instead would produce:

      1. SELECT table.a, table.b FROM table FOR UPDATE

      When called with no arguments, the statement will render with the suffix FOR UPDATE. Additional arguments can then be provided which allow for common database-specific variants.

      • Parameters:

        • nowait – boolean; will render FOR UPDATE NOWAIT on Oracle and PostgreSQL dialects.

        • of – SQL expression or list of SQL expression elements, (typically Column objects or a compatible expression, for some backends may also be a table expression) which will render into a FOR UPDATE OF clause; supported by PostgreSQL, Oracle, some MySQL versions and possibly others. May render as a table or as a column depending on backend.

        • skip_locked – boolean, will render FOR UPDATE SKIP LOCKED on Oracle and PostgreSQL dialects or FOR SHARE SKIP LOCKED if read=True is also specified.

        • key_share – boolean, will render FOR NO KEY UPDATE, or if combined with read=True will render FOR KEY SHARE, on the PostgreSQL dialect.

    • method with_hint(selectable: _FromClauseArgument, text: str, dialect_name: str = ‘*‘) → SelfHasHints

      inherited from the HasHints.with_hint() method of HasHints

      Add an indexing or other executional context hint for the given selectable to this Select or other selectable object.

      The text of the hint is rendered in the appropriate location for the database backend in use, relative to the given or Alias passed as the selectable argument. The dialect implementation typically uses Python string substitution syntax with the token %(name)s to render the name of the table or alias. E.g. when using Oracle, the following:

      1. select(mytable).\
      2. with_hint(mytable, "index(%(name)s ix_mytable)")

      Would render SQL as:

      1. select /*+ index(mytable ix_mytable) */ ... from mytable

      The dialect_name option will limit the rendering of a particular hint to a particular backend. Such as, to add hints for both Oracle and Sybase simultaneously:

      1. select(mytable).\
      2. with_hint(mytable, "index(%(name)s ix_mytable)", 'oracle').\
      3. with_hint(mytable, "WITH INDEX ix_mytable", 'mssql')

      See also

    • method sqlalchemy.sql.expression.Select.with_only_columns(*entities: _ColumnsClauseArgument[Any], maintain_column_froms: bool = False, **_Select\_kw: Any_) → [Any]

      Return a new select() construct with its columns clause replaced with the given entities.

      By default, this method is exactly equivalent to as if the original had been called with the given entities. E.g. a statement:

      1. s = select(table1.c.a, table1.c.b)
      2. s = s.with_only_columns(table1.c.b)

      should be exactly equivalent to:

      1. s = select(table1.c.b)

      In this mode of operation, Select.with_only_columns() will also dynamically alter the FROM clause of the statement if it is not explicitly stated. To maintain the existing set of FROMs including those implied by the current columns clause, add the parameter:

      1. s = select(table1.c.a, table2.c.b)
      2. s = s.with_only_columns(table1.c.a, maintain_column_froms=True)

      The above parameter performs a transfer of the effective FROMs in the columns collection to the Select.select_from() method, as though the following were invoked:

      1. s = select(table1.c.a, table2.c.b)
      2. s = s.select_from(table1, table2).with_only_columns(table1.c.a)

      The parameter makes use of the Select.columns_clause_froms collection and performs an operation equivalent to the following:

      • Parameters:

        • *entities – column expressions to be used.

        • maintain_column_froms

          boolean parameter that will ensure the FROM list implied from the current columns clause will be transferred to the method first.

          New in version 1.4.23.

    • method sqlalchemy.sql.expression.Select.with_statement_hint(text: str, dialect_name: str = ‘*‘) → SelfHasHints

      inherited from the HasHints.with_statement_hint() method of HasHints

      Add a statement hint to this or other selectable object.

      This method is similar to Select.with_hint() except that it does not require an individual table, and instead applies to the statement as a whole.

      Hints here are specific to the backend database and may include directives such as isolation levels, file directives, fetch directives, etc.

      New in version 1.0.0.

      See also

      Select.prefix_with() - generic SELECT prefixing which also can suit some database-specific HINT syntaxes such as MySQL optimizer hints

    class sqlalchemy.sql.expression.Selectable

    Mark a class as being selectable.

    Members

    , exported_columns, , is_derived_from(), , replace_selectable()

    Class signature

    class (sqlalchemy.sql.expression.ReturnsRows)

    • method corresponding_column(column: KeyedColumnElement[Any], require_embedded: bool = False) → Optional[KeyedColumnElement[Any]]

      Given a ColumnElement, return the exported object from the Selectable.exported_columns collection of this which corresponds to that original ColumnElement via a common ancestor column.

      • Parameters:

        • column – the target to be matched.

        • require_embedded – only return corresponding columns for the given ColumnElement, if the given is actually present within a sub-element of this Selectable. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this .

    1. See also
    2. [Selectable.exported\_columns](#sqlalchemy.sql.expression.Selectable.exported_columns "sqlalchemy.sql.expression.Selectable.exported_columns") - the [ColumnCollection]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnCollection "sqlalchemy.sql.expression.ColumnCollection") that is used for the operation.
    3. [ColumnCollection.corresponding\_column()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnCollection.corresponding_column "sqlalchemy.sql.expression.ColumnCollection.corresponding_column") - implementation method.
    • attribute sqlalchemy.sql.expression.Selectable.exported_columns

      inherited from the attribute of ReturnsRows

      A that represents the “exported” columns of this ReturnsRows.

      The “exported” columns represent the collection of expressions that are rendered by this SQL construct. There are primary varieties which are the “FROM clause columns” of a FROM clause, such as a table, join, or subquery, the “SELECTed columns”, which are the columns in the “columns clause” of a SELECT statement, and the RETURNING columns in a DML statement..

      New in version 1.4.

      See also

      FromClause.exported_columns

    • attribute sqlalchemy.sql.expression.Selectable.inherit_cache: Optional[bool] = None

      inherited from the HasCacheKey.inherit_cache attribute of

      Indicate if this HasCacheKey instance should make use of the cache key generation scheme used by its immediate superclass.

      The attribute defaults to None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value to False, except that a warning is also emitted.

      This flag can be set to True on a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.

      See also

      - General guideslines for setting the HasCacheKey.inherit_cache attribute for third-party or user defined SQL constructs.

    • method is_derived_from(fromclause: Optional[FromClause]) → bool

      inherited from the method of ReturnsRows

      Return True if this is ‘derived’ from the given FromClause.

      An example would be an Alias of a Table is derived from that Table.

    • method lateral(name: Optional[str] = None) → LateralFromClause

      Return a LATERAL alias of this Selectable.

      The return value is the construct also provided by the top-level lateral() function.

      New in version 1.1.

      See also

      - overview of usage.

    • method sqlalchemy.sql.expression.Selectable.replace_selectable(old: , alias: Alias) → SelfSelectable

      Replace all occurrences of ‘old’ with the given Alias object, returning a copy of this .

      Deprecated since version 1.4: The Selectable.replace_selectable() method is deprecated, and will be removed in a future release. Similar functionality is available via the sqlalchemy.sql.visitors module.

    class sqlalchemy.sql.expression.SelectBase

    Base class for SELECT statements.

    This includes , CompoundSelect and .

    Members

    add_cte(), , as_scalar(), , corresponding_column(), , exists(), , get_label_style(), , is_derived_from(), , lateral(), , scalar_subquery(), , selected_columns, , subquery()

    Class signature

    class (sqlalchemy.sql.roles.SelectStatementRole, sqlalchemy.sql.roles.DMLSelectRole, sqlalchemy.sql.roles.CompoundElementRole, sqlalchemy.sql.roles.InElementRole, sqlalchemy.sql.expression.HasCTE, sqlalchemy.sql.annotation.SupportsCloneAnnotations, )

    • method sqlalchemy.sql.expression.SelectBase.add_cte(*ctes: , nest_here: bool = False) → SelfHasCTE

      inherited from the HasCTE.add_cte() method of

      Add one or more CTE constructs to this statement.

      This method will associate the given constructs with the parent statement such that they will each be unconditionally rendered in the WITH clause of the final statement, even if not referenced elsewhere within the statement or any sub-selects.

      The optional HasCTE.add_cte.nest_here parameter when set to True will have the effect that each given will render in a WITH clause rendered directly along with this statement, rather than being moved to the top of the ultimate rendered statement, even if this statement is rendered as a subquery within a larger statement.

      This method has two general uses. One is to embed CTE statements that serve some purpose without being referenced explicitly, such as the use case of embedding a DML statement such as an INSERT or UPDATE as a CTE inline with a primary statement that may draw from its results indirectly. The other is to provide control over the exact placement of a particular series of CTE constructs that should remain rendered directly in terms of a particular statement that may be nested in a larger statement.

      E.g.:

      1. from sqlalchemy import table, column, select
      2. t = table('t', column('c1'), column('c2'))
      3. ins = t.insert().values({"c1": "x", "c2": "y"}).cte()
      4. stmt = select(t).add_cte(ins)

      Would render:

      1. WITH anon_1 AS
      2. (INSERT INTO t (c1, c2) VALUES (:param_1, :param_2))
      3. SELECT t.c1, t.c2
      4. FROM t

      Above, the “anon_1” CTE is not referred towards in the SELECT statement, however still accomplishes the task of running an INSERT statement.

      Similarly in a DML-related context, using the PostgreSQL Insert construct to generate an “upsert”:

      1. from sqlalchemy import table, column
      2. from sqlalchemy.dialects.postgresql import insert
      3. t = table("t", column("c1"), column("c2"))
      4. delete_statement_cte = (
      5. t.delete().where(t.c.c1 < 1).cte("deletions")
      6. )
      7. insert_stmt = insert(t).values({"c1": 1, "c2": 2})
      8. update_statement = insert_stmt.on_conflict_do_update(
      9. index_elements=[t.c.c1],
      10. set_={
      11. "c1": insert_stmt.excluded.c1,
      12. "c2": insert_stmt.excluded.c2,
      13. },
      14. ).add_cte(delete_statement_cte)
      15. print(update_statement)

      The above statement renders as:

      1. WITH deletions AS
      2. (DELETE FROM t WHERE t.c1 < %(c1_1)s)
      3. INSERT INTO t (c1, c2) VALUES (%(c1)s, %(c2)s)
      4. ON CONFLICT (c1) DO UPDATE SET c1 = excluded.c1, c2 = excluded.c2

      New in version 1.4.21.

      • Parameters:

        • *ctes

          zero or more constructs.

          Changed in version 2.0: Multiple CTE instances are accepted

        • nest_here

          if True, the given CTE or CTEs will be rendered as though they specified the HasCTE.cte.nesting flag to True when they were added to this . Assuming the given CTEs are not referenced in an outer-enclosing statement as well, the CTEs given should render at the level of this statement when this flag is given.

          New in version 2.0.

          See also

          HasCTE.cte.nesting

    • method alias(name: Optional[str] = None, flat: bool = False) → Subquery

      Return a named subquery against this .

      For a SelectBase (as opposed to a ), this returns a Subquery object which behaves mostly the same as the object that is used with a FromClause.

      Changed in version 1.4: The method is now a synonym for the SelectBase.subquery() method.

    • method as_scalar() → ScalarSelect[Any]

      Deprecated since version 1.4: The method is deprecated and will be removed in a future release. Please refer to SelectBase.scalar_subquery().

    • attribute c

      Deprecated since version 1.4: The SelectBase.c and SelectBase.columns attributes are deprecated and will be removed in a future release; these attributes implicitly create a subquery that should be explicit. Please call first in order to create a subquery, which then contains this attribute. To access the columns that this SELECT object SELECTs from, use the SelectBase.selected_columns attribute.

    • method corresponding_column(column: KeyedColumnElement[Any], require_embedded: bool = False) → Optional[KeyedColumnElement[Any]]

      inherited from the Selectable.corresponding_column() method of

      Given a ColumnElement, return the exported object from the Selectable.exported_columns collection of this which corresponds to that original ColumnElement via a common ancestor column.

      • Parameters:

        • column – the target to be matched.

        • require_embedded – only return corresponding columns for the given ColumnElement, if the given is actually present within a sub-element of this Selectable. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this .

    1. See also
    2. [Selectable.exported\_columns](#sqlalchemy.sql.expression.Selectable.exported_columns "sqlalchemy.sql.expression.Selectable.exported_columns") - the [ColumnCollection]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnCollection "sqlalchemy.sql.expression.ColumnCollection") that is used for the operation.
    3. [ColumnCollection.corresponding\_column()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnCollection.corresponding_column "sqlalchemy.sql.expression.ColumnCollection.corresponding_column") - implementation method.
    • method sqlalchemy.sql.expression.SelectBase.cte(name: Optional[str] = None, recursive: bool = False, nesting: bool = False) →

      inherited from the HasCTE.cte() method of

      Return a new CTE, or Common Table Expression instance.

      Common table expressions are a SQL standard whereby SELECT statements can draw upon secondary statements specified along with the primary statement, using a clause called “WITH”. Special semantics regarding UNION can also be employed to allow “recursive” queries, where a SELECT statement can draw upon the set of rows that have previously been selected.

      CTEs can also be applied to DML constructs UPDATE, INSERT and DELETE on some databases, both as a source of CTE rows when combined with RETURNING, as well as a consumer of CTE rows.

      Changed in version 1.1: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.

      SQLAlchemy detects objects, which are treated similarly to Alias objects, as special elements to be delivered to the FROM clause of the statement as well as to a WITH clause at the top of the statement.

      For special prefixes such as PostgreSQL “MATERIALIZED” and “NOT MATERIALIZED”, the CTE.prefix_with() method may be used to establish these.

      Changed in version 1.3.13: Added support for prefixes. In particular - MATERIALIZED and NOT MATERIALIZED.

      • Parameters:

        • name – name given to the common table expression. Like , the name can be left as None in which case an anonymous symbol will be used at query compile time.

        • recursive – if True, will render WITH RECURSIVE. A recursive common table expression is intended to be used in conjunction with UNION ALL in order to derive rows from those already selected.

        • nesting

          if True, will render the CTE locally to the statement in which it is referenced. For more complex scenarios, the HasCTE.add_cte() method using the parameter may also be used to more carefully control the exact placement of a particular CTE.

          New in version 1.4.24.

          See also

          HasCTE.add_cte()

    1. The following examples include two from PostgreSQLs documentation at [https://www.postgresql.org/docs/current/static/queries-with.html](https://www.postgresql.org/docs/current/static/queries-with.html), as well as additional examples.
    2. Example 1, non recursive:
    3. ```
    4. from sqlalchemy import (Table, Column, String, Integer,
    5. MetaData, select, func)
    6. metadata = MetaData()
    7. orders = Table('orders', metadata,
    8. Column('region', String),
    9. Column('amount', Integer),
    10. Column('product', String),
    11. Column('quantity', Integer)
    12. )
    13. regional_sales = select(
    14. orders.c.region,
    15. func.sum(orders.c.amount).label('total_sales')
    16. ).group_by(orders.c.region).cte("regional_sales")
    17. top_regions = select(regional_sales.c.region).\
    18. where(
    19. regional_sales.c.total_sales >
    20. func.sum(regional_sales.c.total_sales) / 10
    21. )
    22. statement = select(
    23. orders.c.region,
    24. orders.c.product,
    25. func.sum(orders.c.quantity).label("product_units"),
    26. func.sum(orders.c.amount).label("product_sales")
    27. ).where(orders.c.region.in_(
    28. select(top_regions.c.region)
    29. )).group_by(orders.c.region, orders.c.product)
    30. result = conn.execute(statement).fetchall()
    31. ```
    32. Example 2, WITH RECURSIVE:
    33. ```
    34. from sqlalchemy import (Table, Column, String, Integer,
    35. MetaData, select, func)
    36. metadata = MetaData()
    37. parts = Table('parts', metadata,
    38. Column('part', String),
    39. Column('sub_part', String),
    40. Column('quantity', Integer),
    41. )
    42. included_parts = select(\
    43. parts.c.sub_part, parts.c.part, parts.c.quantity\
    44. ).\
    45. where(parts.c.part=='our part').\
    46. cte(recursive=True)
    47. incl_alias = included_parts.alias()
    48. parts_alias = parts.alias()
    49. included_parts = included_parts.union_all(
    50. select(
    51. parts_alias.c.sub_part,
    52. parts_alias.c.part,
    53. parts_alias.c.quantity
    54. ).\
    55. where(parts_alias.c.part==incl_alias.c.sub_part)
    56. )
    57. statement = select(
    58. included_parts.c.sub_part,
    59. func.sum(included_parts.c.quantity).
    60. label('total_quantity')
    61. ).\
    62. group_by(included_parts.c.sub_part)
    63. result = conn.execute(statement).fetchall()
    64. ```
    65. Example 3, an upsert using UPDATE and INSERT with CTEs:
    66. ```
    67. from datetime import date
    68. from sqlalchemy import (MetaData, Table, Column, Integer,
    69. Date, select, literal, and_, exists)
    70. metadata = MetaData()
    71. visitors = Table('visitors', metadata,
    72. Column('product_id', Integer, primary_key=True),
    73. Column('date', Date, primary_key=True),
    74. Column('count', Integer),
    75. )
    76. # add 5 visitors for the product_id == 1
    77. product_id = 1
    78. day = date.today()
    79. count = 5
    80. update_cte = (
    81. visitors.update()
    82. .where(and_(visitors.c.product_id == product_id,
    83. visitors.c.date == day))
    84. .values(count=visitors.c.count + count)
    85. .returning(literal(1))
    86. .cte('update_cte')
    87. )
    88. upsert = visitors.insert().from_select(
    89. [visitors.c.product_id, visitors.c.date, visitors.c.count],
    90. select(literal(product_id), literal(day), literal(count))
    91. .where(~exists(update_cte.select()))
    92. )
    93. connection.execute(upsert)
    94. ```
    95. Example 4, Nesting CTE (SQLAlchemy 1.4.24 and above):
    96. ```
    97. value_a = select(
    98. literal("root").label("n")
    99. ).cte("value_a")
    100. # A nested CTE with the same name as the root one
    101. value_a_nested = select(
    102. literal("nesting").label("n")
    103. ).cte("value_a", nesting=True)
    104. # Nesting CTEs takes ascendency locally
    105. # over the CTEs at a higher level
    106. value_b = select(value_a_nested.c.n).cte("value_b")
    107. value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
    108. ```
    109. The above query will render the second CTE nested inside the first, shown with inline parameters below as:
    110. ```
    111. WITH
    112. value_a AS
    113. (SELECT 'root' AS n),
    114. value_b AS
    115. (WITH value_a AS
    116. (SELECT 'nesting' AS n)
    117. SELECT value_a.n AS n FROM value_a)
    118. SELECT value_a.n AS a, value_b.n AS b
    119. FROM value_a, value_b
    120. ```
    121. The same CTE can be set up using the [HasCTE.add\_cte()](#sqlalchemy.sql.expression.HasCTE.add_cte "sqlalchemy.sql.expression.HasCTE.add_cte") method as follows (SQLAlchemy 2.0 and above):
    122. ```
    123. value_a = select(
    124. literal("root").label("n")
    125. ).cte("value_a")
    126. # A nested CTE with the same name as the root one
    127. value_a_nested = select(
    128. literal("nesting").label("n")
    129. ).cte("value_a")
    130. # Nesting CTEs takes ascendency locally
    131. # over the CTEs at a higher level
    132. value_b = (
    133. select(value_a_nested.c.n).
    134. add_cte(value_a_nested, nest_here=True).
    135. cte("value_b")
    136. )
    137. value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
    138. ```
    139. Example 5, Non-Linear CTE (SQLAlchemy 1.4.28 and above):
    140. ```
    141. edge = Table(
    142. "edge",
    143. metadata,
    144. Column("id", Integer, primary_key=True),
    145. Column("left", Integer),
    146. Column("right", Integer),
    147. )
    148. root_node = select(literal(1).label("node")).cte(
    149. "nodes", recursive=True
    150. )
    151. left_edge = select(edge.c.left).join(
    152. root_node, edge.c.right == root_node.c.node
    153. )
    154. right_edge = select(edge.c.right).join(
    155. root_node, edge.c.left == root_node.c.node
    156. )
    157. subgraph_cte = root_node.union(left_edge, right_edge)
    158. subgraph = select(subgraph_cte)
    159. ```
    160. The above query will render 2 UNIONs inside the recursive CTE:
    161. ```
    162. WITH RECURSIVE nodes(node) AS (
    163. SELECT 1 AS node
    164. UNION
    165. SELECT edge."left" AS "left"
    166. FROM edge JOIN nodes ON edge."right" = nodes.node
    167. UNION
    168. SELECT edge."right" AS "right"
    169. FROM edge JOIN nodes ON edge."left" = nodes.node
    170. )
    171. SELECT nodes.node FROM nodes
    172. ```
    173. See also
    174. [Query.cte()]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query.cte "sqlalchemy.orm.Query.cte") - ORM version of [HasCTE.cte()](#sqlalchemy.sql.expression.HasCTE.cte "sqlalchemy.sql.expression.HasCTE.cte").
    • method exists() → Exists

      Return an representation of this selectable, which can be used as a column expression.

      The returned object is an instance of Exists.

      See also

      EXISTS subqueries - in the tutorial.

      New in version 1.4.

    • attribute sqlalchemy.sql.expression.SelectBase.exported_columns

      A that represents the “exported” columns of this Selectable, not including constructs.

      The “exported” columns for a SelectBase object are synonymous with the collection.

      New in version 1.4.

      See also

      Select.exported_columns

      FromClause.exported_columns

    • method get_label_style() → SelectLabelStyle

      Retrieve the current label style.

      Implemented by subclasses.

    • attribute inherit_cache: Optional[bool] = None

      inherited from the HasCacheKey.inherit_cache attribute of HasCacheKey

      Indicate if this instance should make use of the cache key generation scheme used by its immediate superclass.

      The attribute defaults to None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value to False, except that a warning is also emitted.

      This flag can be set to True on a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.

      See also

      Enabling Caching Support for Custom Constructs - General guideslines for setting the attribute for third-party or user defined SQL constructs.

    • method sqlalchemy.sql.expression.SelectBase.is_derived_from(fromclause: Optional[]) → bool

      inherited from the ReturnsRows.is_derived_from() method of

      Return True if this ReturnsRows is ‘derived’ from the given .

      An example would be an Alias of a Table is derived from that Table.

    • method sqlalchemy.sql.expression.SelectBase.label(name: Optional[str]) → [Any]

      Return a ‘scalar’ representation of this selectable, embedded as a subquery with a label.

      See also

      SelectBase.as_scalar().

    • method lateral(name: Optional[str] = None) → LateralFromClause

      Return a LATERAL alias of this Selectable.

      The return value is the construct also provided by the top-level lateral() function.

      New in version 1.1.

      See also

      - overview of usage.

    • method sqlalchemy.sql.expression.SelectBase.replace_selectable(old: , alias: Alias) → SelfSelectable

      inherited from the method of Selectable

      Replace all occurrences of ‘old’ with the given Alias object, returning a copy of this .

      Deprecated since version 1.4: The Selectable.replace_selectable() method is deprecated, and will be removed in a future release. Similar functionality is available via the sqlalchemy.sql.visitors module.

    • method scalar_subquery() → ScalarSelect[Any]

      Return a ‘scalar’ representation of this selectable, which can be used as a column expression.

      The returned object is an instance of .

      Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression. The scalar subquery can then be used in the WHERE clause or columns clause of an enclosing SELECT.

      Note that the scalar subquery differentiates from the FROM-level subquery that can be produced using the SelectBase.subquery() method.

      See also

      - in the 2.0 tutorial

    • method sqlalchemy.sql.expression.SelectBase.select(*arg: Any, **kw: Any) →

      Deprecated since version 1.4: The SelectBase.select() method is deprecated and will be removed in a future release; this method implicitly creates a subquery that should be explicit. Please call first in order to create a subquery, which then can be selected.

    • attribute sqlalchemy.sql.expression.SelectBase.selected_columns

      A representing the columns that this SELECT statement or similar construct returns in its result set.

      This collection differs from the FromClause.columns collection of a in that the columns within this collection cannot be directly nested inside another SELECT statement; a subquery must be applied first which provides for the necessary parenthesization required by SQL.

      Note

      The SelectBase.selected_columns collection does not include expressions established in the columns clause using the construct; these are silently omitted from the collection. To use plain textual column expressions inside of a Select construct, use the construct.

      See also

      Select.selected_columns

      New in version 1.4.

    • method set_label_style(style: SelectLabelStyle) → SelfSelectBase

      Return a new selectable with the specified label style.

      Implemented by subclasses.

    • method subquery(name: Optional[str] = None) → Subquery

      Return a subquery of this .

      A subquery is from a SQL perspective a parenthesized, named construct that can be placed in the FROM clause of another SELECT statement.

      Given a SELECT statement such as:

      1. stmt = select(table.c.id, table.c.name)

      The above statement might look like:

      1. SELECT table.id, table.name FROM table

      The subquery form by itself renders the same way, however when embedded into the FROM clause of another SELECT statement, it becomes a named sub-element:

      1. subq = stmt.subquery()
      2. new_stmt = select(subq)

      The above renders as:

      1. SELECT anon_1.id, anon_1.name
      2. FROM (SELECT table.id, table.name FROM table) AS anon_1

      Historically, SelectBase.subquery() is equivalent to calling the method on a FROM object; however, as a SelectBase object is not directly FROM object, the method provides clearer semantics.

      New in version 1.4.

    class sqlalchemy.sql.expression.Subquery

    Represent a subquery of a SELECT.

    A Subquery is created by invoking the method, or for convenience the SelectBase.alias() method, on any subclass which includes Select, , and TextualSelect. As rendered in a FROM clause, it represents the body of the SELECT statement inside of parenthesis, followed by the usual “AS <somename>” that defines all “alias” objects.

    The object is very similar to the Alias object and can be used in an equivalent way. The difference between and Subquery is that always contains a FromClause object whereas always contains a SelectBase object.

    New in version 1.4: The class was added which now serves the purpose of providing an aliased version of a SELECT statement.

    Members

    as_scalar(),

    Class signature

    class sqlalchemy.sql.expression.Subquery ()

    • method sqlalchemy.sql.expression.Subquery.as_scalar() → [Any]

      Deprecated since version 1.4: The Subquery.as_scalar() method, which was previously Alias.as_scalar() prior to version 1.4, is deprecated and will be removed in a future release; Please use the method of the select() construct before constructing a subquery object, or with the ORM use the method.

    • attribute sqlalchemy.sql.expression.Subquery.inherit_cache: Optional[bool] = True

      Indicate if this instance should make use of the cache key generation scheme used by its immediate superclass.

      The attribute defaults to None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value to False, except that a warning is also emitted.

      This flag can be set to True on a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.

      See also

      Enabling Caching Support for Custom Constructs - General guideslines for setting the attribute for third-party or user defined SQL constructs.

    class sqlalchemy.sql.expression.TableClause

    Represents a minimal “table” construct.

    This is a lightweight table object that has only a name, a collection of columns, which are typically produced by the column() function, and a schema:

    1. from sqlalchemy import table, column
    2. user = table("user",
    3. column("id"),
    4. column("name"),
    5. column("description"),
    6. )

    The construct serves as the base for the more commonly used Table object, providing the usual set of services including the .c. collection and statement generation methods.

    It does not provide all the additional schema-level services of Table, including constraints, references to other tables, or support for -level services. It’s useful on its own as an ad-hoc construct used to generate quick SQL statements when a more fully fledged Table is not on hand.

    Members

    , c, , compare(), , corresponding_column(), , description, , exported_columns, , get_children(), , inherit_cache, , is_derived_from(), , lateral(), , params(), , replace_selectable(), , select(), , table_valued(), , unique_params(),

    Class signature

    class sqlalchemy.sql.expression.TableClause (sqlalchemy.sql.roles.DMLTableRole, sqlalchemy.sql.expression.Immutable, sqlalchemy.sql.expression.NamedFromClause)

    • method alias(name: Optional[str] = None, flat: bool = False) → NamedFromClause

      inherited from the FromClause.alias() method of

      Return an alias of this FromClause.

      E.g.:

      1. a2 = some_table.alias('a2')

      The above code creates an object which can be used as a FROM clause in any SELECT statement.

      See also

      Using Aliases

    • attribute sqlalchemy.sql.expression.TableClause.c

      inherited from the attribute of FromClause

      A synonym for

    • attribute columns

      inherited from the FromClause.columns attribute of

      A named-based collection of ColumnElement objects maintained by this .

      The columns, or collection, is the gateway to the construction of SQL expressions using table-bound or other selectable-bound columns:

      1. select(mytable).where(mytable.c.somecolumn == 5)
    • method compare(other: ClauseElement, **kw: Any) → bool

      inherited from the method of ClauseElement

      Compare this to the given ClauseElement.

      Subclasses should override the default behavior, which is a straight identity comparison.

      **kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison (see ).

    • method sqlalchemy.sql.expression.TableClause.compile(bind: Optional[Union[, Connection]] = None, dialect: Optional[] = None, **kw: Any) → Compiled

      inherited from the CompilerElement.compile() method of CompilerElement

      Compile this SQL expression.

      The return value is a object. Calling str() or unicode() on the returned value will yield a string representation of the result. The Compiled object also can return a dictionary of bind parameter names and values using the params accessor.

      • Parameters:

        • bind – An or Engine which can provide a in order to generate a Compiled object. If the bind and dialect parameters are both omitted, a default SQL compiler is used.

        • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.

        • dialect – A instance which can generate a Compiled object. This argument takes precedence over the bind argument.

        • compile_kwargs

          optional dictionary of additional parameters that will be passed through to the compiler within all “visit” methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the literal_binds flag through:

          1. from sqlalchemy.sql import table, column, select
          2. t = table('t', column('x'))
          3. s = select(t).where(t.c.x == 5)
          4. print(s.compile(compile_kwargs={"literal_binds": True}))

          New in version 0.9.0.

    1. See also
    2. [How do I render SQL expressions as strings, possibly with bound parameters inlined?]($e9fd44a49fe37bbb.md#faq-sql-expression-string)
    • method corresponding_column(column: KeyedColumnElement[Any], require_embedded: bool = False) → Optional[KeyedColumnElement[Any]]

      inherited from the Selectable.corresponding_column() method of

      Given a ColumnElement, return the exported object from the Selectable.exported_columns collection of this which corresponds to that original ColumnElement via a common ancestor column.

      • Parameters:

        • column – the target to be matched.

        • require_embedded – only return corresponding columns for the given ColumnElement, if the given is actually present within a sub-element of this Selectable. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this .

    1. See also
    2. [Selectable.exported\_columns](#sqlalchemy.sql.expression.Selectable.exported_columns "sqlalchemy.sql.expression.Selectable.exported_columns") - the [ColumnCollection]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnCollection "sqlalchemy.sql.expression.ColumnCollection") that is used for the operation.
    3. [ColumnCollection.corresponding\_column()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnCollection.corresponding_column "sqlalchemy.sql.expression.ColumnCollection.corresponding_column") - implementation method.
    • method sqlalchemy.sql.expression.TableClause.delete() →

      Generate a delete() construct against this .

      E.g.:

      1. table.delete().where(table.c.id==7)

      See delete() for argument and usage information.

    • attribute description

    • attribute sqlalchemy.sql.expression.TableClause.entity_namespace

      inherited from the attribute of FromClause

      Return a namespace used for name-based access in SQL expressions.

      This is the namespace that is used to resolve “filter_by()” type expressions, such as:

      1. stmt.filter_by(address='some address')

      It defaults to the .c collection, however internally it can be overridden using the “entity_namespace” annotation to deliver alternative results.

    • attribute exported_columns

      inherited from the FromClause.exported_columns attribute of

      A ColumnCollection that represents the “exported” columns of this .

      The “exported” columns for a FromClause object are synonymous with the collection.

      New in version 1.4.

      See also

      Selectable.exported_columns

    • attribute sqlalchemy.sql.expression.TableClause.foreign_keys

      inherited from the attribute of FromClause

      Return the collection of marker objects which this FromClause references.

      Each ForeignKey is a member of a -wide ForeignKeyConstraint.

      See also

    • method sqlalchemy.sql.expression.TableClause.get_children(*, omit_attrs: Tuple[str, …] = (), **kw: Any) → Iterable[HasTraverseInternals]

      inherited from the HasTraverseInternals.get_children() method of HasTraverseInternals

      Return immediate child HasTraverseInternals elements of this HasTraverseInternals.

      This is used for visit traversal.

      **kw may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).

    • attribute implicit_returning = False

      TableClause doesn’t support having a primary key or column -level defaults, so implicit returning doesn’t apply.

    • attribute inherit_cache: Optional[bool] = None

      inherited from the HasCacheKey.inherit_cache attribute of HasCacheKey

      Indicate if this instance should make use of the cache key generation scheme used by its immediate superclass.

      The attribute defaults to None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value to False, except that a warning is also emitted.

      This flag can be set to True on a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.

      See also

      Enabling Caching Support for Custom Constructs - General guideslines for setting the attribute for third-party or user defined SQL constructs.

    • method sqlalchemy.sql.expression.TableClause.insert() →

      Generate an Insert construct against this .

      E.g.:

      1. table.insert().values(name='foo')

      See insert() for argument and usage information.

    • method is_derived_from(fromclause: Optional[FromClause]) → bool

      inherited from the method of FromClause

      Return True if this is ‘derived’ from the given FromClause.

      An example would be an Alias of a Table is derived from that Table.

    • method sqlalchemy.sql.expression.TableClause.join(right: _FromClauseArgument, onclause: Optional[_ColumnExpressionArgument[bool]] = None, isouter: bool = False, full: bool = False) →

      inherited from the FromClause.join() method of

      Return a Join from this to another FromClause.

      E.g.:

      1. from sqlalchemy import join
      2. j = user_table.join(address_table,
      3. user_table.c.id == address_table.c.user_id)
      4. stmt = select(user_table).select_from(j)

      would emit SQL along the lines of:

      1. SELECT user.id, user.name FROM user
      2. JOIN address ON user.id = address.user_id
      • Parameters:

        • right – the right side of the join; this is any object such as a Table object, and may also be a selectable-compatible object such as an ORM-mapped class.

        • onclause – a SQL expression representing the ON clause of the join. If left at None, will attempt to join the two tables based on a foreign key relationship.

        • isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.

        • full

          if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. Implies FromClause.join.isouter.

          New in version 1.1.

    1. See also
    2. [join()](#sqlalchemy.sql.expression.join "sqlalchemy.sql.expression.join") - standalone function
    3. [Join](#sqlalchemy.sql.expression.Join "sqlalchemy.sql.expression.Join") - the type of object produced
    • method lateral(name: Optional[str] = None) → LateralFromClause

      inherited from the Selectable.lateral() method of

      Return a LATERAL alias of this Selectable.

      The return value is the construct also provided by the top-level lateral() function.

      New in version 1.1.

      See also

      - overview of usage.

    • method sqlalchemy.sql.expression.TableClause.outerjoin(right: _FromClauseArgument, onclause: Optional[_ColumnExpressionArgument[bool]] = None, full: bool = False) →

      inherited from the FromClause.outerjoin() method of

      Return a Join from this to another FromClause, with the “isouter” flag set to True.

      E.g.:

      1. from sqlalchemy import outerjoin
      2. j = user_table.outerjoin(address_table,
      3. user_table.c.id == address_table.c.user_id)

      The above is equivalent to:

      1. j = user_table.join(
      2. address_table,
      3. user_table.c.id == address_table.c.user_id,
      4. isouter=True)
      • Parameters:

        • right – the right side of the join; this is any object such as a Table object, and may also be a selectable-compatible object such as an ORM-mapped class.

        • onclause – a SQL expression representing the ON clause of the join. If left at None, will attempt to join the two tables based on a foreign key relationship.

        • full

          if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN.

          New in version 1.1.

    1. See also
    2. [FromClause.join()](#sqlalchemy.sql.expression.FromClause.join "sqlalchemy.sql.expression.FromClause.join")
    3. [Join](#sqlalchemy.sql.expression.Join "sqlalchemy.sql.expression.Join")
    • method sqlalchemy.sql.expression.TableClause.params(*optionaldict, **kwargs)

      inherited from the Immutable.params() method of Immutable

      Return a copy with elements replaced.

      Returns a copy of this ClauseElement with bindparam() elements replaced with values taken from the given dictionary:

      1. >>> clause = column('x') + bindparam('foo')
      2. >>> print(clause.compile().params)
      3. {'foo':None}
      4. >>> print(clause.params({'foo':7}).compile().params)
      5. {'foo':7}
    • attribute primary_key

      inherited from the FromClause.primary_key attribute of

      Return the iterable collection of Column objects which comprise the primary key of this _selectable.FromClause.

      For a object, this collection is represented by the PrimaryKeyConstraint which itself is an iterable collection of objects.

    • method sqlalchemy.sql.expression.TableClause.replace_selectable(old: , alias: Alias) → SelfSelectable

      inherited from the method of Selectable

      Replace all occurrences of ‘old’ with the given Alias object, returning a copy of this .

      Deprecated since version 1.4: The Selectable.replace_selectable() method is deprecated, and will be removed in a future release. Similar functionality is available via the sqlalchemy.sql.visitors module.

    • attribute schema: Optional[str] = None

      inherited from the FromClause.schema attribute of

      Define the ‘schema’ attribute for this FromClause.

      This is typically None for most objects except that of , where it is taken as the value of the Table.schema argument.

    • method select() → Select

      inherited from the method of FromClause

      Return a SELECT of this .

      e.g.:

      1. stmt = some_table.select().where(some_table.c.id == 5)

      See also

      select() - general purpose method which allows for arbitrary column lists.

    • method self_group(against: Optional[OperatorType] = None) → ClauseElement

      inherited from the method of ClauseElement

      Apply a ‘grouping’ to this .

      This method is overridden by subclasses to return a “grouping” construct, i.e. parenthesis. In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by select() constructs when placed into the FROM clause of another . (Note that subqueries should be normally created using the Select.alias() method, as many platforms require nested SELECT statements to be named).

      As expressions are composed together, the application of is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression like x OR (y AND z) - AND takes precedence over OR.

      The base self_group() method of just returns self.

    • method sqlalchemy.sql.expression.TableClause.table_valued() → TableValuedColumn[Any]

      inherited from the NamedFromClause.table_valued() method of NamedFromClause

      Return a TableValuedColumn object for this .

      A TableValuedColumn is a ColumnElement that represents a complete row in a table. Support for this construct is backend dependent, and is supported in various forms by backends such as PostgreSQL, Oracle and SQL Server.

      E.g.:

      1. >>> from sqlalchemy import select, column, func, table
      2. >>> a = table("a", column("id"), column("x"), column("y"))
      3. >>> stmt = select(func.row_to_json(a.table_valued()))
      4. >>> print(stmt)
      5. SELECT row_to_json(a) AS row_to_json_1
      6. FROM a

      New in version 1.4.0b2.

      See also

      - in the SQLAlchemy Unified Tutorial

    • method tablesample(sampling: Union[float, Function[Any]], name: Optional[str] = None, seed: Optional[roles.ExpressionElementRole[Any]] = None) →

      inherited from the FromClause.tablesample() method of

      Return a TABLESAMPLE alias of this FromClause.

      The return value is the construct also provided by the top-level tablesample() function.

      New in version 1.1.

      See also

      - usage guidelines and parameters

    • method sqlalchemy.sql.expression.TableClause.unique_params(*optionaldict, **kwargs)

      inherited from the Immutable.unique_params() method of Immutable

      Return a copy with elements replaced.

      Same functionality as ClauseElement.params(), except adds unique=True to affected bind parameters so that multiple statements can be used.

    • method update() → Update

      Generate an construct against this TableClause.

      E.g.:

      1. table.update().where(table.c.id==7).values(name='foo')

      See for argument and usage information.

    class sqlalchemy.sql.expression.TableSample

    Represent a TABLESAMPLE clause.

    This object is constructed from the tablesample() module level function as well as the method available on all FromClause subclasses.

    New in version 1.1.

    See also

    Class signature

    class sqlalchemy.sql.expression.TableSample (sqlalchemy.sql.expression.FromClauseAlias)

    class sqlalchemy.sql.expression.TableValuedAlias

    An alias against a “table valued” SQL function.

    This construct provides for a SQL function that returns columns to be used in the FROM clause of a SELECT statement. The object is generated using the method, e.g.:

    1. >>> from sqlalchemy import select, func
    2. >>> fn = func.json_array_elements_text('["one", "two", "three"]').table_valued("value")
    3. >>> print(select(fn.c.value))
    4. SELECT anon_1.value
    5. FROM json_array_elements_text(:json_array_elements_text_1) AS anon_1

    New in version 1.4.0b2.

    See also

    Table-Valued Functions - in the

    Members

    alias(), , lateral(),

    Class signature

    class sqlalchemy.sql.expression.TableValuedAlias (sqlalchemy.sql.expression.LateralFromClause, )

    • method sqlalchemy.sql.expression.TableValuedAlias.alias(name: Optional[str] = None, flat: bool = False) →

      Return a new alias of this TableValuedAlias.

      This creates a distinct FROM object that will be distinguished from the original one when used in a SQL statement.

    • attribute column

      Return a column expression representing this TableValuedAlias.

      This accessor is used to implement the method. See that method for further details.

      E.g.:

      1. >>> print(select(func.some_func().table_valued("value").column))
      2. SELECT anon_1 FROM some_func() AS anon_1

      See also

      FunctionElement.column_valued()

    • method lateral(name: Optional[str] = None) → LateralFromClause

      Return a new TableValuedAlias with the lateral flag set, so that it renders as LATERAL.

      See also

    • method sqlalchemy.sql.expression.TableValuedAlias.render_derived(name: Optional[str] = None, with_types: bool = False) →

      Apply “render derived” to this TableValuedAlias.

      This has the effect of the individual column names listed out after the alias name in the “AS” sequence, e.g.:

      1. >>> print(
      2. ... select(
      3. ... func.unnest(array(["one", "two", "three"])).
      4. table_valued("x", with_ordinality="o").render_derived()
      5. ... )
      6. ... )
      7. SELECT anon_1.x, anon_1.o
      8. FROM unnest(ARRAY[%(param_1)s, %(param_2)s, %(param_3)s]) WITH ORDINALITY AS anon_1(x, o)

      The with_types keyword will render column types inline within the alias expression (this syntax currently applies to the PostgreSQL database):

      1. >>> print(
      2. ... select(
      3. ... func.json_to_recordset(
      4. ... '[{"a":1,"b":"foo"},{"a":"2","c":"bar"}]'
      5. ... )
      6. ... .table_valued(column("a", Integer), column("b", String))
      7. ... .render_derived(with_types=True)
      8. ... )
      9. ... )
      10. SELECT anon_1.a, anon_1.b FROM json_to_recordset(:json_to_recordset_1)
      11. AS anon_1(a INTEGER, b VARCHAR)
      • Parameters:

        • name – optional string name that will be applied to the alias generated. If left as None, a unique anonymizing name will be used.

        • with_types – if True, the derived columns will include the datatype specification with each column. This is a special syntax currently known to be required by PostgreSQL for some SQL functions.

    class sqlalchemy.sql.expression.TextualSelect

    Wrap a construct within a SelectBase interface.

    This allows the object to gain a .c collection and other FROM-like capabilities such as FromClause.alias(), , etc.

    The TextualSelect construct is produced via the method - see that method for details.

    Changed in version 1.4: the TextualSelect class was renamed from TextAsFrom, to more correctly suit its role as a SELECT-oriented object and not a FROM clause.

    See also

    TextClause.columns() - primary creation interface.

    Members

    , alias(), , c, , compile(), , cte(), , exists(), , get_children(), , get_label_style(), , is_derived_from(), , lateral(), , params(), , scalar_subquery(), , selected_columns, , set_label_style(), , unique_params()

    Class signature

    class (sqlalchemy.sql.expression.SelectBase, , sqlalchemy.sql.expression.Generative)

    • method sqlalchemy.sql.expression.TextualSelect.add_cte(*ctes: , nest_here: bool = False) → SelfHasCTE

      inherited from the HasCTE.add_cte() method of

      Add one or more CTE constructs to this statement.

      This method will associate the given constructs with the parent statement such that they will each be unconditionally rendered in the WITH clause of the final statement, even if not referenced elsewhere within the statement or any sub-selects.

      The optional HasCTE.add_cte.nest_here parameter when set to True will have the effect that each given will render in a WITH clause rendered directly along with this statement, rather than being moved to the top of the ultimate rendered statement, even if this statement is rendered as a subquery within a larger statement.

      This method has two general uses. One is to embed CTE statements that serve some purpose without being referenced explicitly, such as the use case of embedding a DML statement such as an INSERT or UPDATE as a CTE inline with a primary statement that may draw from its results indirectly. The other is to provide control over the exact placement of a particular series of CTE constructs that should remain rendered directly in terms of a particular statement that may be nested in a larger statement.

      E.g.:

      1. from sqlalchemy import table, column, select
      2. t = table('t', column('c1'), column('c2'))
      3. ins = t.insert().values({"c1": "x", "c2": "y"}).cte()
      4. stmt = select(t).add_cte(ins)

      Would render:

      1. WITH anon_1 AS
      2. (INSERT INTO t (c1, c2) VALUES (:param_1, :param_2))
      3. SELECT t.c1, t.c2
      4. FROM t

      Above, the “anon_1” CTE is not referred towards in the SELECT statement, however still accomplishes the task of running an INSERT statement.

      Similarly in a DML-related context, using the PostgreSQL Insert construct to generate an “upsert”:

      1. from sqlalchemy import table, column
      2. from sqlalchemy.dialects.postgresql import insert
      3. t = table("t", column("c1"), column("c2"))
      4. delete_statement_cte = (
      5. t.delete().where(t.c.c1 < 1).cte("deletions")
      6. )
      7. insert_stmt = insert(t).values({"c1": 1, "c2": 2})
      8. update_statement = insert_stmt.on_conflict_do_update(
      9. index_elements=[t.c.c1],
      10. set_={
      11. "c1": insert_stmt.excluded.c1,
      12. "c2": insert_stmt.excluded.c2,
      13. },
      14. ).add_cte(delete_statement_cte)
      15. print(update_statement)

      The above statement renders as:

      1. WITH deletions AS
      2. (DELETE FROM t WHERE t.c1 < %(c1_1)s)
      3. INSERT INTO t (c1, c2) VALUES (%(c1)s, %(c2)s)
      4. ON CONFLICT (c1) DO UPDATE SET c1 = excluded.c1, c2 = excluded.c2

      New in version 1.4.21.

      • Parameters:

        • *ctes

          zero or more constructs.

          Changed in version 2.0: Multiple CTE instances are accepted

        • nest_here

          if True, the given CTE or CTEs will be rendered as though they specified the HasCTE.cte.nesting flag to True when they were added to this . Assuming the given CTEs are not referenced in an outer-enclosing statement as well, the CTEs given should render at the level of this statement when this flag is given.

          New in version 2.0.

          See also

          HasCTE.cte.nesting

    • method alias(name: Optional[str] = None, flat: bool = False) → Subquery

      inherited from the method of SelectBase

      Return a named subquery against this .

      For a SelectBase (as opposed to a ), this returns a Subquery object which behaves mostly the same as the object that is used with a FromClause.

      Changed in version 1.4: The method is now a synonym for the SelectBase.subquery() method.

    • method as_scalar() → ScalarSelect[Any]

      inherited from the method of SelectBase

      Deprecated since version 1.4: The method is deprecated and will be removed in a future release. Please refer to SelectBase.scalar_subquery().

    • attribute c

      inherited from the SelectBase.c attribute of

      Deprecated since version 1.4: The SelectBase.c and SelectBase.columns attributes are deprecated and will be removed in a future release; these attributes implicitly create a subquery that should be explicit. Please call first in order to create a subquery, which then contains this attribute. To access the columns that this SELECT object SELECTs from, use the SelectBase.selected_columns attribute.

    • method compare(other: ClauseElement, **kw: Any) → bool

      inherited from the method of ClauseElement

      Compare this to the given ClauseElement.

      Subclasses should override the default behavior, which is a straight identity comparison.

      **kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison (see ).

    • method sqlalchemy.sql.expression.TextualSelect.compile(bind: Optional[Union[, Connection]] = None, dialect: Optional[] = None, **kw: Any) → Compiled

      inherited from the CompilerElement.compile() method of CompilerElement

      Compile this SQL expression.

      The return value is a object. Calling str() or unicode() on the returned value will yield a string representation of the result. The Compiled object also can return a dictionary of bind parameter names and values using the params accessor.

      • Parameters:

        • bind – An or Engine which can provide a in order to generate a Compiled object. If the bind and dialect parameters are both omitted, a default SQL compiler is used.

        • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.

        • dialect – A instance which can generate a Compiled object. This argument takes precedence over the bind argument.

        • compile_kwargs

          optional dictionary of additional parameters that will be passed through to the compiler within all “visit” methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the literal_binds flag through:

          1. from sqlalchemy.sql import table, column, select
          2. t = table('t', column('x'))
          3. s = select(t).where(t.c.x == 5)
          4. print(s.compile(compile_kwargs={"literal_binds": True}))

          New in version 0.9.0.

    1. See also
    2. [How do I render SQL expressions as strings, possibly with bound parameters inlined?]($e9fd44a49fe37bbb.md#faq-sql-expression-string)
    • method corresponding_column(column: KeyedColumnElement[Any], require_embedded: bool = False) → Optional[KeyedColumnElement[Any]]

      inherited from the Selectable.corresponding_column() method of

      Given a ColumnElement, return the exported object from the Selectable.exported_columns collection of this which corresponds to that original ColumnElement via a common ancestor column.

      • Parameters:

        • column – the target to be matched.

        • require_embedded – only return corresponding columns for the given ColumnElement, if the given is actually present within a sub-element of this Selectable. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this .

    1. See also
    2. [Selectable.exported\_columns](#sqlalchemy.sql.expression.Selectable.exported_columns "sqlalchemy.sql.expression.Selectable.exported_columns") - the [ColumnCollection]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnCollection "sqlalchemy.sql.expression.ColumnCollection") that is used for the operation.
    3. [ColumnCollection.corresponding\_column()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnCollection.corresponding_column "sqlalchemy.sql.expression.ColumnCollection.corresponding_column") - implementation method.
    • method sqlalchemy.sql.expression.TextualSelect.cte(name: Optional[str] = None, recursive: bool = False, nesting: bool = False) →

      inherited from the HasCTE.cte() method of

      Return a new CTE, or Common Table Expression instance.

      Common table expressions are a SQL standard whereby SELECT statements can draw upon secondary statements specified along with the primary statement, using a clause called “WITH”. Special semantics regarding UNION can also be employed to allow “recursive” queries, where a SELECT statement can draw upon the set of rows that have previously been selected.

      CTEs can also be applied to DML constructs UPDATE, INSERT and DELETE on some databases, both as a source of CTE rows when combined with RETURNING, as well as a consumer of CTE rows.

      Changed in version 1.1: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.

      SQLAlchemy detects objects, which are treated similarly to Alias objects, as special elements to be delivered to the FROM clause of the statement as well as to a WITH clause at the top of the statement.

      For special prefixes such as PostgreSQL “MATERIALIZED” and “NOT MATERIALIZED”, the CTE.prefix_with() method may be used to establish these.

      Changed in version 1.3.13: Added support for prefixes. In particular - MATERIALIZED and NOT MATERIALIZED.

      • Parameters:

        • name – name given to the common table expression. Like , the name can be left as None in which case an anonymous symbol will be used at query compile time.

        • recursive – if True, will render WITH RECURSIVE. A recursive common table expression is intended to be used in conjunction with UNION ALL in order to derive rows from those already selected.

        • nesting

          if True, will render the CTE locally to the statement in which it is referenced. For more complex scenarios, the HasCTE.add_cte() method using the parameter may also be used to more carefully control the exact placement of a particular CTE.

          New in version 1.4.24.

          See also

          HasCTE.add_cte()

    1. The following examples include two from PostgreSQLs documentation at [https://www.postgresql.org/docs/current/static/queries-with.html](https://www.postgresql.org/docs/current/static/queries-with.html), as well as additional examples.
    2. Example 1, non recursive:
    3. ```
    4. from sqlalchemy import (Table, Column, String, Integer,
    5. MetaData, select, func)
    6. metadata = MetaData()
    7. orders = Table('orders', metadata,
    8. Column('region', String),
    9. Column('amount', Integer),
    10. Column('product', String),
    11. Column('quantity', Integer)
    12. )
    13. regional_sales = select(
    14. orders.c.region,
    15. func.sum(orders.c.amount).label('total_sales')
    16. ).group_by(orders.c.region).cte("regional_sales")
    17. top_regions = select(regional_sales.c.region).\
    18. where(
    19. regional_sales.c.total_sales >
    20. select(
    21. func.sum(regional_sales.c.total_sales) / 10
    22. )
    23. ).cte("top_regions")
    24. statement = select(
    25. orders.c.region,
    26. orders.c.product,
    27. func.sum(orders.c.quantity).label("product_units"),
    28. func.sum(orders.c.amount).label("product_sales")
    29. ).where(orders.c.region.in_(
    30. select(top_regions.c.region)
    31. )).group_by(orders.c.region, orders.c.product)
    32. result = conn.execute(statement).fetchall()
    33. ```
    34. Example 2, WITH RECURSIVE:
    35. ```
    36. from sqlalchemy import (Table, Column, String, Integer,
    37. MetaData, select, func)
    38. metadata = MetaData()
    39. parts = Table('parts', metadata,
    40. Column('part', String),
    41. Column('sub_part', String),
    42. Column('quantity', Integer),
    43. )
    44. included_parts = select(\
    45. parts.c.sub_part, parts.c.part, parts.c.quantity\
    46. ).\
    47. where(parts.c.part=='our part').\
    48. cte(recursive=True)
    49. incl_alias = included_parts.alias()
    50. parts_alias = parts.alias()
    51. included_parts = included_parts.union_all(
    52. select(
    53. parts_alias.c.sub_part,
    54. parts_alias.c.part,
    55. parts_alias.c.quantity
    56. ).\
    57. where(parts_alias.c.part==incl_alias.c.sub_part)
    58. )
    59. statement = select(
    60. included_parts.c.sub_part,
    61. func.sum(included_parts.c.quantity).
    62. label('total_quantity')
    63. ).\
    64. group_by(included_parts.c.sub_part)
    65. result = conn.execute(statement).fetchall()
    66. ```
    67. Example 3, an upsert using UPDATE and INSERT with CTEs:
    68. ```
    69. from datetime import date
    70. from sqlalchemy import (MetaData, Table, Column, Integer,
    71. Date, select, literal, and_, exists)
    72. metadata = MetaData()
    73. visitors = Table('visitors', metadata,
    74. Column('product_id', Integer, primary_key=True),
    75. Column('date', Date, primary_key=True),
    76. Column('count', Integer),
    77. )
    78. # add 5 visitors for the product_id == 1
    79. product_id = 1
    80. day = date.today()
    81. count = 5
    82. update_cte = (
    83. visitors.update()
    84. .where(and_(visitors.c.product_id == product_id,
    85. visitors.c.date == day))
    86. .values(count=visitors.c.count + count)
    87. .returning(literal(1))
    88. .cte('update_cte')
    89. )
    90. upsert = visitors.insert().from_select(
    91. [visitors.c.product_id, visitors.c.date, visitors.c.count],
    92. select(literal(product_id), literal(day), literal(count))
    93. .where(~exists(update_cte.select()))
    94. )
    95. connection.execute(upsert)
    96. ```
    97. Example 4, Nesting CTE (SQLAlchemy 1.4.24 and above):
    98. ```
    99. value_a = select(
    100. literal("root").label("n")
    101. ).cte("value_a")
    102. # A nested CTE with the same name as the root one
    103. value_a_nested = select(
    104. literal("nesting").label("n")
    105. ).cte("value_a", nesting=True)
    106. # Nesting CTEs takes ascendency locally
    107. # over the CTEs at a higher level
    108. value_b = select(value_a_nested.c.n).cte("value_b")
    109. value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
    110. ```
    111. The above query will render the second CTE nested inside the first, shown with inline parameters below as:
    112. ```
    113. WITH
    114. value_a AS
    115. (SELECT 'root' AS n),
    116. value_b AS
    117. (WITH value_a AS
    118. (SELECT 'nesting' AS n)
    119. SELECT value_a.n AS n FROM value_a)
    120. SELECT value_a.n AS a, value_b.n AS b
    121. FROM value_a, value_b
    122. ```
    123. The same CTE can be set up using the [HasCTE.add\_cte()](#sqlalchemy.sql.expression.HasCTE.add_cte "sqlalchemy.sql.expression.HasCTE.add_cte") method as follows (SQLAlchemy 2.0 and above):
    124. ```
    125. value_a = select(
    126. literal("root").label("n")
    127. ).cte("value_a")
    128. # A nested CTE with the same name as the root one
    129. value_a_nested = select(
    130. literal("nesting").label("n")
    131. ).cte("value_a")
    132. # Nesting CTEs takes ascendency locally
    133. # over the CTEs at a higher level
    134. value_b = (
    135. select(value_a_nested.c.n).
    136. add_cte(value_a_nested, nest_here=True).
    137. cte("value_b")
    138. )
    139. value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
    140. ```
    141. Example 5, Non-Linear CTE (SQLAlchemy 1.4.28 and above):
    142. ```
    143. edge = Table(
    144. "edge",
    145. metadata,
    146. Column("id", Integer, primary_key=True),
    147. Column("left", Integer),
    148. Column("right", Integer),
    149. )
    150. root_node = select(literal(1).label("node")).cte(
    151. "nodes", recursive=True
    152. )
    153. left_edge = select(edge.c.left).join(
    154. root_node, edge.c.right == root_node.c.node
    155. )
    156. right_edge = select(edge.c.right).join(
    157. root_node, edge.c.left == root_node.c.node
    158. )
    159. subgraph_cte = root_node.union(left_edge, right_edge)
    160. subgraph = select(subgraph_cte)
    161. ```
    162. The above query will render 2 UNIONs inside the recursive CTE:
    163. ```
    164. WITH RECURSIVE nodes(node) AS (
    165. SELECT 1 AS node
    166. UNION
    167. SELECT edge."left" AS "left"
    168. FROM edge JOIN nodes ON edge."right" = nodes.node
    169. UNION
    170. SELECT edge."right" AS "right"
    171. FROM edge JOIN nodes ON edge."left" = nodes.node
    172. )
    173. SELECT nodes.node FROM nodes
    174. ```
    175. See also
    176. [Query.cte()]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query.cte "sqlalchemy.orm.Query.cte") - ORM version of [HasCTE.cte()](#sqlalchemy.sql.expression.HasCTE.cte "sqlalchemy.sql.expression.HasCTE.cte").
    • method execution_options(**kw: Any) → SelfExecutable

      inherited from the Executable.execution_options() method of

      Set non-SQL options for the statement which take effect during execution.

      Execution options can be set at many scopes, including per-statement, per-connection, or per execution, using methods such as Connection.execution_options() and parameters which accept a dictionary of options such as and Session.execute.execution_options.

      The primary characteristic of an execution option, as opposed to other kinds of options such as ORM loader options, is that execution options never affect the compiled SQL of a query, only things that affect how the SQL statement itself is invoked or how results are fetched. That is, execution options are not part of what’s accommodated by SQL compilation nor are they considered part of the cached state of a statement.

      The method is generative, as is the case for the method as applied to the and Query objects, which means when the method is called, a copy of the object is returned, which applies the given parameters to that new copy, but leaves the original unchanged:

      1. statement = select(table.c.x, table.c.y)
      2. new_statement = statement.execution_options(my_option=True)

      An exception to this behavior is the object, where the Connection.execution_options() method is explicitly not generative.

      The kinds of options that may be passed to and other related methods and parameter dictionaries include parameters that are explicitly consumed by SQLAlchemy Core or ORM, as well as arbitrary keyword arguments not defined by SQLAlchemy, which means the methods and/or parameter dictionaries may be used for user-defined parameters that interact with custom code, which may access the parameters using methods such as Executable.get_execution_options() and , or within selected event hooks using a dedicated execution_options event parameter such as ConnectionEvents.before_execute.execution_options or , e.g.:

      1. from sqlalchemy import event
      2. @event.listens_for(some_engine, "before_execute")
      3. def _process_opt(conn, statement, multiparams, params, execution_options):
      4. "run a SQL function before invoking a statement"
      5. if execution_options.get("do_special_thing", False):
      6. conn.exec_driver_sql("run_special_function()")

      Within the scope of options that are explicitly recognized by SQLAlchemy, most apply to specific classes of objects and not others. The most common execution options include:

      See also

      Connection.execution_options()

      Session.execute.execution_options

      - documentation on all ORM-specific execution options

    • method sqlalchemy.sql.expression.TextualSelect.exists() →

      inherited from the SelectBase.exists() method of

      Return an Exists representation of this selectable, which can be used as a column expression.

      The returned object is an instance of .

      See also

      exists()

      - in the 2.0 style tutorial.

      New in version 1.4.

    • attribute exported_columns

      inherited from the SelectBase.exported_columns attribute of

      A ColumnCollection that represents the “exported” columns of this , not including TextClause constructs.

      The “exported” columns for a object are synonymous with the SelectBase.selected_columns collection.

      New in version 1.4.

      See also

      Selectable.exported_columns

    • method sqlalchemy.sql.expression.TextualSelect.get_children(*, omit_attrs: Tuple[str, …] = (), **kw: Any) → Iterable[HasTraverseInternals]

      inherited from the HasTraverseInternals.get_children() method of HasTraverseInternals

      Return immediate child HasTraverseInternals elements of this HasTraverseInternals.

      This is used for visit traversal.

      **kw may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).

    • method get_execution_options() → _ExecuteOptions

      inherited from the Executable.get_execution_options() method of

      Get the non-SQL options which will take effect during execution.

      New in version 1.3.

      See also

      Executable.execution_options()

    • method get_label_style() → SelectLabelStyle

      inherited from the method of SelectBase

      Retrieve the current label style.

      Implemented by subclasses.

    • attribute inherit_cache: Optional[bool] = None

      inherited from the HasCacheKey.inherit_cache attribute of HasCacheKey

      Indicate if this instance should make use of the cache key generation scheme used by its immediate superclass.

      The attribute defaults to None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value to False, except that a warning is also emitted.

      This flag can be set to True on a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.

      See also

      Enabling Caching Support for Custom Constructs - General guideslines for setting the attribute for third-party or user defined SQL constructs.

    • method sqlalchemy.sql.expression.TextualSelect.is_derived_from(fromclause: Optional[]) → bool

      inherited from the ReturnsRows.is_derived_from() method of

      Return True if this ReturnsRows is ‘derived’ from the given .

      An example would be an Alias of a Table is derived from that Table.

    • method sqlalchemy.sql.expression.TextualSelect.label(name: Optional[str]) → [Any]

      inherited from the SelectBase.label() method of

      Return a ‘scalar’ representation of this selectable, embedded as a subquery with a label.

      See also

      SelectBase.as_scalar().

    • method lateral(name: Optional[str] = None) → LateralFromClause

      inherited from the SelectBase.lateral() method of

      Return a LATERAL alias of this Selectable.

      The return value is the construct also provided by the top-level lateral() function.

      New in version 1.1.

      See also

      - overview of usage.

    • method sqlalchemy.sql.expression.TextualSelect.options(*options: ExecutableOption) → SelfExecutable

      inherited from the method of Executable

      Apply options to this statement.

      In the general sense, options are any kind of Python object that can be interpreted by the SQL compiler for the statement. These options can be consumed by specific dialects or specific kinds of compilers.

      The most commonly known kind of option are the ORM level options that apply “eager load” and other loading behaviors to an ORM query. However, options can theoretically be used for many other purposes.

      For background on specific kinds of options for specific kinds of statements, refer to the documentation for those option objects.

      Changed in version 1.4: - added to Core statement objects towards the goal of allowing unified Core / ORM querying capabilities.

      See also

      Column Loading Options - refers to options specific to the usage of ORM queries

      - refers to options specific to the usage of ORM queries

    • method sqlalchemy.sql.expression.TextualSelect.params(_ClauseElement\_optionaldict: Optional[Mapping[str, Any]] = None, **kwargs: Any_) → SelfClauseElement

      inherited from the method of ClauseElement

      Return a copy with elements replaced.

      Returns a copy of this ClauseElement with bindparam() elements replaced with values taken from the given dictionary:

      1. >>> clause = column('x') + bindparam('foo')
      2. >>> print(clause.compile().params)
      3. {'foo':None}
      4. >>> print(clause.params({'foo':7}).compile().params)
      5. {'foo':7}
    • method replace_selectable(old: FromClause, alias: ) → SelfSelectable

      inherited from the Selectable.replace_selectable() method of

      Replace all occurrences of FromClause ‘old’ with the given object, returning a copy of this FromClause.

      Deprecated since version 1.4: The method is deprecated, and will be removed in a future release. Similar functionality is available via the sqlalchemy.sql.visitors module.

    • method sqlalchemy.sql.expression.TextualSelect.scalar_subquery() → [Any]

      inherited from the SelectBase.scalar_subquery() method of

      Return a ‘scalar’ representation of this selectable, which can be used as a column expression.

      The returned object is an instance of ScalarSelect.

      Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression. The scalar subquery can then be used in the WHERE clause or columns clause of an enclosing SELECT.

      Note that the scalar subquery differentiates from the FROM-level subquery that can be produced using the method.

      See also

      Scalar and Correlated Subqueries - in the 2.0 tutorial

    • method select(*arg: Any, **kw: Any) → Select

      inherited from the method of SelectBase

      Deprecated since version 1.4: The method is deprecated and will be removed in a future release; this method implicitly creates a subquery that should be explicit. Please call SelectBase.subquery() first in order to create a subquery, which then can be selected.

    • attribute selected_columns

      A ColumnCollection representing the columns that this SELECT statement or similar construct returns in its result set, not including constructs.

      This collection differs from the FromClause.columns collection of a in that the columns within this collection cannot be directly nested inside another SELECT statement; a subquery must be applied first which provides for the necessary parenthesization required by SQL.

      For a TextualSelect construct, the collection contains the objects that were passed to the constructor, typically via the TextClause.columns() method.

      New in version 1.4.

    • method self_group(against: Optional[OperatorType] = None) → ClauseElement

      inherited from the method of ClauseElement

      Apply a ‘grouping’ to this .

      This method is overridden by subclasses to return a “grouping” construct, i.e. parenthesis. In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by select() constructs when placed into the FROM clause of another . (Note that subqueries should be normally created using the Select.alias() method, as many platforms require nested SELECT statements to be named).

      As expressions are composed together, the application of is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression like x OR (y AND z) - AND takes precedence over OR.

      The base self_group() method of just returns self.

    • method sqlalchemy.sql.expression.TextualSelect.set_label_style(style: ) → TextualSelect

      Return a new selectable with the specified label style.

      Implemented by subclasses.

    • method subquery(name: Optional[str] = None) → Subquery

      inherited from the method of SelectBase

      Return a subquery of this .

      A subquery is from a SQL perspective a parenthesized, named construct that can be placed in the FROM clause of another SELECT statement.

      Given a SELECT statement such as:

      1. stmt = select(table.c.id, table.c.name)

      The above statement might look like:

      1. SELECT table.id, table.name FROM table

      The subquery form by itself renders the same way, however when embedded into the FROM clause of another SELECT statement, it becomes a named sub-element:

      1. subq = stmt.subquery()
      2. new_stmt = select(subq)

      The above renders as:

      1. SELECT anon_1.id, anon_1.name
      2. FROM (SELECT table.id, table.name FROM table) AS anon_1

      Historically, SelectBase.subquery() is equivalent to calling the method on a FROM object; however, as a SelectBase object is not directly FROM object, the method provides clearer semantics.

      New in version 1.4.

    • method sqlalchemy.sql.expression.TextualSelect.unique_params(_ClauseElement\_optionaldict: Optional[Dict[str, Any]] = None, **kwargs: Any_) → SelfClauseElement

      inherited from the method of ClauseElement

      Return a copy with elements replaced.

      Same functionality as ClauseElement.params(), except adds unique=True to affected bind parameters so that multiple statements can be used.

    class sqlalchemy.sql.expression.Values

    Represent a VALUES construct that can be used as a FROM element in a statement.

    The object is created from the values() function.

    New in version 1.4.

    Members

    , data(), , scalar_values()

    Class signature

    class (sqlalchemy.sql.roles.InElementRole, sqlalchemy.sql.expression.Generative, sqlalchemy.sql.expression.LateralFromClause)

    • method sqlalchemy.sql.expression.Values.alias(name: Optional[str] = None, flat: bool = False) → SelfValues

      Return a new construct that is a copy of this one with the given name.

      This method is a VALUES-specific specialization of the FromClause.alias() method.

      See also

      alias()

    • method data(values: List[Tuple[Any, …]]) → SelfValues

      Return a new Values construct, adding the given data to the data list.

      E.g.:

      1. my_values = my_values.data([(1, 'value 1'), (2, 'value2')])
      • Parameters:

        values – a sequence (i.e. list) of tuples that map to the column expressions given in the constructor.

    • method sqlalchemy.sql.expression.Values.lateral(name: Optional[str] = None) → LateralFromClause

      Return a new with the lateral flag set, so that it renders as LATERAL.

      See also

      lateral()

    • method scalar_values() → ScalarValues

      Returns a scalar VALUES construct that can be used as a COLUMN element in a statement.

      New in version 2.0.0b4.

    class sqlalchemy.sql.expression.ScalarValues

    Represent a scalar VALUES construct that can be used as a COLUMN element in a statement.

    The object is created from the Values.scalar_values() method. It’s also automatically generated when a is used in an IN or NOT IN condition.

    New in version 2.0.0b4.

    Class signature

    class sqlalchemy.sql.expression.ScalarValues (sqlalchemy.sql.roles.InElementRole, sqlalchemy.sql.expression.GroupedElement, )

    Constants used with the method.

    class sqlalchemy.sql.expression.SelectLabelStyle

    Label style constants that may be passed to Select.set_label_style().

    Members

    , LABEL_STYLE_DISAMBIGUATE_ONLY, , LABEL_STYLE_TABLENAME_PLUS_COL

    Class signature

    class (enum.Enum)

    • attribute sqlalchemy.sql.expression.SelectLabelStyle.LABEL_STYLE_DEFAULT = 2

      The default label style, refers to LABEL_STYLE_DISAMBIGUATE_ONLY.

      New in version 1.4.

    • attribute LABEL_STYLE_DISAMBIGUATE_ONLY = 2

      Label style indicating that columns with a name that conflicts with an existing name should be labeled with a semi-anonymizing label when generating the columns clause of a SELECT statement.

      Below, most column names are left unaffected, except for the second occurrence of the name columna, which is labeled using the label columna_1 to disambiguate it from that of tablea.columna:

      1. >>> from sqlalchemy import table, column, select, true, LABEL_STYLE_DISAMBIGUATE_ONLY
      2. >>> table1 = table("table1", column("columna"), column("columnb"))
      3. >>> table2 = table("table2", column("columna"), column("columnc"))
      4. >>> print(select(table1, table2).join(table2, true()).set_label_style(LABEL_STYLE_DISAMBIGUATE_ONLY))
      5. SELECT table1.columna, table1.columnb, table2.columna AS columna_1, table2.columnc
      6. FROM table1 JOIN table2 ON true

      Used with the GenerativeSelect.set_label_style() method, LABEL_STYLE_DISAMBIGUATE_ONLY is the default labeling style for all SELECT statements outside of ORM queries.

      New in version 1.4.

    • attribute sqlalchemy.sql.expression.SelectLabelStyle.LABEL_STYLE_NONE = 0

      Label style indicating no automatic labeling should be applied to the columns clause of a SELECT statement.

      Below, the columns named columna are both rendered as is, meaning that the name columna can only refer to the first occurrence of this name within a result set, as well as if the statement were used as a subquery:

      Used with the method.

      New in version 1.4.

    • attribute sqlalchemy.sql.expression.SelectLabelStyle.LABEL_STYLE_TABLENAME_PLUS_COL = 1

      Label style indicating all columns should be labeled as <tablename>_<columnname> when generating the columns clause of a SELECT statement, to disambiguate same-named columns referenced from different tables, aliases, or subqueries.

      Below, all column names are given a label so that the two same-named columns columna are disambiguated as table1_columna and table2_columna:

      1. >>> from sqlalchemy import table, column, select, true, LABEL_STYLE_TABLENAME_PLUS_COL
      2. >>> table1 = table("table1", column("columna"), column("columnb"))
      3. >>> table2 = table("table2", column("columna"), column("columnc"))
      4. >>> print(select(table1, table2).join(table2, true()).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL))
      5. FROM table1 JOIN table2 ON true

      Used with the method. Equivalent to the legacy method Select.apply_labels(); LABEL_STYLE_TABLENAME_PLUS_COL is SQLAlchemy’s legacy auto-labeling style. provides a less intrusive approach to disambiguation of same-named column expressions.

      New in version 1.4.

    See also

    Select.set_label_style()