Selectables, Tables, FROM objects

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

    function sqlalchemy.sql.expression.``except_(\selects, **kwargs*)

    Return an EXCEPT of multiple selectables.

    The returned object is an instance of CompoundSelect.

    • Parameters

      • *selects – a list of instances.

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

    function sqlalchemy.sql.expression.``except_all(\selects, **kwargs*)

    Return an EXCEPT ALL of multiple selectables.

    The returned object is an instance of .

    • Parameters

      • *selects – a list of Select instances.

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

    function sqlalchemy.sql.expression.``exists(\args, **kwargs*)

    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.

    function sqlalchemy.sql.expression.``intersect(\selects, **kwargs*)

    Return an INTERSECT of multiple selectables.

    The returned object is an instance of CompoundSelect.

    • Parameters

      • *selects – a list of instances.

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

    function sqlalchemy.sql.expression.``intersect_all(\selects, **kwargs*)

    Return an INTERSECT ALL of multiple selectables.

    The returned object is an instance of .

    • Parameters

      • *selects – a list of Select instances.

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

    function sqlalchemy.sql.expression.``select(\args, **kw*)

    Create a Select using either the 1.x or 2.0 constructor style.

    For the legacy calling style, see . If the first argument passed is a Python sequence or if keyword arguments are present, this style is used.

    New in version 2.0: - the select() construct is the same construct as the one returned by , except that the function only accepts the “columns clause” entities up front; the rest of the state of the SELECT should be built up using generative methods.

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

    See also

    Selecting - Core Tutorial description of .

    • 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, \columns, **kw*)

    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, **kwargs*)

    Return a UNION of multiple selectables.

    The returned object is an instance of CompoundSelect.

    A similar method is available on all FromClause subclasses.

    • Parameters

      • *selects – a list of instances.

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

    function sqlalchemy.sql.expression.``union_all(\selects, **kwargs*)

    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.

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

    function sqlalchemy.sql.expression.``values(\columns, **kw*)

    Construct a Values construct.

    The column expressions and the actual data for are given in two separate steps. The constructor receives the column expressions typically as column() constructs, and the data is then passed via the 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 column() 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=None, flat=False)

    Return an object.

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

    Similar functionality is available via the FromClause.alias() method available on all subclasses. In terms of a SELECT object as generated from the select() function, the method returns an Alias or similar object which represents a named, parenthesized subquery.

    When an is created from a Table object, this has the effect of the table being rendered as tablename AS aliasname in a SELECT statement.

    For objects, the effect is that of creating a named subquery, i.e. (select ...) AS aliasname.

    The name parameter is optional, and provides the name to use in the rendered SQL. If blank, an “anonymous” 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.

    • 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.

      • 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, name=None, recursive=False)

    Return a new , or Common Table Expression instance.

    Please see HasCTE.cte() for detail on CTE usage.

    function sqlalchemy.sql.expression.``join(left, right, onclause=None, isouter=False, full=False)

    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, name=None)

    Return a object.

    Lateral is an 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

    LATERAL correlation - overview of usage.

    function sqlalchemy.sql.expression.``outerjoin(left, right, onclause=None, full=False)

    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, sampling, name=None, seed=None)

    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 Selectable Foundational Constructors and .

    class sqlalchemy.sql.expression.``Alias(\arg, **kw*)

    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 alias() module level function as well as the method available on all FromClause subclasses.

    See also

    Class signature

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

    class sqlalchemy.sql.expression.``AliasedReturnsRows(\arg, **kw*)

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

    Class signature

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

    • attribute sqlalchemy.sql.expression.AliasedReturnsRows.description

    • method is_derived_from(fromclause)

      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(keyword, \selects, **kwargs*)

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

    See also

    union()

    intersect()

    except()

    except_all()

    Class signature

    class (sqlalchemy.sql.expression.HasCompileState, sqlalchemy.sql.expression.GenerativeSelect)

    • attribute bind

      Returns the Engine or to which this Executable is bound, or None if none found.

      Deprecated since version 1.4: The attribute is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. Bound metadata is being removed as of SQLAlchemy 2.0. (Background on SQLAlchemy 2.0 at: Migrating to SQLAlchemy 2.0)

    • attribute selected_columns

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

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

      New in version 1.4.

    • method self_group(against=None)

      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.

    class sqlalchemy.sql.expression.``CTE(\arg, **kw*)

    Represent a Common Table Expression.

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

    See also

    - in the 2.0 tutorial

    HasCTE.cte() - examples of calling styles

    Class signature

    class (sqlalchemy.sql.expression.Generative, sqlalchemy.sql.expression.HasPrefixes, , sqlalchemy.sql.expression.AliasedReturnsRows)

    • method alias(name=None, flat=False)

      Return an Alias of this .

      This method is a CTE-specific specialization of the FromClause.alias() method.

      See also

      alias()

    class sqlalchemy.sql.expression.``Executable

    Mark a as supporting execution.

    Executable is a superclass for all “statement” types of objects, including , delete(), , insert(), .

    Class signature

    class sqlalchemy.sql.expression.Executable (sqlalchemy.sql.roles.CoerceTextStatementRole, sqlalchemy.sql.expression.Generative)

    • attribute bind

      Returns the Engine or to which this Executable is bound, or None if none found.

      Deprecated since version 1.4: The attribute is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. Bound metadata is being removed as of SQLAlchemy 2.0. (Background on SQLAlchemy 2.0 at: Migrating to SQLAlchemy 2.0)

      This is a traversal which checks locally, then checks among the “from” clauses of associated objects until a bound engine or connection is found.

    • method execute(\multiparams, **params*)

      Compile and execute this Executable.

      Deprecated since version 1.4: The method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. All statement execution in SQLAlchemy 2.0 is performed by the Connection.execute() method of , or in the ORM by the Session.execute() method of . (Background on SQLAlchemy 2.0 at: Migrating to SQLAlchemy 2.0)

    • method execution_options(\*kw*)

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

      Execution options can be set on a per-statement or per Connection basis. Additionally, the and ORM Query objects provide access to execution options which they in turn configure upon connections.

      The execution_options() method is generative. A new instance of this statement is returned that contains the options:

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

      Note that only a subset of possible execution options can be applied to a statement - these include “autocommit” and “stream_results”, but not “isolation_level” or “compiled_cache”. See for a full list of possible options.

      See also

      Connection.execution_options()

      Executable.get_execution_options()

    • method get_execution_options()

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

      New in version 1.3.

      See also

      Executable.execution_options()

    • method options(\options*)

      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 Generative.options() to Core statement objects towards the goal of allowing unified Core / ORM querying capabilities.

      See also

      Deferred Column Loader Query 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.Executable.scalar(\multiparams, **params*)

      Compile and execute this , returning the result’s scalar representation.

      Deprecated since version 1.4: The Executable.scalar() method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. Scalar execution in SQLAlchemy 2.0 is performed by the method of Connection, or in the ORM by the method of Session. (Background on SQLAlchemy 2.0 at: )

    class sqlalchemy.sql.expression.``Exists(\args, **kwargs*)

    Represent an EXISTS clause.

    See exists() for a description of usage.

    Class signature

    class (sqlalchemy.sql.expression.UnaryExpression)

    • method __init__(\args, **kwargs*)

      Construct a new Exists object.

      This constructor is mirrored as a public API function; see for a full usage and argument description.

    • method sqlalchemy.sql.expression.Exists.correlate(\fromclause*)

      Apply correlation to the subquery noted by this .

      See also

      ScalarSelect.correlate()

    • method correlate_except(\fromclause*)

      Apply correlation to the subquery noted by this Exists.

      See also

    • method sqlalchemy.sql.expression.Exists.select(whereclause=None, \*kwargs*)

      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
      • Parameters

        • whereclause

          a WHERE clause, equivalent to calling the Select.where() method.

          Deprecated since version 1.4: The parameter is deprecated and will be removed in version 2.0. Please make use of the Select.where() method to add WHERE criteria to the SELECT statement.

        • **kwargs

          additional keyword arguments are passed to the legacy constructor for described at Select.create_legacy_select().

          Deprecated since version 1.4: The method will no longer accept keyword arguments in version 2.0. Please use generative methods from the Select construct in order to apply additional modifications.

    1. See also
    2. [`select()`](#sqlalchemy.sql.expression.select "sqlalchemy.sql.expression.select") - general purpose method which allows for arbitrary column lists.
    • method select_from(\froms*)

      Return a new Exists construct, applying the given expression to the method of the select statement contained.

      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.

    • method where(clause)

      Return a new exists() 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 statement first, including the desired WHERE clause, then use the SelectBase.exists() method to produce an 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 FromClause are the and the select() constructs. Key features common to all objects include:

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

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

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

    Class signature

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

    • method alias(name=None, flat=False)

      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 and Subqueries

    • attribute sqlalchemy.sql.expression.FromClause.c

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

      The attribute is an alias for the FromClause.columns atttribute.

      • 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)

      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.FromClause.join(right, onclause=None, isouter=False, full=False)

      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, onclause=None, full=False)

      Return a from this FromClause to another , 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 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.

        • 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 primary_key

      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.

    • attribute sqlalchemy.sql.expression.FromClause.schema = None

      Define the ‘schema’ attribute for this .

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

    • method sqlalchemy.sql.expression.FromClause.select(whereclause=None, \*kwargs*)

      Return a SELECT of this .

      e.g.:

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

        • whereclause

          a WHERE clause, equivalent to calling the Select.where() method.

          Deprecated since version 1.4: The parameter is deprecated and will be removed in version 2.0. Please make use of the Select.where() method to add WHERE criteria to the SELECT statement.

        • **kwargs – additional keyword arguments are passed to the legacy constructor for described at Select.create_legacy_select().

    1. See also
    2. [`select()`](#sqlalchemy.sql.expression.select "sqlalchemy.sql.expression.select") - general purpose method which allows for arbitrary column lists.
    • method table_valued()

      Return a TableValuedColumn object for this FromClause.

      A TableValuedColumn is a 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

      Working with SQL Functions - in the

    • method sqlalchemy.sql.expression.FromClause.tablesample(sampling, name=None, seed=None)

      Return a TABLESAMPLE alias of this .

      The return value is the TableSample construct also provided by the top-level function.

      New in version 1.1.

      See also

      tablesample() - usage guidelines and parameters

    class sqlalchemy.sql.expression.``GenerativeSelect(_label_style=symbol(‘LABEL_STYLE_DISAMBIGUATE_ONLY’), use_labels=False, limit=None, offset=None, order_by=None, group_by=None, bind=None)

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

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

    Class signature

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

    • method apply_labels()

      Deprecated since version 1.4: The GenerativeSelect.apply_labels() method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. Use set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) instead. (Background on SQLAlchemy 2.0 at: )

    • method sqlalchemy.sql.expression.GenerativeSelect.fetch(count, with_ties=False, percent=False)

      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.GenerativeSelect.get_label_style()

      Retrieve the current label style.

      New in version 1.4.

    • method group_by(\clauses*)

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

      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

    • method sqlalchemy.sql.expression.GenerativeSelect.limit(limit)

      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.GenerativeSelect.offset(offset)

      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.GenerativeSelect.order_by(\clauses*)

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

      e.g.:

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

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

      See also

      Ordering, Grouping, Limiting, Offset…ing…

    • method set_label_style(style)

      Return a new selectable with the specified label style.

      There are three “label styles” available, LABEL_STYLE_DISAMBIGUATE_ONLY, , and 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, 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_TABLENAME_PLUS_COL

      LABEL_STYLE_DEFAULT

    • method slice(start, stop)

      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=False, read=False, of=None, skip_locked=False, key_share=False)

      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.

        • 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) which will render into a FOR UPDATE OF clause; supported by PostgreSQL and Oracle. 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.

    Class signature

    class (sqlalchemy.sql.roles.HasCTERole)

    • method sqlalchemy.sql.expression.HasCTE.cte(name=None, recursive=False)

      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.

    1. The following examples include two from PostgreSQLs documentation at [http://www.postgresql.org/docs/current/static/queries-with.html](http://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. See also
    98. [`Query.cte()`]($3cf240505c8b4e45.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

    • method prefix_with(\expr, **kw*)

      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

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

        • **kw – A single keyword ‘dialect’ is accepted. This is an optional string dialect name which will limit rendering of this prefix to only that dialect.

    class sqlalchemy.sql.expression.``HasSuffixes

    • method sqlalchemy.sql.expression.HasSuffixes.suffix_with(\expr, **kw*)

      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 .

      • Parameters

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

        • **kw – A single keyword ‘dialect’ is accepted. This is an optional string dialect name which will limit rendering of this suffix to only that dialect.

    class sqlalchemy.sql.expression.``Join(left, right, onclause=None, isouter=False, full=False)

    Represent a JOIN construct between two elements.

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

    See also

    FromClause.join()

    Class signature

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

    • method __init__(left, right, onclause=None, isouter=False, full=False)

      Construct a new Join.

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

    • method sqlalchemy.sql.expression.Join.alias(name=None, flat=False)

      Deprecated since version 1.4: The method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. Create a select + subquery, or alias the individual tables inside the join, instead. (Background on SQLAlchemy 2.0 at: Migrating to SQLAlchemy 2.0)

      The default behavior here is to first produce a SELECT construct from this , then to produce an Alias from that. So given a join of the form:

      1. j = table_a.join(table_b, table_a.c.id == table_b.c.a_id)

      The JOIN by itself would look like:

      1. table_a JOIN table_b ON table_a.id = table_b.a_id

      Whereas the alias of the above, j.alias(), would in a SELECT context look like:

      1. (SELECT table_a.id AS table_a_id, table_b.id AS table_b_id,
      2. table_b.a_id AS table_b_a_id
      3. FROM table_a
      4. JOIN table_b ON table_a.id = table_b.a_id) AS anon_1

      The equivalent long-hand form, given a object j, is:

      1. from sqlalchemy import select, alias
      2. j = alias(
      3. select(j.left, j.right).\
      4. select_from(j).\
      5. set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL).\
      6. correlate(False),
      7. name=name
      8. )

      The selectable produced by Join.alias() features the same columns as that of the two individual selectables presented under a single name - the individual columns are “auto-labeled”, meaning the .c. collection of the resulting represents the names of the individual columns using a <tablename>_<columname> scheme:

      1. j.c.table_a_id
      2. j.c.table_b_a_id

      Join.alias() also features an alternate option for aliasing joins which produces no enclosing SELECT and does not normally apply labels to the column names. The flat=True option will call against the left and right sides individually. Using this option, no new SELECT is produced; we instead, from a construct as below:

      1. j = table_a.join(table_b, table_a.c.id == table_b.c.a_id)

      we get a result like this:

      The flat=True argument is also propagated to the contained selectables, so that a composite join such as:

      1. j = table_a.join(
      2. table_b.join(table_c,
      3. table_b.c.id == table_c.c.b_id),
      4. table_b.c.a_id == table_a.c.id
      5. ).alias(flat=True)

      Will produce an expression like:

      1. table_a AS table_a_1 JOIN (
      2. table_b AS table_b_1 JOIN table_c AS table_c_1
      3. ON table_b_1.id = table_c_1.b_id
      4. ) ON table_a_1.id = table_b_1.a_id

      The standalone alias() function as well as the base method also support the flat=True argument as a no-op, so that the argument can be passed to the alias() method of any selectable.

      • Parameters

        • name – name given to the alias.

        • flat – if True, produce an alias of the left and right sides of this Join and return the join of those two selectables. This produces join expression that does not include an enclosing SELECT.

    1. See also
    2. [Using Aliases and Subqueries]($4249fd39c54c4079.md#core-tutorial-aliases)
    3. [`alias()`](#sqlalchemy.sql.expression.alias "sqlalchemy.sql.expression.alias")
    • attribute bind

      Return the bound engine associated with either the left or right side of this Join.

      Deprecated since version 1.4: The attribute is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. Bound metadata is being removed as of SQLAlchemy 2.0. (Background on SQLAlchemy 2.0 at: Migrating to SQLAlchemy 2.0)

    • attribute description

    • method sqlalchemy.sql.expression.Join.is_derived_from(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.Join.select(whereclause=None, \*kwargs*)

      Create a from this Join.

      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
      • Parameters

        • whereclause

          WHERE criteria, same as calling on the resulting statement

          Deprecated since version 1.4: The Join.select().whereclause parameter is deprecated and will be removed in version 2.0. Please make use of the method to add WHERE criteria to the SELECT statement.

        • **kwargs – additional keyword arguments are passed to the legacy constructor for Select described at .

    • method sqlalchemy.sql.expression.Join.self_group(against=None)

      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 method of just returns self.

    class sqlalchemy.sql.expression.``Lateral(\arg, **kw*)

    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.

    Class signature

    class (sqlalchemy.sql.expression.AliasedReturnsRows)

    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.

    Class signature

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

    • attribute exported_columns

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

      The “exported” columns represent the collection of ColumnElement 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

      SelectBase.exported_columns

    class sqlalchemy.sql.expression.``ScalarSelect(element)

    Represent a scalar subquery.

    A ScalarSubquery 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

    - in the 1.x tutorial

    Class signature

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

    • method correlate(\fromclauses*)

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

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

      New in version 1.4: Previously, the method was only available from Select.

      • Parameters

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

      See also

      ScalarSelect.correlate_except()

      - in the 2.0 tutorial

      Correlated Subqueries - in the 1.x tutorial

    • method correlate_except(\fromclauses*)

      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

      - in the 1.x tutorial

    • method sqlalchemy.sql.expression.ScalarSelect.self_group(\*kwargs*)

      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)

      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 1.x tutorial

    Selecting Data - in the 2.0 tutorial

    Class signature

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

    • method add_columns(\columns*)

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

      E.g.:

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

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

    • method alias(name=None, flat=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.apply_labels()

      inherited from the method of GenerativeSelect

      Deprecated since version 1.4: The method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. Use set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) instead. (Background on SQLAlchemy 2.0 at: Migrating to SQLAlchemy 2.0)

    • method as_scalar()

      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.bind

      Returns the or Connection to which this is bound, or None if none found.

      Deprecated since version 1.4: The Executable.bind attribute is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. Bound metadata is being removed as of SQLAlchemy 2.0. (Background on SQLAlchemy 2.0 at: )

    • 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)

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

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

      E.g.:

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

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

    • attribute sqlalchemy.sql.expression.Select.column_descriptions

      Return a ‘column descriptions’ structure which may be .

    • method sqlalchemy.sql.expression.Select.correlate(\fromclauses*)

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

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

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

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

      • 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

      Correlated Subqueries

    • method correlate_except(\fromclauses*)

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

      Calling turns off the Select 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, the object will correlate all of its FROM entries.

      • 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

      Correlated Subqueries

    • method corresponding_column(column, require_embedded=False)

      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`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnCollection "sqlalchemy.sql.expression.ColumnCollection") that is used for the operation.
    3. [`ColumnCollection.corresponding_column()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnCollection.corresponding_column "sqlalchemy.sql.expression.ColumnCollection.corresponding_column") - implementation method.
    • method sqlalchemy.sql.expression.Select.classmethod create_legacy_select(columns=None, whereclause=None, from_obj=None, distinct=False, having=None, correlate=True, prefixes=None, suffixes=None, \*kwargs*)

      Construct a new using the 1.x style API.

      Deprecated since version 1.4: The legacy calling style of select() is deprecated and will be removed in SQLAlchemy 2.0. Please use the new calling style described at . (Background on SQLAlchemy 2.0 at: Migrating to SQLAlchemy 2.0)

      This method is called implicitly when the construct is used and the first argument is a Python list or other plain sequence object, which is taken to refer to the columns collection.

      Changed in version 1.4: Added the Select.create_legacy_select() constructor which documents the calling style in use when the construct is invoked using 1.x-style arguments.

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

      All arguments which accept ClauseElement arguments also accept string arguments, which will be converted as appropriate into either or literal_column() constructs.

      See also

      - Core Tutorial description of select().

      • Parameters

        • columns

          A list of or FromClause objects which will form the columns clause of the resulting statement. For those objects that are instances of (typically Table or objects), the FromClause.c collection is extracted to form a collection of objects.

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

          Note

          The parameter is not available in the method form of select(), e.g. .

          See also

          Select.column()

        • whereclause

          A ClauseElement expression which will be used to form the WHERE clause. It is typically preferable to add WHERE criterion to an existing using method chaining with Select.where().

          See also

        • from_obj

          A list of ClauseElement objects which will be added to the FROM clause of the resulting statement. This is equivalent to calling using method chaining on an existing Select object.

          See also

          - full description of explicit FROM clause specification.

        • bind=None – an Engine or instance to which the resulting Select object will be bound. The object will otherwise automatically bind to whatever Connectable instances can be located within its contained ClauseElement members.

        • correlate=True

          indicates that this object should have its contained FromClause elements “correlated” to an enclosing object. It is typically preferable to specify correlations on an existing Select construct using .

          See also

          Select.correlate() - full description of correlation.

        • distinct=False

          when True, applies a DISTINCT qualifier to the columns clause of the resulting statement.

          The boolean argument may also be a column expression or list of column expressions - this is a special calling form which is understood by the PostgreSQL dialect to render the DISTINCT ON (<columns>) syntax.

          distinct is also available on an existing object via the Select.distinct() method.

          See also

        • group_by

          a list of ClauseElement objects which will comprise the GROUP BY clause of the resulting select. This parameter is typically specified more naturally using the method on an existing Select.

          See also

        • having

          a ClauseElement that will comprise the HAVING clause of the resulting select when GROUP BY is used. This parameter is typically specified more naturally using the method on an existing Select.

          See also

        • limit=None

          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. This parameter is typically specified more naturally using the Select.limit() method on an existing .

          See also

          Select.limit()

        • offset=None

          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. This parameter is typically specified more naturally using the method on an existing Select.

          See also

        • order_by

          a scalar or list of ClauseElement objects which will comprise the ORDER BY clause of the resulting select. This parameter is typically specified more naturally using the method on an existing Select.

          See also

        • use_labels=False

          when True, the statement will be generated using labels for each column in the columns clause, which qualify each column with its parent table’s (or aliases) name so that name conflicts between columns in different tables don’t occur. The format of the label is <tablename>_<column>. The “c” collection of a Subquery created against this object, as well as the Select.selected_columns collection of the itself, will use these names for targeting column members.

          This parameter can also be specified on an existing Select object using the method.

          See also

          Select.set_label_style()

    • method cte(name=None, recursive=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.

    1. The following examples include two from PostgreSQLs documentation at [http://www.postgresql.org/docs/current/static/queries-with.html](http://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. See also
    98. [`Query.cte()`]($3cf240505c8b4e45.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*)

      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, \*kwargs*)

      Return a SQL EXCEPT of this select() construct against the given selectable.

    • method sqlalchemy.sql.expression.Select.except_all(other, \*kwargs*)

      Return a SQL EXCEPT ALL of this select() construct against the given selectable.

    • method execute(\multiparams, **params*)

      inherited from the Executable.execute() method of

      Compile and execute this Executable.

      Deprecated since version 1.4: The method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. All statement execution in SQLAlchemy 2.0 is performed by the Connection.execute() method of , or in the ORM by the Session.execute() method of . (Background on SQLAlchemy 2.0 at: Migrating to SQLAlchemy 2.0)

    • method execution_options(\*kw*)

      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 on a per-statement or per Connection basis. Additionally, the and ORM Query objects provide access to execution options which they in turn configure upon connections.

      The execution_options() method is generative. A new instance of this statement is returned that contains the options:

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

      Note that only a subset of possible execution options can be applied to a statement - these include “autocommit” and “stream_results”, but not “isolation_level” or “compiled_cache”. See for a full list of possible options.

      See also

      Connection.execution_options()

      Executable.get_execution_options()

    • method 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 .

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

      New in version 1.4.

      See also

      Selectable.exported_columns

    • method sqlalchemy.sql.expression.Select.fetch(count, with_ties=False, percent=False)

      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*)

      A synonym for the Select.where() method.

    • method filter_by(\*kwargs*)

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

    • method sqlalchemy.sql.expression.Select.from_statement(statement)

      Apply the columns which this would select onto another statement.

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

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

      See also

      - usage examples in the ORM Querying Guide

    • attribute sqlalchemy.sql.expression.Select.froms

      Return the displayed list of elements.

    • method sqlalchemy.sql.expression.Select.get_children(\*kwargs*)

      Return immediate child elements of this Traversible.

      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()

      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()

      inherited from the GenerativeSelect.get_label_style() method of

      Retrieve the current label style.

      New in version 1.4.

    • method sqlalchemy.sql.expression.Select.group_by(\clauses*)

      inherited from the method of GenerativeSelect

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

      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

      Ordering, Grouping, Limiting, Offset…ing…

    • method having(having)

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

    • attribute inner_columns

      An iterator of all ColumnElement 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 collection.

    • method sqlalchemy.sql.expression.Select.intersect(other, \*kwargs*)

      Return a SQL INTERSECT of this select() construct against the given selectable.

    • method intersect_all(other, \*kwargs*)

      Return a SQL INTERSECT ALL of this select() construct against the given selectable.

    • method sqlalchemy.sql.expression.Select.join(target, onclause=None, isouter=False, full=False)

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

      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: 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 .

      • Parameters

        • target – target table to join towards

        • onclause – ON clause of the join. If omitted, an ON clause is generated automatically based on the ForeignKey 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 .

        • full – if True, generate FULL OUTER join.

    1. See also
    2. [Explicit FROM clauses and JOINs]($cfdc81b69abe0678.md#tutorial-select-join) - in the [SQLAlchemy 1.4 / 2.0 Tutorial]($2006f9816d864d8d.md)
    3. [Joins]($03b903c0b580274b.md#orm-queryguide-joins) - in the [ORM Querying Guide]($03b903c0b580274b.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 sqlalchemy.sql.expression.Select.join_from(from_, target, onclause=None, isouter=False, full=False)

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

      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 method.

        • target – target table to join towards

        • onclause – ON clause of the join.

        • 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]($cfdc81b69abe0678.md#tutorial-select-join) - in the [SQLAlchemy 1.4 / 2.0 Tutorial]($2006f9816d864d8d.md)
    3. [Joins]($03b903c0b580274b.md#orm-queryguide-joins) - in the [ORM Querying Guide]($03b903c0b580274b.md)
    4. [`Select.join()`](#sqlalchemy.sql.expression.Select.join "sqlalchemy.sql.expression.Select.join")
    • method label(name)

      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=None)

      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)

      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)

      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*)

      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 Generative.options() to Core statement objects towards the goal of allowing unified Core / ORM querying capabilities.

      See also

      - refers to options specific to the usage of ORM queries

      Relationship Loading with Loader Options - refers to options specific to the usage of ORM queries

    • method order_by(\clauses*)

      inherited from the GenerativeSelect.order_by() method of

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

      e.g.:

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

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

      See also

    • method sqlalchemy.sql.expression.Select.outerjoin(target, onclause=None, full=False)

      Create a left outer join.

      Parameters are the same as that of .

      Changed in version 1.4: Select.outerjoin() 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.

      See also

      - in the SQLAlchemy 1.4 / 2.0 Tutorial

      - in the ORM Querying Guide

    • method sqlalchemy.sql.expression.Select.outerjoin_from(from_, target, onclause=None, full=False)

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

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

    • method prefix_with(\expr, **kw*)

      inherited from the HasPrefixes.prefix_with() method of

      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

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

        • **kw – A single keyword ‘dialect’ is accepted. This is an optional string dialect name which will limit rendering of this prefix to only that dialect.

    • method sqlalchemy.sql.expression.Select.reduce_columns(only_synonyms=True)

      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, alias)

      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(\multiparams, **params*)

      inherited from the method of Executable

      Compile and execute this , returning the result’s scalar representation.

      Deprecated since version 1.4: The Executable.scalar() method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. Scalar execution in SQLAlchemy 2.0 is performed by the method of Connection, or in the ORM by the method of Session. (Background on SQLAlchemy 2.0 at: )

    • method sqlalchemy.sql.expression.Select.scalar_subquery()

      inherited from the method of SelectBase

      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

      Scalar Selects - in the 1.x tutorial

    • method select(\arg, **kw*)

      inherited from the SelectBase.select() method of

      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.

    • method sqlalchemy.sql.expression.Select.select_from(\froms*)

      Return a new 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 Table or other selectable will have no effect. Passing a that refers to an already present Table 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 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 sqlalchemy.sql.expression.Select.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.

      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.

      New in version 1.4.

    • method sqlalchemy.sql.expression.Select.self_group(against=None)

      Return a ‘grouping’ construct as per the specification.

      This produces an element that can be embedded in an expression. Note that this method is called automatically as needed when constructing expressions and should not require explicit use.

    • method sqlalchemy.sql.expression.Select.set_label_style(style)

      inherited from the method of GenerativeSelect

      Return a new selectable with the specified label style.

      There are three “label styles” available, , LABEL_STYLE_TABLENAME_PLUS_COL, and . The default style is LABEL_STYLE_TABLENAME_PLUS_COL.

      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 method. In past versions, LABEL_STYLE_TABLENAME_PLUS_COL was used to disambiguate same-named columns from different tables, aliases, or subqueries; the newer 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 FromClause.c collection when a subquery is created.

      New in version 1.4: - the 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_NONE

    • method sqlalchemy.sql.expression.Select.slice(start, stop)

      inherited from the method of GenerativeSelect

      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 method will replace any clause applied with GenerativeSelect.fetch().

      New in version 1.4: Added the method generalized from the ORM.

      See also

      GenerativeSelect.limit()

      GenerativeSelect.fetch()

    • method subquery(name=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(\expr, **kw*)

      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

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

        • **kw – A single keyword ‘dialect’ is accepted. This is an optional string dialect name which will limit rendering of this suffix to only that dialect.

    • method sqlalchemy.sql.expression.Select.union(other, \*kwargs*)

      Return a SQL UNION of this select() construct against the given selectable.

    • method union_all(other, \*kwargs*)

      Return a SQL UNION ALL of this select() construct against the given selectable.

    • method sqlalchemy.sql.expression.Select.where(\whereclause*)

      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=False, read=False, of=None, skip_locked=False, key_share=False)

      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.

        • 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) which will render into a FOR UPDATE OF clause; supported by PostgreSQL and Oracle. 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, text, dialect_name=’\‘*)

      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", 'sybase')

      See also

    • method sqlalchemy.sql.expression.Select.with_only_columns(\columns*)

      Return a new construct with its columns clause replaced with the given columns.

      This method is exactly equivalent to as if the original select() had been called with the given columns clause. I.e. 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)

      Note that this will also dynamically alter the FROM clause of the statement if it is not explicitly stated. To maintain the FROM clause, ensure the method is used appropriately:

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

        *columns

        column expressions to be used.

        Changed in version 1.4: the Select.with_only_columns() method accepts the list of column expressions positionally; passing the expressions as a list is deprecated.

    • method with_statement_hint(text, dialect_name=’\‘*)

      inherited from the HasHints.with_statement_hint() method of HasHints

      Add a statement hint to this Select or other selectable object.

      This method is similar to 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.with_hint()

      - 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.

    Class signature

    class sqlalchemy.sql.expression.Selectable ()

    • method sqlalchemy.sql.expression.Selectable.corresponding_column(column, require_embedded=False)

      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`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnCollection "sqlalchemy.sql.expression.ColumnCollection") that is used for the operation.
    3. [`ColumnCollection.corresponding_column()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnCollection.corresponding_column "sqlalchemy.sql.expression.ColumnCollection.corresponding_column") - implementation method.
    • attribute exported_columns

      inherited from the ReturnsRows.exported_columns attribute of

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

      The “exported” columns represent the collection of ColumnElement 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

      SelectBase.exported_columns

    • Return a LATERAL alias of this .

      The return value is the Lateral construct also provided by the top-level function.

      New in version 1.1.

      See also

      LATERAL correlation - overview of usage.

    • method replace_selectable(old, alias)

      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.

    class sqlalchemy.sql.expression.``SelectBase

    Base class for SELECT statements.

    This includes Select, and TextualSelect.

    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, sqlalchemy.sql.expression.Selectable)

    • method alias(name=None, flat=False)

      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.SelectBase.as_scalar()

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

    • attribute bind

      inherited from the Executable.bind attribute of

      Returns the Engine or to which this Executable is bound, or None if none found.

      Deprecated since version 1.4: The attribute is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. Bound metadata is being removed as of SQLAlchemy 2.0. (Background on SQLAlchemy 2.0 at: Migrating to SQLAlchemy 2.0)

      This is a traversal which checks locally, then checks among the “from” clauses of associated objects until a bound engine or connection is found.

    • 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, require_embedded=False)

      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`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnCollection "sqlalchemy.sql.expression.ColumnCollection") that is used for the operation.
    3. [`ColumnCollection.corresponding_column()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnCollection.corresponding_column "sqlalchemy.sql.expression.ColumnCollection.corresponding_column") - implementation method.
    • method sqlalchemy.sql.expression.SelectBase.cte(name=None, recursive=False)

      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.

    • method execute(\multiparams, **params*)

      inherited from the Executable.execute() method of

      Compile and execute this Executable.

      Deprecated since version 1.4: The method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. All statement execution in SQLAlchemy 2.0 is performed by the Connection.execute() method of , or in the ORM by the Session.execute() method of . (Background on SQLAlchemy 2.0 at: Migrating to SQLAlchemy 2.0)

    • method execution_options(\*kw*)

      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 on a per-statement or per Connection basis. Additionally, the and ORM Query objects provide access to execution options which they in turn configure upon connections.

      The execution_options() method is generative. A new instance of this statement is returned that contains the options:

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

      Note that only a subset of possible execution options can be applied to a statement - these include “autocommit” and “stream_results”, but not “isolation_level” or “compiled_cache”. See for a full list of possible options.

      See also

      Connection.execution_options()

      Executable.get_execution_options()

    • method exists()

      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

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

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

      New in version 1.4.

      See also

      Selectable.exported_columns

    • method sqlalchemy.sql.expression.SelectBase.get_execution_options()

      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.SelectBase.label(name)

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

      See also

      .

    • method sqlalchemy.sql.expression.SelectBase.lateral(name=None)

      Return a LATERAL alias of this .

      The return value is the Lateral construct also provided by the top-level function.

      New in version 1.1.

      See also

      LATERAL correlation - overview of usage.

    • method options(\options*)

      inherited from the Executable.options() method of

      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 Generative.options() to Core statement objects towards the goal of allowing unified Core / ORM querying capabilities.

      See also

      Deferred Column Loader Query 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.SelectBase.replace_selectable(old, alias)

      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(\multiparams, **params*)

      inherited from the Executable.scalar() method of

      Compile and execute this Executable, returning the result’s scalar representation.

      Deprecated since version 1.4: The method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. Scalar execution in SQLAlchemy 2.0 is performed by the Connection.scalar() method of , or in the ORM by the Session.scalar() method of . (Background on SQLAlchemy 2.0 at: Migrating to SQLAlchemy 2.0)

    • method scalar_subquery()

      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

      - in the 1.x tutorial

    • method sqlalchemy.sql.expression.SelectBase.select(\arg, **kw*)

      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.

      This collection differs from the collection of a FromClause 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.

      New in version 1.4.

    • method subquery(name=None)

      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.

    class sqlalchemy.sql.expression.``Subquery(\arg, **kw*)

    Represent a subquery of a SELECT.

    A is created by invoking the SelectBase.subquery() method, or for convenience the method, on any SelectBase subclass which includes , CompoundSelect, and . 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 Subquery object is very similar to the object and can be used in an equivalent way. The difference between Alias and is that Alias always contains a object whereas Subquery always contains a object.

    New in version 1.4: The Subquery class was added which now serves the purpose of providing an aliased version of a SELECT statement.

    Class signature

    class (sqlalchemy.sql.expression.AliasedReturnsRows)

    • method as_scalar()

      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.

    class sqlalchemy.sql.expression.``TableClause(name, \columns, **kw*)

    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.

    Class signature

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

    • method __init__(name, \columns, **kw*)

      Construct a new TableClause object.

      This constructor is mirrored as a public API function; see for a full usage and argument description.

    • method sqlalchemy.sql.expression.TableClause.alias(name=None, flat=False)

      inherited from the method of FromClause

      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

      inherited from the FromClause.c attribute of

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

      The FromClause.c attribute is an alias for the atttribute.

    • 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, \*kw*)

      inherited from the ClauseElement.compare() method of

      Compare this ClauseElement to the given .

      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 ColumnElement).

    • method compile(bind=None, dialect=None, \*kw*)

      inherited from the ClauseElement.compile() method of

      Compile this SQL expression.

      The return value is a Compiled object. Calling str() or unicode() on the returned value will yield a string representation of the result. The object also can return a dictionary of bind parameter names and values using the params accessor.

      • Parameters

        • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement’s bound engine, if any.

        • 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 Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ‘s bound engine, if any.

        • 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?]($23f306fd0cdd485d.md#faq-sql-expression-string)
    • method sqlalchemy.sql.expression.TableClause.corresponding_column(column, require_embedded=False)

      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`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnCollection "sqlalchemy.sql.expression.ColumnCollection") that is used for the operation.
    3. [`ColumnCollection.corresponding_column()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnCollection.corresponding_column "sqlalchemy.sql.expression.ColumnCollection.corresponding_column") - implementation method.
    • method delete(whereclause=None, \*kwargs*)

      Generate a delete() construct against this .

      E.g.:

      1. table.delete().where(table.c.id==7)

      See delete() for argument and usage information.

    • attribute entity_namespace

      inherited from the FromClause.entity_namespace attribute of

      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 sqlalchemy.sql.expression.TableClause.exported_columns

      inherited from the attribute of FromClause

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

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

      New in version 1.4.

      See also

      SelectBase.exported_columns

    • attribute foreign_keys

      inherited from the FromClause.foreign_keys attribute of

      Return the collection of ForeignKey marker objects which this FromClause references.

      Each is a member of a Table-wide .

      See also

      Table.foreign_key_constraints

    • method get_children(omit_attrs=(), \*kw*)

      inherited from the ClauseElement.get_children() method of

      Return immediate child Traversible elements of this .

      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 sqlalchemy.sql.expression.TableClause.implicit_returning = False

      doesn’t support having a primary key or column -level defaults, so implicit returning doesn’t apply.

    • method sqlalchemy.sql.expression.TableClause.insert(values=None, inline=False, \*kwargs*)

      Generate an construct against this TableClause.

      E.g.:

      1. table.insert().values(name='foo')

      See for argument and usage information.

    • method sqlalchemy.sql.expression.TableClause.is_derived_from(fromclause)

      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, onclause=None, isouter=False, full=False)

      inherited from the method of FromClause

      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.TableClause.lateral(name=None)

      inherited from the method of Selectable

      Return a LATERAL alias of this .

      The return value is the Lateral construct also provided by the top-level function.

      New in version 1.1.

      See also

      LATERAL correlation - overview of usage.

    • class memoized_attribute(fget, doc=None)

      A read-only @property that is only evaluated once.

    • method classmethod memoized_instancemethod(fn)

      inherited from the HasMemoized.memoized_instancemethod() method of HasMemoized

      Decorate a method memoize its return value.

    • method sqlalchemy.sql.expression.TableClause.outerjoin(right, onclause=None, full=False)

      inherited from the method of FromClause

      Return a from this FromClause to another , 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 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.

        • 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 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)

      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 select(whereclause=None, \*kwargs*)

      inherited from the FromClause.select() method of

      Return a SELECT of this FromClause.

      e.g.:

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

        • whereclause

          a WHERE clause, equivalent to calling the method.

          Deprecated since version 1.4: The FromClause.select().whereclause parameter is deprecated and will be removed in version 2.0. Please make use of the method to add WHERE criteria to the SELECT statement.

        • **kwargs – additional keyword arguments are passed to the legacy constructor for Select described at .

    1. See also
    2. [`select()`](#sqlalchemy.sql.expression.select "sqlalchemy.sql.expression.select") - general purpose method which allows for arbitrary column lists.
    • method sqlalchemy.sql.expression.TableClause.self_group(against=None)

      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()

      inherited from the method of FromClause

      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 1.4 / 2.0 Tutorial

    • method tablesample(sampling, name=None, seed=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.update(whereclause=None, values=None, inline=False, \*kwargs*)

      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(\arg, **kw*)

    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 ()

    class sqlalchemy.sql.expression.``TableValuedAlias(\arg, **kw*)

    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 FunctionElement.table_valued() 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

    - in the SQLAlchemy 1.4 / 2.0 Tutorial

    Class signature

    class (sqlalchemy.sql.expression.Alias)

    • method alias(name=None)

      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=None)

      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=None, with_types=False)

      Apply “render derived” to this .

      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(text, columns, positional=False)

    Wrap a TextClause construct within a interface.

    This allows the TextClause object to gain a .c collection and other FROM-like capabilities such as , SelectBase.cte(), etc.

    The construct is produced via the TextClause.columns() method - see that method for details.

    Changed in version 1.4: the class was renamed from TextAsFrom, to more correctly suit its role as a SELECT-oriented object and not a FROM clause.

    See also

    text()

    - primary creation interface.

    Class signature

    class sqlalchemy.sql.expression.TextualSelect ()

    • method sqlalchemy.sql.expression.TextualSelect.alias(name=None, flat=False)

      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()

      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.TextualSelect.bind

      inherited from the attribute of Executable

      Returns the or Connection to which this is bound, or None if none found.

      Deprecated since version 1.4: The Executable.bind attribute is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. Bound metadata is being removed as of SQLAlchemy 2.0. (Background on SQLAlchemy 2.0 at: )

      This is a traversal which checks locally, then checks among the “from” clauses of associated objects until a bound engine or connection is found.

    • attribute sqlalchemy.sql.expression.TextualSelect.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.TextualSelect.compare(other, \*kw*)

      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=None, dialect=None, \*kw*)

      inherited from the method of ClauseElement

      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 Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ’s bound engine, if any.

        • 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 Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement ‘s bound engine, if any.

        • 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?]($23f306fd0cdd485d.md#faq-sql-expression-string)
    • method corresponding_column(column, require_embedded=False)

      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`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnCollection "sqlalchemy.sql.expression.ColumnCollection") that is used for the operation.
    3. [`ColumnCollection.corresponding_column()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnCollection.corresponding_column "sqlalchemy.sql.expression.ColumnCollection.corresponding_column") - implementation method.
    • method sqlalchemy.sql.expression.TextualSelect.cte(name=None, recursive=False)

      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.

    1. The following examples include two from PostgreSQLs documentation at [http://www.postgresql.org/docs/current/static/queries-with.html](http://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. See also
    98. [`Query.cte()`]($3cf240505c8b4e45.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 execute(\multiparams, **params*)

      inherited from the Executable.execute() method of

      Compile and execute this Executable.

      Deprecated since version 1.4: The method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. All statement execution in SQLAlchemy 2.0 is performed by the Connection.execute() method of , or in the ORM by the Session.execute() method of . (Background on SQLAlchemy 2.0 at: Migrating to SQLAlchemy 2.0)

    • method execution_options(\*kw*)

      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 on a per-statement or per Connection basis. Additionally, the and ORM Query objects provide access to execution options which they in turn configure upon connections.

      The execution_options() method is generative. A new instance of this statement is returned that contains the options:

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

      Note that only a subset of possible execution options can be applied to a statement - these include “autocommit” and “stream_results”, but not “isolation_level” or “compiled_cache”. See for a full list of possible options.

      See also

      Connection.execution_options()

      Executable.get_execution_options()

    • method 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 .

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

      New in version 1.4.

      See also

      Selectable.exported_columns

    • method sqlalchemy.sql.expression.TextualSelect.get_children(omit_attrs=(), \*kw*)

      inherited from the method of ClauseElement

      Return immediate child elements of this Traversible.

      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()

      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 label(name)

      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=None)

      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.

    • class memoized_attribute(fget, doc=None)

      A read-only @property that is only evaluated once.

    • method sqlalchemy.sql.expression.TextualSelect.classmethod memoized_instancemethod(fn)

      inherited from the HasMemoized.memoized_instancemethod() method of HasMemoized

      Decorate a method memoize its return value.

    • method options(\options*)

      inherited from the Executable.options() method of

      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 Generative.options() to Core statement objects towards the goal of allowing unified Core / ORM querying capabilities.

      See also

      Deferred Column Loader Query 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(\optionaldict, **kwargs*)

      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, alias)

      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(\multiparams, **params*)

      inherited from the method of Executable

      Compile and execute this , returning the result’s scalar representation.

      Deprecated since version 1.4: The Executable.scalar() method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. Scalar execution in SQLAlchemy 2.0 is performed by the method of Connection, or in the ORM by the method of Session. (Background on SQLAlchemy 2.0 at: )

    • method sqlalchemy.sql.expression.TextualSelect.scalar_subquery()

      inherited from the method of SelectBase

      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

      Scalar Selects - in the 1.x tutorial

    • method select(\arg, **kw*)

      inherited from the SelectBase.select() method of

      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.TextualSelect.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.

      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=None)

      inherited from the ClauseElement.self_group() method of

      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 subquery(name=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 unique_params(\optionaldict, **kwargs*)

      inherited from the ClauseElement.unique_params() method of

      Return a copy with bindparam() elements replaced.

      Same functionality as , except adds unique=True to affected bind parameters so that multiple statements can be used.

    class sqlalchemy.sql.expression.``Values(\columns, **kw*)

    Represent a VALUES construct that can be used as a FROM element in a statement.

    The Values object is created from the function.

    New in version 1.4.

    Class signature

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

    • method sqlalchemy.sql.expression.Values.__init__(\columns, **kw*)

      Construct a new object.

      This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.values() for a full usage and argument description.

    • method alias(name, \*kw*)

      Return a new Values construct that is a copy of this one with the given name.

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

      See also

      Using Aliases and Subqueries

    • method sqlalchemy.sql.expression.Values.data(values)

      Return a new 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 Values constructor.

    • method lateral(name=None)

      Return a new Values with the lateral flag set, so that it renders as LATERAL.

      See also

    Constants used with the GenerativeSelect.set_label_style() method.

    sqlalchemy.sql.expression.``LABEL_STYLE_DISAMBIGUATE_ONLY = symbol(‘LABEL_STYLE_DISAMBIGUATE_ONLY’)

    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 method, LABEL_STYLE_DISAMBIGUATE_ONLY is the default labeling style for all SELECT statements outside of ORM queries.

    New in version 1.4.

    sqlalchemy.sql.expression.``LABEL_STYLE_NONE = symbol(‘LABEL_STYLE_NONE’)

    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:

    1. >>> from sqlalchemy import table, column, select, true, LABEL_STYLE_NONE
    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_NONE))
    5. SELECT table1.columna, table1.columnb, table2.columna, table2.columnc
    6. FROM table1 JOIN table2 ON true

    Used with the Select.set_label_style() method.

    New in version 1.4.

    sqlalchemy.sql.expression.``LABEL_STYLE_TABLENAME_PLUS_COL = symbol(‘LABEL_STYLE_TABLENAME_PLUS_COL’)

    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`:

    Used with the GenerativeSelect.set_label_style() method. Equivalent to the legacy method Select.apply_labels(); is SQLAlchemy’s legacy auto-labeling style. LABEL_STYLE_DISAMBIGUATE_ONLY provides a less intrusive approach to disambiguation of same-named column expressions.

    New in version 1.4.

    sqlalchemy.sql.expression.``LABEL_STYLE_DEFAULT

    The default label style, refers to .

    New in version 1.4.

    See also

    Select.set_label_style()