Column Elements and Expressions

    Standalone functions imported from the namespace which are used when building up SQLAlchemy Expression Language constructs.

    function sqlalchemy.sql.expression.and_(*clauses)

    function sqlalchemy.sql.expression.bindparam(key: Optional[str], value: Any = _NoArg.NO_ARG, type\: Optional[_TypeEngineArgument[_T]] = None, _unique: bool = False, required: Union[bool, Literal[_NoArg.NO_ARG]] = _NoArg.NO_ARG, quote: Optional[bool] = None, callable\: Optional[Callable[[], Any]] = None, _expanding: bool = False, isoutparam: bool = False, literal_execute: bool = False) → [_T]

    Produce a “bound expression”.

    The return value is an instance of BindParameter; this is a subclass which represents a so-called “placeholder” value in a SQL expression, the value of which is supplied at the point at which the statement in executed against a database connection.

    In SQLAlchemy, the bindparam() construct has the ability to carry along the actual value that will be ultimately used at expression time. In this way, it serves not just as a “placeholder” for eventual population, but also as a means of representing so-called “unsafe” values which should not be rendered directly in a SQL statement, but rather should be passed along to the as values which need to be correctly escaped and potentially handled for type-safety.

    When using bindparam() explicitly, the use case is typically one of traditional deferment of parameters; the construct accepts a name which can then be referred to at execution time:

    The above statement, when rendered, will produce SQL similar to:

    1. SELECT id, name FROM user WHERE name = :username

    In order to populate the value of :username above, the value would typically be applied at execution time to a method like Connection.execute():

    1. result = connection.execute(stmt, username='wendy')

    Explicit use of is also common when producing UPDATE or DELETE statements that are to be invoked multiple times, where the WHERE criterion of the statement is to change on each invocation, such as:

    1. stmt = (users_table.update().
    2. where(user_table.c.name == bindparam('username')).
    3. values(fullname=bindparam('fullname'))
    4. )
    5. connection.execute(
    6. stmt, [{"username": "wendy", "fullname": "Wendy Smith"},
    7. {"username": "jack", "fullname": "Jack Jones"},
    8. ]
    9. )

    SQLAlchemy’s Core expression system makes wide use of bindparam() in an implicit sense. It is typical that Python literal values passed to virtually all SQL expression functions are coerced into fixed constructs. For example, given a comparison operation such as:

    1. expr = users_table.c.name == 'Wendy'

    The above expression will produce a BinaryExpression construct, where the left side is the object representing the name column, and the right side is a BindParameter representing the literal value:

    1. print(repr(expr.right))
    2. BindParameter('%(4327771088 name)s', 'Wendy', type_=String())

    The expression above will render SQL such as:

    1. user.name = :name_1

    Where the :name_1 parameter name is an anonymous name. The actual string Wendy is not in the rendered string, but is carried along where it is later used within statement execution. If we invoke a statement like the following:

    1. stmt = select(users_table).where(users_table.c.name == 'Wendy')
    2. result = connection.execute(stmt)

    We would see SQL logging output as:

    1. SELECT "user".id, "user".name
    2. FROM "user"
    3. WHERE "user".name = %(name_1)s
    4. {'name_1': 'Wendy'}

    Above, we see that Wendy is passed as a parameter to the database, while the placeholder :name_1 is rendered in the appropriate form for the target database, in this case the PostgreSQL database.

    Similarly, is invoked automatically when working with CRUD statements as far as the “VALUES” portion is concerned. The construct produces an INSERT expression which will, at statement execution time, generate bound placeholders based on the arguments passed, as in:

    1. stmt = users_table.insert()
    2. result = connection.execute(stmt, name='Wendy')

    The above will produce SQL output as:

    1. INSERT INTO "user" (name) VALUES (%(name)s)
    2. {'name': 'Wendy'}

    The Insert construct, at compilation/execution time, rendered a single mirroring the column name name as a result of the single name parameter we passed to the Connection.execute() method.

    • Parameters:

      • key

        the key (e.g. the name) for this bind param. Will be used in the generated SQL statement for dialects that use named parameters. This value may be modified when part of a compilation operation, if other objects exist with the same key, or if its length is too long and truncation is required.

        If omitted, an “anonymous” name is generated for the bound parameter; when given a value to bind, the end result is equivalent to calling upon the literal() function with a value to bind, particularly if the parameter is also provided.

      • value – Initial value for this bind param. Will be used at statement execution time as the value for this parameter passed to the DBAPI, if no other value is indicated to the statement execution method for this particular parameter name. Defaults to None.

      • callable_ – A callable function that takes the place of “value”. The function will be called at statement execution time to determine the ultimate value. Used for scenarios where the actual bind value cannot be determined at the point at which the clause construct is created, but embedded bind values are still desirable.

      • type_

        A TypeEngine class or instance representing an optional datatype for this . If not passed, a type may be determined automatically for the bind, based on the given value; for example, trivial Python types such as str, int, bool may result in the String, or Boolean types being automatically selected.

        The type of a is significant especially in that the type will apply pre-processing to the value before it is passed to the database. For example, a bindparam() which refers to a datetime value, and is specified as holding the type, may apply conversion needed to the value (such as stringification on SQLite) before passing the value to the database.

      • unique – if True, the key name of this BindParameter will be modified if another of the same name already has been located within the containing expression. This flag is used generally by the internals when producing so-called “anonymous” bound expressions, it isn’t generally applicable to explicitly-named bindparam() constructs.

      • required – If True, a value is required at execution time. If not passed, it defaults to True if neither or bindparam.callable were passed. If either of these parameters are present, then defaults to False.

      • quote – True if this parameter name requires quoting and is not currently known as a SQLAlchemy reserved word; this currently only applies to the Oracle backend, where bound names must sometimes be quoted.

      • isoutparam – if True, the parameter should be treated like a stored procedure “OUT” parameter. This applies to backends such as Oracle which support OUT parameters.

      • expanding

        if True, this parameter will be treated as an “expanding” parameter at execution time; the parameter value is expected to be a sequence, rather than a scalar value, and the string SQL statement will be transformed on a per-execution basis to accommodate the sequence with a variable number of parameter slots passed to the DBAPI. This is to allow statement caching to be used in conjunction with an IN clause.

        See also

        ColumnOperators.in_()

        - with baked queries

        Note

        The “expanding” feature does not support “executemany”- style parameter sets.

        New in version 1.2.

        Changed in version 1.3: the “expanding” bound parameter feature now supports empty lists.

      • literal_execute

        if True, the bound parameter will be rendered in the compile phase with a special “POSTCOMPILE” token, and the SQLAlchemy compiler will render the final value of the parameter into the SQL statement at statement execution time, omitting the value from the parameter dictionary / list passed to DBAPI cursor.execute(). This produces a similar effect as that of using the literal_binds, compilation flag, however takes place as the statement is sent to the DBAPI cursor.execute() method, rather than when the statement is compiled. The primary use of this capability is for rendering LIMIT / OFFSET clauses for database drivers that can’t accommodate for bound parameters in these contexts, while allowing SQL constructs to be cacheable at the compilation level.

        New in version 1.4: Added “post compile” bound parameters

        See also

        New “post compile” bound parameters used for LIMIT/OFFSET in Oracle, SQL Server.

    See also

    - in the SQLAlchemy Unified Tutorial

    function sqlalchemy.sql.expression.case(*whens: Union[typing_Tuple[_ColumnExpressionArgument[bool], Any], Mapping[Any, Any]], value: Optional[Any] = None, else\: Optional[Any] = None_) → [Any]

    Produce a CASE expression.

    The CASE construct in SQL is a conditional object that acts somewhat analogously to an “if/then” construct in other languages. It returns an instance of Case.

    in its usual form is passed a series of “when” constructs, that is, a list of conditions and results as tuples:

    1. from sqlalchemy import case
    2. stmt = select(users_table).\
    3. where(
    4. case(
    5. (users_table.c.name == 'wendy', 'W'),
    6. (users_table.c.name == 'jack', 'J'),
    7. else_='E'
    8. )
    9. )

    The above statement will produce SQL resembling:

    1. SELECT id, name FROM user
    2. WHERE CASE
    3. WHEN (name = :name_1) THEN :param_1
    4. WHEN (name = :name_2) THEN :param_2
    5. ELSE :param_3
    6. END

    When simple equality expressions of several values against a single parent column are needed, case() also has a “shorthand” format used via the parameter, which is passed a column expression to be compared. In this form, the case.whens parameter is passed as a dictionary containing expressions to be compared against keyed to result expressions. The statement below is equivalent to the preceding statement:

    1. stmt = select(users_table).\
    2. where(
    3. case(
    4. {"wendy": "W", "jack": "J"},
    5. value=users_table.c.name,
    6. else_='E'
    7. )
    8. )

    The values which are accepted as result values in as well as with case.else_ are coerced from Python literals into constructs. SQL expressions, e.g. ColumnElement constructs, are accepted as well. To coerce a literal string expression into a constant expression rendered inline, use the construct, as in:

    1. from sqlalchemy import case, literal_column
    2. case(
    3. (
    4. orderline.c.qty > 100,
    5. literal_column("'greaterthan100'")
    6. ),
    7. (
    8. orderline.c.qty > 10,
    9. literal_column("'greaterthan10'")
    10. ),
    11. else_=literal_column("'lessthan10'")
    12. )

    The above will render the given constants without using bound parameters for the result values (but still for the comparison values), as in:

    1. CASE
    2. WHEN (orderline.qty > :qty_1) THEN 'greaterthan100'
    3. WHEN (orderline.qty > :qty_2) THEN 'greaterthan10'
    4. ELSE 'lessthan10'
    5. END
    • Parameters:

      • *whens

        The criteria to be compared against, case.whens accepts two different forms, based on whether or not is used.

        Changed in version 1.4: the case() function now accepts the series of WHEN conditions positionally

        In the first form, it accepts a list of 2-tuples; each 2-tuple consists of (<sql expression>, <value>), where the SQL expression is a boolean expression and “value” is a resulting value, e.g.:

        1. case(
        2. (users_table.c.name == 'wendy', 'W'),
        3. (users_table.c.name == 'jack', 'J')
        4. )

        In the second form, it accepts a Python dictionary of comparison values mapped to a resulting value; this form requires to be present, and values will be compared using the == operator, e.g.:

        1. case(
        2. {"wendy": "W", "jack": "J"},
        3. value=users_table.c.name
        4. )
      • value – An optional SQL expression which will be used as a fixed “comparison point” for candidate values within a dictionary passed to case.whens.

      • else_ – An optional SQL expression which will be the evaluated result of the CASE construct if all expressions within evaluate to false. When omitted, most databases will produce a result of NULL if none of the “when” expressions evaluate to true.

    function sqlalchemy.sql.expression.cast(expression: _ColumnExpressionOrLiteralArgument[Any], type\: _TypeEngineArgument[_T]_) → Cast[_T]

    Produce a CAST expression.

    returns an instance of Cast.

    E.g.:

    1. from sqlalchemy import cast, Numeric
    2. stmt = select(cast(product_table.c.unit_price, Numeric(10, 4)))

    The above statement will produce SQL resembling:

    1. SELECT CAST(unit_price AS NUMERIC(10, 4)) FROM product

    The function performs two distinct functions when used. The first is that it renders the CAST expression within the resulting SQL string. The second is that it associates the given type (e.g. TypeEngine class or instance) with the column expression on the Python side, which means the expression will take on the expression operator behavior associated with that type, as well as the bound-value handling and result-row-handling behavior of the type.

    Changed in version 0.9.0: now applies the given type to the expression such that it takes effect on the bound-value, e.g. the Python-to-database direction, in addition to the result handling, e.g. database-to-Python, direction.

    An alternative to cast() is the function. This function performs the second task of associating an expression with a specific type, but does not render the CAST expression in SQL.

    • Parameters:

      • expression – A SQL expression, such as a ColumnElement expression or a Python string which will be coerced into a bound literal value.

      • type_ – A class or instance indicating the type to which the CAST should apply.

    See also

    Data Casts and Type Coercion

    - an alternative to CAST that coerces the type on the Python side only, which is often sufficient to generate the correct SQL and data coercion.

    function sqlalchemy.sql.expression.column(text: str, type\: Optional[_TypeEngineArgument[_T]] = None, _is_literal: bool = False, _selectable: Optional[FromClause] = None) → [_T]

    Produce a ColumnClause object.

    The is a lightweight analogue to the Column class. The function can be invoked with just a name alone, as in:

    1. from sqlalchemy import column
    2. id, name = column("id"), column("name")
    3. stmt = select(id, name).select_from("user")

    The above statement would produce SQL like:

    1. SELECT id, name FROM user

    Once constructed, column() may be used like any other SQL expression element such as within constructs:

    1. from sqlalchemy.sql import column
    2. id, name = column("id"), column("name")
    3. stmt = select(id, name).select_from("user")

    The text handled by column() is assumed to be handled like the name of a database column; if the string contains mixed case, special characters, or matches a known reserved word on the target backend, the column expression will render using the quoting behavior determined by the backend. To produce a textual SQL expression that is rendered exactly without any quoting, use instead, or pass True as the value of column.is_literal. Additionally, full SQL statements are best handled using the construct.

    column() can be used in a table-like fashion by combining it with the function (which is the lightweight analogue to Table ) to produce a working table construct with minimal boilerplate:

    1. from sqlalchemy import table, column, select
    2. user = table("user",
    3. column("id"),
    4. column("name"),
    5. column("description"),
    6. )
    7. stmt = select(user.c.description).where(user.c.name == 'wendy')

    A / table() construct like that illustrated above can be created in an ad-hoc fashion and is not associated with any , DDL, or events, unlike its Table counterpart.

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

    • Parameters:

      • text – the text of the element.

      • typeTypeEngine object which can associate this with a type.

      • is_literal – if True, the ColumnClause is assumed to be an exact expression that will be delivered to the output with no quoting rules applied regardless of case sensitive settings. the function essentially invokes column() while passing is_literal=True.

    See also

    literal_column()

    text()

    class sqlalchemy.sql.expression.custom_op

    Represent a ‘custom’ operator.

    custom_op is normally instantiated when the or Operators.bool_op() methods are used to create a custom operator callable. The class can also be used directly when programmatically constructing expressions. E.g. to represent the “factorial” operation:

    1. from sqlalchemy.sql import UnaryExpression
    2. from sqlalchemy.sql import operators
    3. from sqlalchemy import Numeric
    4. unary = UnaryExpression(table.c.somecolumn,
    5. modifier=operators.custom_op("!"),
    6. type_=Numeric)

    See also

    Operators.bool_op()

    Class signature

    class (sqlalchemy.sql.expression.OperatorType, typing.Generic)

    function sqlalchemy.sql.expression.distinct(expr: _ColumnExpressionArgument[_T]) → UnaryExpression[_T]

    Produce an column-expression-level unary DISTINCT clause.

    This applies the DISTINCT keyword to an individual column expression, and is typically contained within an aggregate function, as in:

    1. from sqlalchemy import distinct, func
    2. stmt = select(func.count(distinct(users_table.c.name)))

    The above would produce an expression resembling:

    1. SELECT COUNT(DISTINCT name) FROM user

    The function is also available as a column-level method, e.g. ColumnElement.distinct(), as in:

    1. stmt = select(func.count(users_table.c.name.distinct()))

    The operator is different from the Select.distinct() method of , which produces a SELECT statement with DISTINCT applied to the result set as a whole, e.g. a SELECT DISTINCT expression. See that method for further information.

    See also

    ColumnElement.distinct()

    func

    function sqlalchemy.sql.expression.extract(field: str, expr: _ColumnExpressionArgument[Any]) →

    Return a Extract construct.

    This is typically available as as well as func.extract from the func namespace.

    • Parameters:

      • field – The field to extract.

      • expr – A column or Python scalar expression serving as the right side of the EXTRACT expression.

    E.g.:

    1. from sqlalchemy import extract
    2. from sqlalchemy import table, column
    3. logged_table = table("user",
    4. column("id"),
    5. column("date_created"),
    6. )
    7. stmt = select(logged_table.c.id).where(
    8. extract("YEAR", logged_table.c.date_created) == 2021
    9. )

    In the above example, the statement is used to select ids from the database where the YEAR component matches a specific value.

    Similarly, one can also select an extracted component:

    1. stmt = select(
    2. extract("YEAR", logged_table.c.date_created)
    3. ).where(logged_table.c.id == 1)

    The implementation of EXTRACT may vary across database backends. Users are reminded to consult their database documentation.

    function sqlalchemy.sql.expression.false() →

    Return a False_ construct.

    E.g.:

    1. >>> from sqlalchemy import false
    2. >>> print(select(t.c.x).where(false()))
    3. SELECT x FROM t WHERE false

    A backend which does not support true/false constants will render as an expression against 1 or 0:

    1. >>> print(select(t.c.x).where(false()))
    2. SELECT x FROM t WHERE 0 = 1

    The and false() constants also feature “short circuit” operation within an or or_() conjunction:

    1. >>> print(select(t.c.x).where(or_(t.c.x > 5, true())))
    2. SELECT x FROM t WHERE true
    3. >>> print(select(t.c.x).where(and_(t.c.x > 5, false())))
    4. SELECT x FROM t WHERE false

    Changed in version 0.9: and false() feature better integrated behavior within conjunctions and on dialects that don’t support true/false constants.

    See also

    sqlalchemy.sql.expression.func = <sqlalchemy.sql.functions._FunctionGenerator object>

    Generate SQL function expressions.

    func is a special object instance which generates SQL functions based on name-based attributes, e.g.:

    1. >>> print(func.count(1))
    2. count(:param_1)

    The returned object is an instance of , and is a column-oriented SQL element like any other, and is used in that way:

    1. >>> print(select(func.count(table.c.id)))
    2. SELECT count(sometable.id) FROM sometable

    Any name can be given to func. If the function name is unknown to SQLAlchemy, it will be rendered exactly as is. For common SQL functions which SQLAlchemy is aware of, the name may be interpreted as a generic function which will be compiled appropriately to the target database:

    1. >>> print(func.current_timestamp())
    2. CURRENT_TIMESTAMP

    To call functions which are present in dot-separated packages, specify them in the same manner:

    1. >>> print(func.stats.yield_curve(5, 10))
    2. stats.yield_curve(:yield_curve_1, :yield_curve_2)

    SQLAlchemy can be made aware of the return type of functions to enable type-specific lexical and result-based behavior. For example, to ensure that a string-based function returns a Unicode value and is similarly treated as a string in expressions, specify as the type:

    1. >>> print(func.my_string(u'hi', type_=Unicode) + ' ' +
    2. ... func.my_string(u'there', type_=Unicode))
    3. my_string(:my_string_1) || :my_string_2 || my_string(:my_string_3)

    The object returned by a func call is usually an instance of . This object meets the “column” interface, including comparison and labeling functions. The object can also be passed the Connectable.execute() method of a Connection or , where it will be wrapped inside of a SELECT statement first:

    1. print(connection.execute(func.current_timestamp()).scalar())

    In a few exception cases, the func accessor will redirect a name to a built-in expression such as or extract(), as these names have well-known meaning but are not exactly the same as “functions” from a SQLAlchemy perspective.

    Functions which are interpreted as “generic” functions know how to calculate their return type automatically. For a listing of known generic functions, see .

    Note

    The func construct has only limited support for calling standalone “stored procedures”, especially those with special parameterization concerns.

    See the section for details on how to use the DBAPI-level callproc() method for fully traditional stored procedures.

    See also

    Working with SQL Functions - in the

    Function

    function sqlalchemy.sql.expression.lambda_stmt(lmb: Callable[[], Any], enable_tracking: bool = True, track_closure_variables: bool = True, track_on: Optional[object] = None, global_track_bound_values: bool = True, track_bound_values: bool = True, lambda_cache: Optional[MutableMapping[Tuple[Any, …], Union[NonAnalyzedFunction, AnalyzedFunction]]] = None) →

    Produce a SQL statement that is cached as a lambda.

    The Python code object within the lambda is scanned for both Python literals that will become bound parameters as well as closure variables that refer to Core or ORM constructs that may vary. The lambda itself will be invoked only once per particular set of constructs detected.

    E.g.:

    1. from sqlalchemy import lambda_stmt
    2. stmt = lambda_stmt(lambda: table.select())
    3. stmt += lambda s: s.where(table.c.id == 5)
    4. result = connection.execute(stmt)

    The object returned is an instance of StatementLambdaElement.

    New in version 1.4.

    • Parameters:

      • lmb – a Python function, typically a lambda, which takes no arguments and returns a SQL expression construct

      • enable_tracking – when False, all scanning of the given lambda for changes in closure variables or bound parameters is disabled. Use for a lambda that produces the identical results in all cases with no parameterization.

      • track_closure_variables – when False, changes in closure variables within the lambda will not be scanned. Use for a lambda where the state of its closure variables will never change the SQL structure returned by the lambda.

      • track_bound_values – when False, bound parameter tracking will be disabled for the given lambda. Use for a lambda that either does not produce any bound values, or where the initial bound values never change.

      • global_track_bound_values – when False, bound parameter tracking will be disabled for the entire statement including additional links added via the method.

      • lambda_cache – a dictionary or other mapping-like object where information about the lambda’s Python code as well as the tracked closure variables in the lambda itself will be stored. Defaults to a global LRU cache. This cache is independent of the “compiled_cache” used by the Connection object.

    See also

    function sqlalchemy.sql.expression.literal(value: Any, type\: Optional[_TypeEngineArgument[_T]] = None, _literal_execute: bool = False) → BindParameter[_T]

    Return a literal clause, bound to a bind parameter.

    Literal clauses are created automatically when non- objects (such as strings, ints, dates, etc.) are used in a comparison operation with a ColumnElement subclass, such as a object. Use this function to force the generation of a literal clause, which will be created as a BindParameter with a bound value.

    • Parameters:

      • value – the value to be bound. Can be any Python object supported by the underlying DB-API, or is translatable via the given type argument.

      • type_ – an optional which will provide bind-parameter translation for this literal.

      • literal_execute

        optional bool, when True, the SQL engine will attempt to render the bound value directly in the SQL statement at execution time rather than providing as a parameter value.

        New in version 2.0.

    function sqlalchemy.sql.expression.literal_column(text: str, type\: Optional[_TypeEngineArgument[_T]] = None_) → ColumnClause[_T]

    Produce a object that has the column.is_literal flag set to True.

    is similar to column(), except that it is more often used as a “standalone” column expression that renders exactly as stated; while stores a string name that will be assumed to be part of a table and may be quoted as such, literal_column() can be that, or any other arbitrary column-oriented expression.

    • Parameters:

      • text – the text of the expression; can be any SQL expression. Quoting rules will not be applied. To specify a column-name expression which should be subject to quoting rules, use the function.

      • type_ – an optional TypeEngine object which will provide result-set translation and additional expression semantics for this column. If left as None the type will be .

    See also

    column()

    Selecting with Textual Column Expressions

    function sqlalchemy.sql.expression.not_(clause: _ColumnExpressionArgument[_T]) → [_T]

    Return a negation of the given clause, i.e. NOT(clause).

    The ~ operator is also overloaded on all ColumnElement subclasses to produce the same result.

    function sqlalchemy.sql.expression.null() →

    Return a constant Null construct.

    function sqlalchemy.sql.expression.or_(*clauses)

    function sqlalchemy.sql.expression.outparam(key: str, type\: Optional[[_T]] = None_) → BindParameter[_T]

    Create an ‘OUT’ parameter for usage in functions (stored procedures), for databases which support them.

    The outparam can be used like a regular function parameter. The “output” value will be available from the object via its out_parameters attribute, which returns a dictionary containing the values.

    function sqlalchemy.sql.expression.text(text: str) → TextClause

    Construct a new clause, representing a textual SQL string directly.

    E.g.:

    1. from sqlalchemy import text
    2. t = text("SELECT * FROM users")
    3. result = connection.execute(t)

    The advantages text() provides over a plain string are backend-neutral support for bind parameters, per-statement execution options, as well as bind parameter and result-column typing behavior, allowing SQLAlchemy type constructs to play a role when executing a statement that is specified literally. The construct can also be provided with a .c collection of column elements, allowing it to be embedded in other SQL expression constructs as a subquery.

    Bind parameters are specified by name, using the format :name. E.g.:

    1. t = text("SELECT * FROM users WHERE id=:user_id")
    2. result = connection.execute(t, user_id=12)

    For SQL statements where a colon is required verbatim, as within an inline string, use a backslash to escape:

    1. t = text(r"SELECT * FROM users WHERE name='\:username'")

    The construct includes methods which can provide information about the bound parameters as well as the column values which would be returned from the textual statement, assuming it’s an executable SELECT type of statement. The TextClause.bindparams() method is used to provide bound parameter detail, and method allows specification of return columns including names and types:

    1. t = text("SELECT * FROM users WHERE id=:user_id").\
    2. bindparams(user_id=7).\
    3. columns(id=Integer, name=String)
    4. for id, name in connection.execute(t):
    5. print(id, name)

    The text() construct is used in cases when a literal string SQL fragment is specified as part of a larger query, such as for the WHERE clause of a SELECT statement:

    1. s = select(users.c.id, users.c.name).where(text("id=:user_id"))
    2. result = connection.execute(s, user_id=12)

    is also used for the construction of a full, standalone statement using plain text. As such, SQLAlchemy refers to it as an Executable object and may be used like any other statement passed to an .execute() method.

    • Parameters:

      text

      the text of the SQL statement to be created. Use :<param> to specify bind parameters; they will be compiled to their engine-specific format.

      Warning

      The argument to text() can be passed as a Python string argument, which will be treated as trusted SQL text and rendered as given. DO NOT PASS UNTRUSTED INPUT TO THIS PARAMETER.

    See also

    function sqlalchemy.sql.expression.true() → True_

    Return a constant construct.

    E.g.:

    1. >>> from sqlalchemy import true
    2. >>> print(select(t.c.x).where(true()))
    3. SELECT x FROM t WHERE true

    A backend which does not support true/false constants will render as an expression against 1 or 0:

    1. >>> print(select(t.c.x).where(true()))
    2. SELECT x FROM t WHERE 1 = 1

    The true() and constants also feature “short circuit” operation within an and_() or conjunction:

    1. >>> print(select(t.c.x).where(or_(t.c.x > 5, true())))
    2. SELECT x FROM t WHERE true
    3. >>> print(select(t.c.x).where(and_(t.c.x > 5, false())))
    4. SELECT x FROM t WHERE false

    Changed in version 0.9: true() and feature better integrated behavior within conjunctions and on dialects that don’t support true/false constants.

    See also

    false()

    function sqlalchemy.sql.expression.tuple_(*clauses: _ColumnExpressionArgument[Any], types: Optional[[_TypeEngineArgument[Any]]] = None) → Tuple

    Return a .

    Main usage is to produce a composite IN construct using ColumnOperators.in_()

    1. from sqlalchemy import tuple_
    2. tuple_(table.c.col1, table.c.col2).in_(
    3. [(1, 2), (5, 12), (10, 19)]
    4. )

    Changed in version 1.3.6: Added support for SQLite IN tuples.

    Warning

    The composite IN construct is not supported by all backends, and is currently known to work on PostgreSQL, MySQL, and SQLite. Unsupported backends will raise a subclass of when such an expression is invoked.

    function sqlalchemy.sql.expression.type_coerce(expression: _ColumnExpressionOrLiteralArgument[Any], type\: _TypeEngineArgument[_T]_) → TypeCoerce[_T]

    Associate a SQL expression with a particular type, without rendering CAST.

    E.g.:

    1. from sqlalchemy import type_coerce
    2. stmt = select(type_coerce(log_table.date_string, StringDateTime()))

    The above construct will produce a object, which does not modify the rendering in any way on the SQL side, with the possible exception of a generated label if used in a columns clause context:

    1. SELECT date_string AS date_string FROM log

    When result rows are fetched, the StringDateTime type processor will be applied to result rows on behalf of the date_string column.

    Note

    the type_coerce() construct does not render any SQL syntax of its own, including that it does not imply parenthesization. Please use if explicit parenthesization is required.

    In order to provide a named label for the expression, use ColumnElement.label():

    1. stmt = select(
    2. type_coerce(log_table.date_string, StringDateTime()).label('date')
    3. )

    A type that features bound-value handling will also have that behavior take effect when literal values or constructs are passed to type_coerce() as targets. For example, if a type implements the method or TypeEngine.bind_processor() method or equivalent, these functions will take effect at statement compilation/execution time when a literal value is passed, as in:

    1. # bound-value handling of MyStringType will be applied to the
    2. # literal value "some string"
    3. stmt = select(type_coerce("some string", MyStringType))

    When using with composed expressions, note that parenthesis are not applied. If type_coerce() is being used in an operator context where the parenthesis normally present from CAST are necessary, use the method:

    1. >>> some_integer = column("someint", Integer)
    2. >>> some_string = column("somestr", String)
    3. >>> expr = type_coerce(some_integer + 5, String) + some_string
    4. >>> print(expr)
    5. someint + :someint_1 || somestr
    6. >>> expr = type_coerce(some_integer + 5, String).self_group() + some_string
    7. >>> print(expr)
    8. (someint + :someint_1) || somestr
    • Parameters:

      • expression – A SQL expression, such as a ColumnElement expression or a Python string which will be coerced into a bound literal value.

      • type_ – A class or instance indicating the type to which the expression is coerced.

    See also

    Data Casts and Type Coercion

    class sqlalchemy.sql.expression.quoted_name

    Represent a SQL identifier combined with quoting preferences.

    quoted_name is a Python unicode/str subclass which represents a particular identifier name along with a quote flag. This quote flag, when set to True or False, overrides automatic quoting behavior for this identifier in order to either unconditionally quote or to not quote the name. If left at its default of None, quoting behavior is applied to the identifier on a per-backend basis based on an examination of the token itself.

    A object with quote=True is also prevented from being modified in the case of a so-called “name normalize” option. Certain database backends, such as Oracle, Firebird, and DB2 “normalize” case-insensitive names as uppercase. The SQLAlchemy dialects for these backends convert from SQLAlchemy’s lower-case-means-insensitive convention to the upper-case-means-insensitive conventions of those backends. The quote=True flag here will prevent this conversion from occurring to support an identifier that’s quoted as all lower case against such a backend.

    The quoted_name object is normally created automatically when specifying the name for key schema constructs such as , Column, and others. The class can also be passed explicitly as the name to any function that receives a name which can be quoted. Such as to use the Engine.has_table() method with an unconditionally quoted name:

    1. from sqlalchemy import create_engine
    2. from sqlalchemy import inspect
    3. from sqlalchemy.sql import quoted_name
    4. engine = create_engine("oracle+cx_oracle://some_dsn")
    5. print(inspect(engine).has_table(quoted_name("some_table", True)))

    The above logic will run the “has table” logic against the Oracle backend, passing the name exactly as "some_table" without converting to upper case.

    New in version 0.9.0.

    Changed in version 1.2: The construct is now importable from sqlalchemy.sql, in addition to the previous location of sqlalchemy.sql.elements.

    Members

    quote

    Class signature

    class (sqlalchemy.util.langhelpers.MemoizedSlots, builtins.str)

    Functions listed here are more commonly available as methods from any ColumnElement construct, for example, the function is usually invoked via the ColumnElement.label() method.

    function sqlalchemy.sql.expression.all_(expr: _ColumnExpressionArgument[_T]) → CollectionAggregate[bool]

    Produce an ALL expression.

    For dialects such as that of PostgreSQL, this operator applies to usage of the datatype, for that of MySQL, it may apply to a subquery. e.g.:

    1. # renders on PostgreSQL:
    2. # '5 = ALL (somearray)'
    3. expr = 5 == all_(mytable.c.somearray)
    4. # renders on MySQL:
    5. # '5 = ALL (SELECT value FROM table)'
    6. expr = 5 == all_(select(table.c.value))

    Comparison to NULL may work using None:

    1. None == all_(mytable.c.somearray)

    The any_() / all_() operators also feature a special “operand flipping” behavior such that if any_() / all_() are used on the left side of a comparison using a standalone operator such as ==, !=, etc. (not including operator methods such as ColumnOperators.is_()) the rendered expression is flipped:

    1. # would render '5 = ALL (column)`
    2. all_(mytable.c.column) == 5

    Or with None, which note will not perform the usual step of rendering “IS” as is normally the case for NULL:

    1. # would render 'NULL = ALL(somearray)'
    2. all_(mytable.c.somearray) == None

    Changed in version 1.4.26: repaired the use of any_() / all_() comparing to NULL on the right side to be flipped to the left.

    The column-level method (not to be confused with ARRAY level ) is shorthand for all_(col):

    1. 5 == mytable.c.somearray.all_()

    See also

    ColumnOperators.all_()

    function sqlalchemy.sql.expression.any_(expr: _ColumnExpressionArgument[_T]) → CollectionAggregate[bool]

    Produce an ANY expression.

    For dialects such as that of PostgreSQL, this operator applies to usage of the ARRAY datatype, for that of MySQL, it may apply to a subquery. e.g.:

    1. # renders on PostgreSQL:
    2. # '5 = ANY (somearray)'
    3. expr = 5 == any_(mytable.c.somearray)
    4. # renders on MySQL:
    5. # '5 = ANY (SELECT value FROM table)'
    6. expr = 5 == any_(select(table.c.value))

    Comparison to NULL may work using None or :

    1. None == any_(mytable.c.somearray)

    The any_() / all_() operators also feature a special “operand flipping” behavior such that if any_() / all_() are used on the left side of a comparison using a standalone operator such as ==, !=, etc. (not including operator methods such as ColumnOperators.is_()) the rendered expression is flipped:

    1. # would render '5 = ANY (column)`
    2. any_(mytable.c.column) == 5

    Or with None, which note will not perform the usual step of rendering “IS” as is normally the case for NULL:

    1. # would render 'NULL = ANY(somearray)'
    2. any_(mytable.c.somearray) == None

    Changed in version 1.4.26: repaired the use of any_() / all_() comparing to NULL on the right side to be flipped to the left.

    The column-level method (not to be confused with ARRAY level ) is shorthand for any_(col):

    1. 5 = mytable.c.somearray.any_()

    See also

    ColumnOperators.any_()

    function sqlalchemy.sql.expression.asc(column: _ColumnExpressionOrStrLabelArgument[_T]) → UnaryExpression[_T]

    Produce an ascending ORDER BY clause element.

    e.g.:

    1. from sqlalchemy import asc
    2. stmt = select(users_table).order_by(asc(users_table.c.name))

    will produce SQL as:

    1. SELECT id, name FROM user ORDER BY name ASC

    The function is a standalone version of the ColumnElement.asc() method available on all SQL expressions, e.g.:

    1. stmt = select(users_table).order_by(users_table.c.name.asc())
    • Parameters:

      column – A (e.g. scalar SQL expression) with which to apply the asc() operation.

    See also

    nulls_first()

    Select.order_by()

    function sqlalchemy.sql.expression.between(expr: _ColumnExpressionOrLiteralArgument[_T], lower_bound: Any, upper_bound: Any, symmetric: bool = False) → [bool]

    Produce a BETWEEN predicate clause.

    E.g.:

    1. from sqlalchemy import between
    2. stmt = select(users_table).where(between(users_table.c.id, 5, 7))

    Would produce SQL resembling:

    1. SELECT id, name FROM user WHERE id BETWEEN :id_1 AND :id_2

    The between() function is a standalone version of the method available on all SQL expressions, as in:

    1. stmt = select(users_table).where(users_table.c.id.between(5, 7))

    All arguments passed to between(), including the left side column expression, are coerced from Python scalar values if a the value is not a subclass. For example, three fixed values can be compared as in:

    1. print(between(5, 3, 7))

    Which would produce:

    1. :param_1 BETWEEN :param_2 AND :param_3
    • Parameters:

      • expr – a column expression, typically a ColumnElement instance or alternatively a Python scalar expression to be coerced into a column expression, serving as the left side of the BETWEEN expression.

      • lower_bound – a column or Python scalar expression serving as the lower bound of the right side of the BETWEEN expression.

      • upper_bound – a column or Python scalar expression serving as the upper bound of the right side of the BETWEEN expression.

      • symmetric

        if True, will render “ BETWEEN SYMMETRIC “. Note that not all databases support this syntax.

        New in version 0.9.5.

    See also

    function sqlalchemy.sql.expression.collate(expression: _ColumnExpressionArgument[str], collation: str) → BinaryExpression[str]

    Return the clause expression COLLATE collation.

    e.g.:

    1. collate(mycolumn, 'utf8_bin')

    produces:

    1. mycolumn COLLATE utf8_bin

    The collation expression is also quoted if it is a case sensitive identifier, e.g. contains uppercase characters.

    Changed in version 1.2: quoting is automatically applied to COLLATE expressions if they are case sensitive.

    function sqlalchemy.sql.expression.desc(column: _ColumnExpressionOrStrLabelArgument[_T]) → [_T]

    Produce a descending ORDER BY clause element.

    e.g.:

    1. from sqlalchemy import desc
    2. stmt = select(users_table).order_by(desc(users_table.c.name))

    will produce SQL as:

    1. SELECT id, name FROM user ORDER BY name DESC

    The desc() function is a standalone version of the method available on all SQL expressions, e.g.:

    1. stmt = select(users_table).order_by(users_table.c.name.desc())
    • Parameters:

      column – A ColumnElement (e.g. scalar SQL expression) with which to apply the operation.

    See also

    asc()

    nulls_last()

    function sqlalchemy.sql.expression.funcfilter(func: FunctionElement[_T], *criterion: _ColumnExpressionArgument[bool]) → [_T]

    Produce a FunctionFilter object against a function.

    Used against aggregate and window functions, for database backends that support the “FILTER” clause.

    E.g.:

    1. from sqlalchemy import funcfilter
    2. funcfilter(func.count(1), MyClass.name == 'some name')

    Would produce “COUNT(1) FILTER (WHERE myclass.name = ‘some name’)”.

    This function is also available from the construct itself via the FunctionElement.filter() method.

    New in version 1.0.0.

    See also

    - in the SQLAlchemy Unified Tutorial

    function sqlalchemy.sql.expression.label(name: str, element: _ColumnExpressionArgument[_T], type\: Optional[_TypeEngineArgument[_T]] = None_) → Label[_T]

    Return a object for the given ColumnElement.

    A label changes the name of an element in the columns clause of a SELECT statement, typically via the AS SQL keyword.

    This functionality is more conveniently available via the method on ColumnElement.

    • Parameters:

      • name – label name

      • obj – a .

    function sqlalchemy.sql.expression.nulls_first(column: _ColumnExpressionArgument[_T]) → UnaryExpression[_T]

    Produce the NULLS FIRST modifier for an ORDER BY expression.

    is intended to modify the expression produced by asc() or , and indicates how NULL values should be handled when they are encountered during ordering:

    1. from sqlalchemy import desc, nulls_first
    2. stmt = select(users_table).order_by(
    3. nulls_first(desc(users_table.c.name)))

    The SQL expression from the above would resemble:

    1. SELECT id, name FROM user ORDER BY name DESC NULLS FIRST

    Like asc() and , nulls_first() is typically invoked from the column expression itself using , rather than as its standalone function version, as in:

    1. stmt = select(users_table).order_by(
    2. users_table.c.name.desc().nulls_first())

    Changed in version 1.4: nulls_first() is renamed from nullsfirst() in previous releases. The previous name remains available for backwards compatibility.

    See also

    desc()

    Select.order_by()

    function sqlalchemy.sql.expression.nulls_last(column: _ColumnExpressionArgument[_T]) → [_T]

    Produce the NULLS LAST modifier for an ORDER BY expression.

    nulls_last() is intended to modify the expression produced by or desc(), and indicates how NULL values should be handled when they are encountered during ordering:

    1. from sqlalchemy import desc, nulls_last
    2. stmt = select(users_table).order_by(
    3. nulls_last(desc(users_table.c.name)))

    The SQL expression from the above would resemble:

    1. SELECT id, name FROM user ORDER BY name DESC NULLS LAST

    Like and desc(), is typically invoked from the column expression itself using ColumnElement.nulls_last(), rather than as its standalone function version, as in:

    1. stmt = select(users_table).order_by(
    2. users_table.c.name.desc().nulls_last())

    Changed in version 1.4: is renamed from nullslast() in previous releases. The previous name remains available for backwards compatibility.

    See also

    asc()

    nulls_first()

    function sqlalchemy.sql.expression.over(element: FunctionElement[_T], partition_by: Optional[Union[Iterable[_ColumnExpressionArgument[Any]], _ColumnExpressionArgument[Any]]] = None, order_by: Optional[Union[Iterable[_ColumnExpressionArgument[Any]], _ColumnExpressionArgument[Any]]] = None, range\: Optional[typing_Tuple[Optional[int], Optional[int]]] = None, _rows: Optional[typing_Tuple[Optional[int], Optional[int]]] = None) → [_T]

    Produce an Over object against a function.

    Used against aggregate or so-called “window” functions, for database backends that support window functions.

    is usually called using the FunctionElement.over() method, e.g.:

    1. func.row_number().over(order_by=mytable.c.some_column)

    Would produce:

    1. ROW_NUMBER() OVER(ORDER BY some_column)

    Ranges are also possible using the and over.rows parameters. These mutually-exclusive parameters each accept a 2-tuple, which contains a combination of integers and None:

    1. func.row_number().over(
    2. order_by=my_table.c.some_column, range_=(None, 0))

    The above would produce:

    1. ROW_NUMBER() OVER(ORDER BY some_column
    2. RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)

    A value of None indicates “unbounded”, a value of zero indicates “current row”, and negative / positive integers indicate “preceding” and “following”:

    • RANGE BETWEEN 5 PRECEDING AND 10 FOLLOWING:

      1. func.row_number().over(order_by='x', range_=(-5, 10))
    • ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW:

      1. func.row_number().over(order_by='x', rows=(None, 0))
    • RANGE BETWEEN 2 PRECEDING AND UNBOUNDED FOLLOWING:

      1. func.row_number().over(order_by='x', range_=(-2, None))
    • RANGE BETWEEN 1 FOLLOWING AND 3 FOLLOWING:

      1. func.row_number().over(order_by='x', range_=(1, 3))

    New in version 1.1: support for RANGE / ROWS within a window

    • Parameters:

      • element – a , WithinGroup, or other compatible construct.

      • partition_by – a column element or string, or a list of such, that will be used as the PARTITION BY clause of the OVER construct.

      • order_by – a column element or string, or a list of such, that will be used as the ORDER BY clause of the OVER construct.

      • range_

        optional range clause for the window. This is a tuple value which can contain integer values or None, and will render a RANGE BETWEEN PRECEDING / FOLLOWING clause.

        New in version 1.1.

      • rows

        optional rows clause for the window. This is a tuple value which can contain integer values or None, and will render a ROWS BETWEEN PRECEDING / FOLLOWING clause.

        New in version 1.1.

    This function is also available from the construct itself via the FunctionElement.over() method.

    See also

    - in the SQLAlchemy Unified Tutorial

    within_group()

    function sqlalchemy.sql.expression.within_group(element: [_T], *order_by: _ColumnExpressionArgument[Any]) → WithinGroup[_T]

    Produce a object against a function.

    Used against so-called “ordered set aggregate” and “hypothetical set aggregate” functions, including percentile_cont, , dense_rank, etc.

    is usually called using the FunctionElement.within_group() method, e.g.:

    1. from sqlalchemy import within_group
    2. stmt = select(
    3. department.c.id,
    4. func.percentile_cont(0.5).within_group(
    5. department.c.salary.desc()
    6. )
    7. )

    The above statement would produce SQL similar to SELECT department.id, percentile_cont(0.5) WITHIN GROUP (ORDER BY department.salary DESC).

    • Parameters:

      • element – a construct, typically generated by func.

      • *order_by – one or more column elements that will be used as the ORDER BY clause of the WITHIN GROUP construct.

    New in version 1.1.

    See also

    - in the SQLAlchemy Unified Tutorial

    over()

    The classes here are generated using the constructors listed at Column Element Foundational Constructors and .

    class sqlalchemy.sql.expression.BinaryExpression

    Represent an expression that is LEFT <operator> RIGHT.

    A BinaryExpression is generated automatically whenever two column expressions are used in a Python binary expression:

    1. >>> from sqlalchemy.sql import column
    2. >>> column('a') + column('b')
    3. <sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
    4. >>> print(column('a') + column('b'))
    5. a + b

    Class signature

    class (sqlalchemy.sql.expression.OperatorExpression)

    class sqlalchemy.sql.expression.BindParameter

    Represent a “bound expression”.

    BindParameter is invoked explicitly using the function, as in:

    1. from sqlalchemy import bindparam
    2. stmt = select(users_table).\
    3. where(users_table.c.name == bindparam('username'))

    Detailed discussion of how BindParameter is used is at .

    See also

    bindparam()

    Members

    , inherit_cache,

    Class signature

    class sqlalchemy.sql.expression.BindParameter (sqlalchemy.sql.roles.InElementRole, sqlalchemy.sql.expression.KeyedColumnElement)

    • attribute effective_value

      Return the value of this bound parameter, taking into account if the callable parameter was set.

      The callable value will be evaluated and returned if present, else value.

    • attribute sqlalchemy.sql.expression.BindParameter.inherit_cache: Optional[bool] = True

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

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

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

      See also

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

    • method sqlalchemy.sql.expression.BindParameter.render_literal_execute() → [_T]

      Produce a copy of this bound parameter that will enable the BindParameter.literal_execute flag.

      The flag will have the effect of the parameter rendered in the compiled SQL string using [POSTCOMPILE] form, which is a special form that is converted to be a rendering of the literal value of the parameter at SQL execution time. The rationale is to support caching of SQL statement strings that can embed per-statement literal values, such as LIMIT and OFFSET parameters, in the final SQL string that is passed to the DBAPI. Dialects in particular may want to use this method within custom compilation schemes.

      New in version 1.4.5.

      See also

      Caching for Third Party Dialects

    class sqlalchemy.sql.expression.Case

    Represent a CASE expression.

    is produced using the case() factory function, as in:

    1. from sqlalchemy import case
    2. stmt = select(users_table). where(
    3. case(
    4. (users_table.c.name == 'wendy', 'W'),
    5. (users_table.c.name == 'jack', 'J'),
    6. else_='E'
    7. )
    8. )

    Details on usage is at case().

    See also

    Class signature

    class sqlalchemy.sql.expression.Case ()

    class sqlalchemy.sql.expression.Cast

    Represent a CAST expression.

    Cast is produced using the factory function, as in:

    1. from sqlalchemy import cast, Numeric
    2. stmt = select(cast(product_table.c.unit_price, Numeric(10, 4)))

    Details on Cast usage is at .

    See also

    Data Casts and Type Coercion

    type_coerce() - an alternative to CAST that coerces the type on the Python side only, which is often sufficient to generate the correct SQL and data coercion.

    Class signature

    class (sqlalchemy.sql.expression.WrapsColumnExpression)

    class sqlalchemy.sql.expression.ClauseList

    Describe a list of clauses, separated by an operator.

    By default, is comma-separated, such as a column listing.

    Members

    self_group()

    Class signature

    class (sqlalchemy.sql.roles.InElementRole, sqlalchemy.sql.roles.OrderByRole, sqlalchemy.sql.roles.ColumnsClauseRole, sqlalchemy.sql.roles.DMLColumnRole, sqlalchemy.sql.expression.DQLDMLClauseElement)

    • method sqlalchemy.sql.expression.ClauseList.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 self_group() method of just returns self.

    class sqlalchemy.sql.expression.ColumnClause

    Represents a column expression from any textual string.

    The ColumnClause, a lightweight analogue to the class, is typically invoked using the column() function, as in:

    1. from sqlalchemy import column
    2. id, name = column("id"), column("name")
    3. stmt = select(id, name).select_from("user")

    The above statement would produce SQL like:

    1. SELECT id, name FROM user

    is the immediate superclass of the schema-specific Column object. While the class has all the same capabilities as ColumnClause, the class is usable by itself in those cases where behavioral requirements are limited to simple SQL expression generation. The object has none of the associations with schema-level metadata or with execution-time behavior that Column does, so in that sense is a “lightweight” version of .

    Full details on ColumnClause usage is at .

    See also

    column()

    Members

    get_children()

    Class signature

    class (sqlalchemy.sql.roles.DDLReferredColumnRole, sqlalchemy.sql.roles.LabeledColumnExprRole, sqlalchemy.sql.roles.StrAsPlainColumnRole, sqlalchemy.sql.expression.Immutable, sqlalchemy.sql.expression.NamedColumn)

    • method sqlalchemy.sql.expression.ColumnClause.get_children(*, column_tables=False, **kw)

      Return immediate child HasTraverseInternals elements of this HasTraverseInternals.

      This is used for visit traversal.

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

    class sqlalchemy.sql.expression.ColumnCollection

    Collection of instances, typically for FromClause objects.

    The object is most commonly available as the Table.c or collection on the Table object, introduced at .

    The ColumnCollection has both mapping- and sequence- like behaviors. A usually stores Column objects, which are then accessible both via mapping style access as well as attribute access style.

    To access objects using ordinary attribute-style access, specify the name like any other object attribute, such as below a column named employee_name is accessed:

    1. >>> employee_table.c.employee_name

    To access columns that have names with special characters or spaces, index-style access is used, such as below which illustrates a column named employee ' payment is accessed:

    1. >>> employee_table.c["employee ' payment"]

    As the ColumnCollection object provides a Python dictionary interface, common dictionary method names like , ColumnCollection.values(), and are available, which means that database columns that are keyed under these names also need to use indexed access:

    1. >>> employee_table.c["values"]
    1. >>> from sqlalchemy import select, column, table
    2. >>> from sqlalchemy import LABEL_STYLE_TABLENAME_PLUS_COL
    3. >>> t = table("t", column("c"))
    4. >>> stmt = select(t).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
    5. >>> subq = stmt.subquery()
    6. >>> subq.c.t_c
    7. <sqlalchemy.sql.elements.ColumnClause at 0x7f59dcf04fa0; t_c>

    ColumnCollection also indexes the columns in order and allows them to be accessible by their integer position:

    1. >>> cc[0]
    2. Column('x', Integer(), table=None)
    3. >>> cc[1]
    4. Column('y', Integer(), table=None)

    New in version 1.4: allows integer-based index access to the collection.

    Iterating the collection yields the column expressions in order:

    The base ColumnCollection object can store duplicates, which can mean either two columns with the same key, in which case the column returned by key access is arbitrary:

    1. >>> cc = ColumnCollection(columns=[(x1.name, x1), (x2.name, x2)])
    2. >>> list(cc)
    3. [Column('x', Integer(), table=None),
    4. Column('x', Integer(), table=None)]
    5. >>> cc['x'] is x1
    6. False
    7. >>> cc['x'] is x2
    8. True

    Or it can also mean the same column multiple times. These cases are supported as is used to represent the columns in a SELECT statement which may include duplicates.

    A special subclass DedupeColumnCollection exists which instead maintains SQLAlchemy’s older behavior of not allowing duplicates; this collection is used for schema level objects like Table and where this deduping is helpful. The DedupeColumnCollection class also has additional mutation methods as the schema constructs have more use cases that require removal and replacement of columns.

    Changed in version 1.4: ColumnCollection now stores duplicate column keys as well as the same column in multiple positions. The DedupeColumnCollection class is added to maintain the former behavior in those cases where deduplication as well as additional replace/remove operations are needed.

    Members

    , as_readonly(), , compare(), , corresponding_column(), , items(), , update(),

    Class signature

    class sqlalchemy.sql.expression.ColumnCollection (typing.Generic)

    • method add(column: ColumnElement[Any], key: Optional[_COLKEY] = None) → None

      Add a column to this .

      Note

      This method is not normally used by user-facing code, as the ColumnCollection is usually part of an existing object such as a . To add a Column to an existing object, use the Table.append_column() method.

    • method as_readonly() → ReadOnlyColumnCollection[_COLKEY, _COL_co]

      Return a “read only” form of this ColumnCollection.

    • method clear() → NoReturn

      Dictionary clear() is not implemented for ColumnCollection.

    • method compare(other: ColumnCollection[Any, Any]) → bool

      Compare this to another based on the names of the keys

    • method sqlalchemy.sql.expression.ColumnCollection.contains_column(col: [Any]) → bool

      Checks if a column object exists in this collection

    • method sqlalchemy.sql.expression.ColumnCollection.corresponding_column(column: _COL, require_embedded: bool = False) → Optional[Union[_COL, _COL_co]]

      Given a , return the exported ColumnElement object from 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.corresponding\_column()]($75ae4d183452a412.md#sqlalchemy.sql.expression.Selectable.corresponding_column "sqlalchemy.sql.expression.Selectable.corresponding_column") - invokes this method against the collection returned by [Selectable.exported\_columns]($75ae4d183452a412.md#sqlalchemy.sql.expression.Selectable.exported_columns "sqlalchemy.sql.expression.Selectable.exported_columns").
    3. Changed in version 1.4: the implementation for `corresponding_column` was moved onto the [ColumnCollection](#sqlalchemy.sql.expression.ColumnCollection "sqlalchemy.sql.expression.ColumnCollection") itself.

    class sqlalchemy.sql.expression.ColumnElement

    Represent a column-oriented SQL expression suitable for usage in the “columns” clause, WHERE clause etc. of a statement.

    While the most familiar kind of is the Column object, serves as the basis for any unit that may be present in a SQL expression, including the expressions themselves, SQL functions, bound parameters, literal expressions, keywords such as NULL, etc. ColumnElement is the ultimate base class for all such elements.

    A wide variety of SQLAlchemy Core functions work at the SQL expression level, and are intended to accept instances of as arguments. These functions will typically document that they accept a “SQL expression” as an argument. What this means in terms of SQLAlchemy usually refers to an input which is either already in the form of a ColumnElement object, or a value which can be coerced into one. The coercion rules followed by most, but not all, SQLAlchemy Core functions with regards to SQL expressions are as follows:

    A provides the ability to generate new ColumnElement objects using Python expressions. This means that Python operators such as ==, != and < are overloaded to mimic SQL operations, and allow the instantiation of further instances which are composed from other, more fundamental ColumnElement objects. For example, two objects can be added together with the addition operator + to produce a BinaryExpression. Both and BinaryExpression are subclasses of :

    1. >>> from sqlalchemy.sql import column
    2. <sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
    3. >>> print(column('a') + column('b'))
    4. a + b

    See also

    Column

    Members

    __eq__(), , __lt__(), , all_(), , anon_key_label, , any_(), , base_columns, , bool_op(), , collate(), , compare(), , concat(), , desc(), , distinct(), , entity_namespace, , foreign_keys, , icontains(), , ilike(), , inherit_cache, , is_clause_element, , is_dml, , is_not_distinct_from(), , isnot(), , istartswith(), , label(), , match(), , not_ilike(), , not_like(), , notin_(), , nulls_first(), , nullsfirst(), , op(), , params(), , proxy_set, , regexp_replace(), , self_group(), , startswith(), , supports_execution, , type, , uses_inspection

    Class signature

    class (sqlalchemy.sql.roles.ColumnArgumentOrKeyRole, sqlalchemy.sql.roles.StatementOptionRole, sqlalchemy.sql.roles.WhereHavingRole, sqlalchemy.sql.roles.BinaryElementRole, sqlalchemy.sql.roles.OrderByRole, sqlalchemy.sql.roles.ColumnsClauseRole, sqlalchemy.sql.roles.LimitOffsetRole, sqlalchemy.sql.roles.DMLColumnRole, sqlalchemy.sql.roles.DDLConstraintColumnRole, sqlalchemy.sql.roles.DDLExpressionRole, sqlalchemy.sql.expression.SQLColumnExpression, sqlalchemy.sql.expression.DQLDMLClauseElement)

    • method __eq__(other: Any) → ColumnOperators

      inherited from the sqlalchemy.sql.expression.ColumnOperators.__eq__ method of

      Implement the == operator.

      In a column context, produces the clause a = b. If the target is None, produces a IS NULL.

    • method sqlalchemy.sql.expression.ColumnElement.__le__(other: Any) →

      inherited from the sqlalchemy.sql.expression.ColumnOperators.__le__ method of ColumnOperators

      Implement the <= operator.

      In a column context, produces the clause a <= b.

    • method __lt__(other: Any) → ColumnOperators

      inherited from the sqlalchemy.sql.expression.ColumnOperators.__lt__ method of

      Implement the < operator.

      In a column context, produces the clause a < b.

    • method sqlalchemy.sql.expression.ColumnElement.__ne__(other: Any) →

      inherited from the sqlalchemy.sql.expression.ColumnOperators.__ne__ method of ColumnOperators

      Implement the != operator.

      In a column context, produces the clause a != b. If the target is None, produces a IS NOT NULL.

    • method all_() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce an clause against the parent object.

      See the documentation for all_() for examples.

      Note

      be sure to not confuse the newer method with its older ARRAY-specific counterpart, the method, which a different calling syntax and usage pattern.

      New in version 1.1.

    • attribute sqlalchemy.sql.expression.ColumnElement.allows_lambda = True

    • attribute anon_key_label

      Deprecated since version 1.4: The ColumnElement.anon_key_label attribute is now private, and the public accessor is deprecated.

    • attribute anon_label

      Deprecated since version 1.4: The ColumnElement.anon_label attribute is now private, and the public accessor is deprecated.

    • method any_() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce an clause against the parent object.

      See the documentation for any_() for examples.

      Note

      be sure to not confuse the newer method with its older ARRAY-specific counterpart, the method, which a different calling syntax and usage pattern.

      New in version 1.1.

    • method sqlalchemy.sql.expression.ColumnElement.asc() →

      inherited from the ColumnOperators.asc() method of

      Produce a asc() clause against the parent object.

    • attribute base_columns

    • method sqlalchemy.sql.expression.ColumnElement.between(cleft: Any, cright: Any, symmetric: bool = False) →

      inherited from the ColumnOperators.between() method of

      Produce a between() clause against the parent object, given the lower and upper range.

    • method bool_op(opstring: str, precedence: int = 0, python_impl: Optional[Callable[[…], Any]] = None) → Callable[[Any], Operators]

      inherited from the method of Operators

      Return a custom boolean operator.

      This method is shorthand for calling and passing the Operators.op.is_comparison flag with True. A key advantage to using is that when using column constructs, the “boolean” nature of the returned expression will be present for PEP 484 purposes.

      See also

    • method sqlalchemy.sql.expression.ColumnElement.cast(type\: _TypeEngineArgument[_T]_) → [_T]

      Produce a type cast, i.e. CAST(<expression> AS <type>).

      This is a shortcut to the cast() function.

      See also

      cast()

      New in version 1.0.7.

    • method sqlalchemy.sql.expression.ColumnElement.collate(collation: str) →

      inherited from the ColumnOperators.collate() method of

      Produce a collate() clause against the parent object, given the collation string.

      See also

    • attribute sqlalchemy.sql.expression.ColumnElement.comparator

    • method compare(other: ClauseElement, **kw: Any) → bool

      inherited from the method of ClauseElement

      Compare this to the given ClauseElement.

      Subclasses should override the default behavior, which is a straight identity comparison.

      **kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison (see ).

    • method sqlalchemy.sql.expression.ColumnElement.compile(bind: Optional[Union[, Connection]] = None, dialect: Optional[] = None, **kw: Any) → Compiled

      inherited from the CompilerElement.compile() method of CompilerElement

      Compile this SQL expression.

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

      • Parameters:

        • bind – An or Engine which can provide a in order to generate a Compiled object. If the bind and dialect parameters are both omitted, a default SQL compiler is used.

        • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.

        • dialect – A instance which can generate a Compiled object. This argument takes precedence over the bind argument.

        • compile_kwargs

          optional dictionary of additional parameters that will be passed through to the compiler within all “visit” methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the literal_binds flag through:

          1. from sqlalchemy.sql import table, column, select
          2. t = table('t', column('x'))
          3. s = select(t).where(t.c.x == 5)
          4. print(s.compile(compile_kwargs={"literal_binds": True}))

          New in version 0.9.0.

    1. See also
    2. [How do I render SQL expressions as strings, possibly with bound parameters inlined?]($e9fd44a49fe37bbb.md#faq-sql-expression-string)
    • method concat(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the ‘concat’ operator.

      In a column context, produces the clause a || b, or uses the concat() operator on MySQL.

    • method contains(other: Any, **kw: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the ‘contains’ operator.

      Produces a LIKE expression that tests against a match for the middle of a string value:

      1. column LIKE '%' || <other> || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.contains("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.contains.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.contains("foo%bar", autoescape=True)

          Will render as:

          1. somecolumn LIKE '%' || :param || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.contains("foo/%bar", escape="^")

          Will render as:

          1. somecolumn LIKE '%' || :param || '%' ESCAPE '^'

          The parameter may also be combined with ColumnOperators.contains.autoescape:

          1. somecolumn.contains("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.startswith()](#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    3. [ColumnOperators.endswith()](#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    4. [ColumnOperators.like()](#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method desc() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

    • attribute sqlalchemy.sql.expression.ColumnElement.description

      inherited from the ClauseElement.description attribute of

    • method sqlalchemy.sql.expression.ColumnElement.distinct() →

      inherited from the ColumnOperators.distinct() method of

      Produce a distinct() clause against the parent object.

    • method endswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the ‘endswith’ operator.

      Produces a LIKE expression that tests against a match for the end of a string value:

      1. column LIKE '%' || <other>

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.endswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.endswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.endswith("foo%bar", autoescape=True)

          Will render as:

          1. somecolumn LIKE '%' || :param ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.endswith("foo/%bar", escape="^")

          Will render as:

          1. somecolumn LIKE '%' || :param ESCAPE '^'

          The parameter may also be combined with ColumnOperators.endswith.autoescape:

          1. somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.startswith()](#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    3. [ColumnOperators.contains()](#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    4. [ColumnOperators.like()](#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • attribute entity_namespace

      inherited from the ClauseElement.entity_namespace attribute of ClauseElement

    • attribute expression

      Return a column expression.

      Part of the inspection interface; returns self.

    • attribute sqlalchemy.sql.expression.ColumnElement.foreign_keys: AbstractSet[] = frozenset({})

    • method sqlalchemy.sql.expression.ColumnElement.get_children(*, omit_attrs: Tuple[str, …] = (), **kw: Any) → Iterable[HasTraverseInternals]

      inherited from the HasTraverseInternals.get_children() method of HasTraverseInternals

      Return immediate child HasTraverseInternals elements of this HasTraverseInternals.

      This is used for visit traversal.

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

    • method icontains(other: Any, **kw: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the icontains operator, e.g. case insensitive version of .

      Produces a LIKE expression that tests against an insensitive match for the middle of a string value:

      1. lower(column) LIKE '%' || lower(<other>) || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.icontains("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the ColumnOperators.icontains.autoescape flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the ColumnOperators.icontains.autoescape flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.icontains("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.icontains("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '^'

          The parameter may also be combined with :

          1. somecolumn.icontains("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.contains()](#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    • method sqlalchemy.sql.expression.ColumnElement.iendswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) →

      inherited from the ColumnOperators.iendswith() method of

      Implement the iendswith operator, e.g. case insensitive version of ColumnOperators.endswith().

      Produces a LIKE expression that tests against an insensitive match for the end of a string value:

      1. lower(column) LIKE '%' || lower(<other>)

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.iendswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.iendswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.iendswith("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.iendswith("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '^'

          The parameter may also be combined with ColumnOperators.iendswith.autoescape:

          1. somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.endswith()](#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    • method ilike(other: Any, escape: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the ilike operator, e.g. case insensitive LIKE.

      In a column context, produces an expression either of the form:

      1. lower(a) LIKE lower(other)

      Or on backends that support the ILIKE operator:

      1. a ILIKE other

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.ilike("%foobar%"))
      • Parameters:

        • other – expression to be compared

        • escape

          optional escape character, renders the ESCAPE keyword, e.g.:

          1. somecolumn.ilike("foo/%bar", escape="/")
    1. See also
    2. [ColumnOperators.like()](#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method in_(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the in operator.

      In a column context, produces the clause column IN <other>.

      The given parameter other may be:

      • A list of literal values, e.g.:

        1. stmt.where(column.in_([1, 2, 3]))

        In this calling form, the list of items is converted to a set of bound parameters the same length as the list given:

        1. WHERE COL IN (?, ?, ?)
      • A list of tuples may be provided if the comparison is against a containing multiple expressions:

        1. from sqlalchemy import tuple_
        2. stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
      • An empty list, e.g.:

        1. stmt.where(column.in_([]))

        In this calling form, the expression renders an “empty set” expression. These expressions are tailored to individual backends and are generally trying to get an empty SELECT statement as a subquery. Such as on SQLite, the expression is:

        1. WHERE col IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)

        Changed in version 1.4: empty IN expressions now use an execution-time generated SELECT subquery in all cases.

      • A bound parameter, e.g. bindparam(), may be used if it includes the flag:

        1. stmt.where(column.in_(bindparam('value', expanding=True)))

        In this calling form, the expression renders a special non-SQL placeholder expression that looks like:

        1. WHERE COL IN ([EXPANDING_value])

        This placeholder expression is intercepted at statement execution time to be converted into the variable number of bound parameter form illustrated earlier. If the statement were executed as:

        1. connection.execute(stmt, {"value": [1, 2, 3]})

        The database would be passed a bound parameter for each value:

        1. WHERE COL IN (?, ?, ?)

        New in version 1.2: added “expanding” bound parameters

        If an empty list is passed, a special “empty list” expression, which is specific to the database in use, is rendered. On SQLite this would be:

        1. WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)

        New in version 1.3: “expanding” bound parameters now support empty lists

      • a select() construct, which is usually a correlated scalar select:

        1. stmt.where(
        2. column.in_(
        3. select(othertable.c.y).
        4. where(table.c.x == othertable.c.x)
        5. )
        6. )

        In this calling form, renders as given:

        1. WHERE COL IN (SELECT othertable.y
        2. FROM othertable WHERE othertable.x = table.x)
      • Parameters:

        other – a list of literals, a select() construct, or a construct that includes the bindparam.expanding flag set to True.

    • attribute inherit_cache: Optional[bool] = None

      inherited from the HasCacheKey.inherit_cache attribute of HasCacheKey

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

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

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

      See also

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

    • method sqlalchemy.sql.expression.ColumnElement.is_(other: Any) →

      inherited from the ColumnOperators.is_() method of

      Implement the IS operator.

      Normally, IS is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS may be desirable if comparing to boolean values on certain platforms.

      See also

      ColumnOperators.is_not()

    • attribute is_clause_element = True

    • method sqlalchemy.sql.expression.ColumnElement.is_distinct_from(other: Any) →

      inherited from the ColumnOperators.is_distinct_from() method of

      Implement the IS DISTINCT FROM operator.

      Renders “a IS DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS NOT b”.

      New in version 1.1.

    • attribute sqlalchemy.sql.expression.ColumnElement.is_dml = False

    • method is_not(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the IS NOT operator.

      Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.

      Changed in version 1.4: The is_not() operator is renamed from isnot() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.sql.expression.ColumnElement.is_not_distinct_from(other: Any) →

      inherited from the ColumnOperators.is_not_distinct_from() method of

      Implement the IS NOT DISTINCT FROM operator.

      Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.

      Changed in version 1.4: The is_not_distinct_from() operator is renamed from isnot_distinct_from() in previous releases. The previous name remains available for backwards compatibility.

      New in version 1.1.

    • attribute sqlalchemy.sql.expression.ColumnElement.is_selectable = False

    • method isnot(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the IS NOT operator.

      Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.

      Changed in version 1.4: The is_not() operator is renamed from isnot() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.sql.expression.ColumnElement.isnot_distinct_from(other: Any) →

      inherited from the ColumnOperators.isnot_distinct_from() method of

      Implement the IS NOT DISTINCT FROM operator.

      Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.

      Changed in version 1.4: The is_not_distinct_from() operator is renamed from isnot_distinct_from() in previous releases. The previous name remains available for backwards compatibility.

      New in version 1.1.

    • method sqlalchemy.sql.expression.ColumnElement.istartswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) →

      inherited from the ColumnOperators.istartswith() method of

      Implement the istartswith operator, e.g. case insensitive version of ColumnOperators.startswith().

      Produces a LIKE expression that tests against an insensitive match for the start of a string value:

      1. lower(column) LIKE lower(<other>) || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.istartswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.istartswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.istartswith("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.istartswith("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '^'

          The parameter may also be combined with ColumnOperators.istartswith.autoescape:

          1. somecolumn.istartswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.startswith()](#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    • attribute key: Optional[str] = None

      The ‘key’ that in some circumstances refers to this object in a Python namespace.

      This typically refers to the “key” of the column as present in the .c collection of a selectable, e.g. sometable.c["somekey"] would return a Column with a .key of “somekey”.

    • method label(name: Optional[str]) → Label[_T]

      Produce a column label, i.e. <columnname> AS <name>.

      This is a shortcut to the function.

      If ‘name’ is None, an anonymous label name will be generated.

    • method sqlalchemy.sql.expression.ColumnElement.like(other: Any, escape: Optional[str] = None) →

      inherited from the ColumnOperators.like() method of

      Implement the like operator.

      In a column context, produces the expression:

      1. a LIKE other

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.like("%foobar%"))
      • Parameters:

        • other – expression to be compared

        • escape

          optional escape character, renders the ESCAPE keyword, e.g.:

          1. somecolumn.like("foo/%bar", escape="/")
    1. See also
    2. [ColumnOperators.ilike()](#sqlalchemy.sql.expression.ColumnOperators.ilike "sqlalchemy.sql.expression.ColumnOperators.ilike")
    • method sqlalchemy.sql.expression.ColumnElement.match(other: Any, **kwargs: Any) →

      inherited from the ColumnOperators.match() method of

      Implements a database-specific ‘match’ operator.

      ColumnOperators.match() attempts to resolve to a MATCH-like function or operator provided by the backend. Examples include:

      • PostgreSQL - renders x @@ plainto_tsquery(y)

      • MySQL - renders MATCH (x) AGAINST (y IN BOOLEAN MODE)

        See also

        - MySQL specific construct with additional features.

      • Oracle - renders CONTAINS(x, y)

      • other backends may provide special implementations.

      • Backends without any special implementation will emit the operator as “MATCH”. This is compatible with SQLite, for example.

    • attribute sqlalchemy.sql.expression.ColumnElement.negation_clause: [bool]

    • method sqlalchemy.sql.expression.ColumnElement.not_ilike(other: Any, escape: Optional[str] = None) →

      inherited from the ColumnOperators.not_ilike() method of

      implement the NOT ILIKE operator.

      This is equivalent to using negation with ColumnOperators.ilike(), i.e. ~x.ilike(y).

      Changed in version 1.4: The not_ilike() operator is renamed from notilike() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.sql.expression.ColumnElement.not_in(other: Any) →

      inherited from the ColumnOperators.not_in() method of

      implement the NOT IN operator.

      This is equivalent to using negation with ColumnOperators.in_(), i.e. ~x.in_(y).

      In the case that other is an empty sequence, the compiler produces an “empty not in” expression. This defaults to the expression “1 = 1” to produce true in all cases. The may be used to alter this behavior.

      Changed in version 1.4: The not_in() operator is renamed from notin_() in previous releases. The previous name remains available for backwards compatibility.

      Changed in version 1.2: The ColumnOperators.in_() and operators now produce a “static” expression for an empty IN sequence by default.

      See also

      ColumnOperators.in_()

    • method not_like(other: Any, escape: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      implement the NOT LIKE operator.

      This is equivalent to using negation with , i.e. ~x.like(y).

      Changed in version 1.4: The not_like() operator is renamed from notlike() in previous releases. The previous name remains available for backwards compatibility.

      See also

      ColumnOperators.like()

    • method notilike(other: Any, escape: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      implement the NOT ILIKE operator.

      This is equivalent to using negation with , i.e. ~x.ilike(y).

      Changed in version 1.4: The not_ilike() operator is renamed from notilike() in previous releases. The previous name remains available for backwards compatibility.

      See also

      ColumnOperators.ilike()

    • method notin_(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      implement the NOT IN operator.

      This is equivalent to using negation with , i.e. ~x.in_(y).

      In the case that other is an empty sequence, the compiler produces an “empty not in” expression. This defaults to the expression “1 = 1” to produce true in all cases. The create_engine.empty_in_strategy may be used to alter this behavior.

      Changed in version 1.4: The not_in() operator is renamed from notin_() in previous releases. The previous name remains available for backwards compatibility.

      Changed in version 1.2: The and ColumnOperators.not_in() operators now produce a “static” expression for an empty IN sequence by default.

      See also

    • method sqlalchemy.sql.expression.ColumnElement.notlike(other: Any, escape: Optional[str] = None) →

      inherited from the ColumnOperators.notlike() method of

      implement the NOT LIKE operator.

      This is equivalent to using negation with ColumnOperators.like(), i.e. ~x.like(y).

      Changed in version 1.4: The not_like() operator is renamed from notlike() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.sql.expression.ColumnElement.nulls_first() →

      inherited from the ColumnOperators.nulls_first() method of

      Produce a nulls_first() clause against the parent object.

      Changed in version 1.4: The nulls_first() operator is renamed from nullsfirst() in previous releases. The previous name remains available for backwards compatibility.

    • method nulls_last() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

      Changed in version 1.4: The nulls_last() operator is renamed from nullslast() in previous releases. The previous name remains available for backwards compatibility.

    • method sqlalchemy.sql.expression.ColumnElement.nullsfirst() →

      inherited from the ColumnOperators.nullsfirst() method of

      Produce a nulls_first() clause against the parent object.

      Changed in version 1.4: The nulls_first() operator is renamed from nullsfirst() in previous releases. The previous name remains available for backwards compatibility.

    • method nullslast() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

      Changed in version 1.4: The nulls_last() operator is renamed from nullslast() in previous releases. The previous name remains available for backwards compatibility.

    • method sqlalchemy.sql.expression.ColumnElement.op(opstring: str, precedence: int = 0, is_comparison: bool = False, return_type: Optional[Union[Type[[Any]], TypeEngine[Any]]] = None, python_impl: Optional[Callable[…, Any]] = None) → Callable[[Any], ]

      inherited from the Operators.op() method of

      Produce a generic operator function.

      e.g.:

      1. somecolumn.op("*")(5)

      produces:

      1. somecolumn * 5

      This function can also be used to make bitwise operators explicit. For example:

      1. somecolumn.op('&')(0xff)

      is a bitwise AND of the value in somecolumn.

      • Parameters:

        • opstring – a string which will be output as the infix operator between this element and the expression passed to the generated function.

        • precedence

          precedence which the database is expected to apply to the operator in SQL expressions. This integer value acts as a hint for the SQL compiler to know when explicit parenthesis should be rendered around a particular operation. A lower number will cause the expression to be parenthesized when applied against another operator with higher precedence. The default value of 0 is lower than all operators except for the comma (,) and AS operators. A value of 100 will be higher or equal to all operators, and -100 will be lower than or equal to all operators.

          See also

          I’m using op() to generate a custom operator and my parenthesis are not coming out correctly - detailed description of how the SQLAlchemy SQL compiler renders parenthesis

        • is_comparison

          legacy; if True, the operator will be considered as a “comparison” operator, that is which evaluates to a boolean true/false value, like ==, >, etc. This flag is provided so that ORM relationships can establish that the operator is a comparison operator when used in a custom join condition.

          Using the is_comparison parameter is superseded by using the method instead; this more succinct operator sets this parameter automatically, but also provides correct PEP 484 typing support as the returned object will express a “boolean” datatype, i.e. BinaryExpression[bool].

        • return_type – a class or object that will force the return type of an expression produced by this operator to be of that type. By default, operators that specify Operators.op.is_comparison will resolve to , and those that do not will be of the same type as the left-hand operand.

        • python_impl

          an optional Python function that can evaluate two Python values in the same way as this operator works when run on the database server. Useful for in-Python SQL expression evaluation functions, such as for ORM hybrid attributes, and the ORM “evaluator” used to match objects in a session after a multi-row update or delete.

          e.g.:

          1. >>> expr = column('x').op('+', python_impl=lambda a, b: a + b)('y')

          The operator for the above expression will also work for non-SQL left and right objects:

          1. >>> expr.operator(5, 10)
          2. 15

          New in version 2.0.

    1. See also
    2. [Operators.bool\_op()](#sqlalchemy.sql.expression.Operators.bool_op "sqlalchemy.sql.expression.Operators.bool_op")
    3. [Redefining and Creating New Operators]($e8ad009010586d59.md#types-operators)
    4. [Using custom operators in join conditions]($b68ea79e4b407a37.md#relationship-custom-operator)
    • method sqlalchemy.sql.expression.ColumnElement.operate(op: OperatorType, *other: Any, **kwargs: Any) → [Any]

      Operate on an argument.

      This is the lowest level of operation, raises NotImplementedError by default.

      Overriding this on a subclass can allow common behavior to be applied to all operations. For example, overriding ColumnOperators to apply func.lower() to the left and right side:

      1. class MyComparator(ColumnOperators):
      2. def operate(self, op, other, **kwargs):
      3. return op(func.lower(self), func.lower(other), **kwargs)
      • Parameters:

        • op – Operator callable.

        • *other – the ‘other’ side of the operation. Will be a single scalar for most operations.

        • **kwargs – modifiers. These may be passed by special operators such as .

    • method sqlalchemy.sql.expression.ColumnElement.params(_ClauseElement\_optionaldict: Optional[Mapping[str, Any]] = None, **kwargs: Any_) → SelfClauseElement

      inherited from the method of ClauseElement

      Return a copy with elements replaced.

      Returns a copy of this ClauseElement with bindparam() elements replaced with values taken from the given dictionary:

      1. >>> clause = column('x') + bindparam('foo')
      2. >>> print(clause.compile().params)
      3. {'foo':None}
      4. >>> print(clause.params({'foo':7}).compile().params)
      5. {'foo':7}
    • attribute primary_key: bool = False

    • attribute sqlalchemy.sql.expression.ColumnElement.proxy_set: util.generic_fn_descriptor[FrozenSet[Any]]

      set of all columns we are proxying

      as of 2.0 this is explicitly deannotated columns. previously it was effectively deannotated columns but wasn’t enforced. annotated columns should basically not go into sets if at all possible because their hashing behavior is very non-performant.

    • method regexp_match(pattern: Any, flags: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      Implements a database-specific ‘regexp match’ operator.

      E.g.:

      1. stmt = select(table.c.some_column).where(
      2. table.c.some_column.regexp_match('^(b|c)')
      3. )

      attempts to resolve to a REGEXP-like function or operator provided by the backend, however the specific regular expression syntax and flags available are not backend agnostic.

      Examples include:

      • PostgreSQL - renders x ~ y or x !~ y when negated.

      • Oracle - renders REGEXP_LIKE(x, y)

      • SQLite - uses SQLite’s REGEXP placeholder operator and calls into the Python re.match() builtin.

      • other backends may provide special implementations.

      • Backends without any special implementation will emit the operator as “REGEXP” or “NOT REGEXP”. This is compatible with SQLite and MySQL, for example.

      Regular expression support is currently implemented for Oracle, PostgreSQL, MySQL and MariaDB. Partial support is available for SQLite. Support among third-party dialects may vary.

      • Parameters:

        • pattern – The regular expression pattern string or column clause.

        • flags – Any regular expression string flags to apply. Flags tend to be backend specific. It can be a string or a column clause. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern. When using the ignore case flag ‘i’ in PostgreSQL, the ignore case regexp match operator ~* or !~* will be used.

    1. New in version 1.4.
    2. See also
    3. [ColumnOperators.regexp\_replace()](#sqlalchemy.sql.expression.ColumnOperators.regexp_replace "sqlalchemy.sql.expression.ColumnOperators.regexp_replace")
    • method sqlalchemy.sql.expression.ColumnElement.regexp_replace(pattern: Any, replacement: Any, flags: Optional[str] = None) →

      inherited from the ColumnOperators.regexp_replace() method of

      Implements a database-specific ‘regexp replace’ operator.

      E.g.:

      1. stmt = select(
      2. table.c.some_column.regexp_replace(
      3. 'b(..)',
      4. 'XY',
      5. flags='g'
      6. )
      7. )

      ColumnOperators.regexp_replace() attempts to resolve to a REGEXP_REPLACE-like function provided by the backend, that usually emit the function REGEXP_REPLACE(). However, the specific regular expression syntax and flags available are not backend agnostic.

      Regular expression replacement support is currently implemented for Oracle, PostgreSQL, MySQL 8 or greater and MariaDB. Support among third-party dialects may vary.

      • Parameters:

        • pattern – The regular expression pattern string or column clause.

        • pattern – The replacement string or column clause.

        • flags – Any regular expression string flags to apply. Flags tend to be backend specific. It can be a string or a column clause. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern.

    1. New in version 1.4.
    2. See also
    3. [ColumnOperators.regexp\_match()](#sqlalchemy.sql.expression.ColumnOperators.regexp_match "sqlalchemy.sql.expression.ColumnOperators.regexp_match")
    • method reverse_operate(op: OperatorType, other: Any, **kwargs: Any) → ColumnElement[Any]

      Reverse operate on an argument.

      Usage is the same as .

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

      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 shares_lineage(othercolumn: ColumnElement[Any]) → bool

      Return True if the given has a common ancestor to this ColumnElement.

    • method startswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the startswith operator.

      Produces a LIKE expression that tests against a match for the start of a string value:

      1. column LIKE <other> || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.startswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.startswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.startswith("foo%bar", autoescape=True)

          Will render as:

          1. somecolumn LIKE :param || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.startswith("foo/%bar", escape="^")

          Will render as:

          1. somecolumn LIKE :param || '%' ESCAPE '^'

          The parameter may also be combined with ColumnOperators.startswith.autoescape:

          1. somecolumn.startswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.endswith()](#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    3. [ColumnOperators.contains()](#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    4. [ColumnOperators.like()](#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")

    class sqlalchemy.sql.expression.ColumnOperators

    Defines boolean, comparison, and other operators for ColumnElement expressions.

    By default, all methods call down to or reverse_operate(), passing in the appropriate operator function from the Python builtin operator module or a SQLAlchemy-specific operator function from sqlalchemy.expression.operators. For example the __eq__ function:

    1. def __eq__(self, other):
    2. return self.operate(operators.eq, other)

    Where operators.eq is essentially:

    1. def eq(a, b):
    2. return a == b

    The core column expression unit overrides Operators.operate() and others to return further constructs, so that the == operation above is replaced by a clause construct.

    See also

    Redefining and Creating New Operators

    ColumnOperators

    Members

    __add__(), , __eq__(), , __ge__(), , __gt__(), , __invert__(), , __lshift__(), , __mod__(), , __ne__(), , __or__(), , __rfloordiv__(), , __rmul__(), , __rsub__(), , __sa_operate__(), , __truediv__(), , any_(), , between(), , collate(), , contains(), , distinct(), , icontains(), , ilike(), , is_(), , is_not(), , isnot(), , istartswith(), , match(), , not_in(), , notilike(), , notlike(), , nulls_last(), , nullslast(), , operate(), , regexp_replace(), , startswith(),

    Class signature

    class sqlalchemy.sql.expression.ColumnOperators ()

    • method sqlalchemy.sql.expression.ColumnOperators.__add__(other: Any) →

      Implement the + operator.

      In a column context, produces the clause a + b if the parent object has non-string affinity. If the parent object has a string affinity, produces the concatenation operator, a || b - see ColumnOperators.concat().

    • method __and__(other: Any) → Operators

      inherited from the sqlalchemy.sql.expression.Operators.__and__ method of

      Implement the & operator.

      When used with SQL expressions, results in an AND operation, equivalent to and_(), that is:

      1. a & b

      is equivalent to:

      1. from sqlalchemy import and_
      2. and_(a, b)

      Care should be taken when using & regarding operator precedence; the & operator has the highest precedence. The operands should be enclosed in parenthesis if they contain further sub expressions:

      1. (a == 2) & (b == 4)
    • method __eq__(other: Any) → ColumnOperators

      Implement the == operator.

      In a column context, produces the clause a = b. If the target is None, produces a IS NULL.

    • method __floordiv__(other: Any) → ColumnOperators

      Implement the // operator.

      In a column context, produces the clause a / b, which is the same as “truediv”, but considers the result type to be integer.

      New in version 2.0.

    • method __ge__(other: Any) → ColumnOperators

      Implement the >= operator.

      In a column context, produces the clause a >= b.

    • method __getitem__(index: Any) → ColumnOperators

      Implement the [] operator.

      This can be used by some database-specific types such as PostgreSQL ARRAY and HSTORE.

    • method __gt__(other: Any) → ColumnOperators

      Implement the > operator.

      In a column context, produces the clause a > b.

    • method __hash__()

      Return hash(self).

    • method sqlalchemy.sql.expression.ColumnOperators.__invert__() →

      inherited from the sqlalchemy.sql.expression.Operators.__invert__ method of Operators

      Implement the ~ operator.

      When used with SQL expressions, results in a NOT operation, equivalent to , that is:

      1. ~a

      is equivalent to:

      1. from sqlalchemy import not_
      2. not_(a)
    • method sqlalchemy.sql.expression.ColumnOperators.__le__(other: Any) →

      Implement the <= operator.

      In a column context, produces the clause a <= b.

    • method sqlalchemy.sql.expression.ColumnOperators.__lshift__(other: Any) →

      implement the << operator.

      Not used by SQLAlchemy core, this is provided for custom operator systems which want to use << as an extension point.

    • method sqlalchemy.sql.expression.ColumnOperators.__lt__(other: Any) →

      Implement the < operator.

      In a column context, produces the clause a < b.

    • method sqlalchemy.sql.expression.ColumnOperators.__mod__(other: Any) →

      Implement the % operator.

      In a column context, produces the clause a % b.

    • method sqlalchemy.sql.expression.ColumnOperators.__mul__(other: Any) →

      Implement the * operator.

      In a column context, produces the clause a * b.

    • method sqlalchemy.sql.expression.ColumnOperators.__ne__(other: Any) →

      Implement the != operator.

      In a column context, produces the clause a != b. If the target is None, produces a IS NOT NULL.

    • method sqlalchemy.sql.expression.ColumnOperators.__neg__() →

      Implement the - operator.

      In a column context, produces the clause -a.

    • method sqlalchemy.sql.expression.ColumnOperators.__or__(other: Any) →

      inherited from the sqlalchemy.sql.expression.Operators.__or__ method of Operators

      Implement the | operator.

      When used with SQL expressions, results in an OR operation, equivalent to , that is:

      1. a | b

      is equivalent to:

      1. from sqlalchemy import or_
      2. or_(a, b)

      Care should be taken when using | regarding operator precedence; the | operator has the highest precedence. The operands should be enclosed in parenthesis if they contain further sub expressions:

      1. (a == 2) | (b == 4)
    • method sqlalchemy.sql.expression.ColumnOperators.__radd__(other: Any) →

      Implement the + operator in reverse.

      See ColumnOperators.__add__().

    • method __rfloordiv__(other: Any) → ColumnOperators

      Implement the // operator in reverse.

    • method __rmod__(other: Any) → ColumnOperators

      Implement the % operator in reverse.

      See .

    • method sqlalchemy.sql.expression.ColumnOperators.__rmul__(other: Any) →

      Implement the * operator in reverse.

      See ColumnOperators.__mul__().

    • method __rshift__(other: Any) → ColumnOperators

      implement the >> operator.

      Not used by SQLAlchemy core, this is provided for custom operator systems which want to use >> as an extension point.

    • method __rsub__(other: Any) → ColumnOperators

      Implement the - operator in reverse.

      See .

    • method sqlalchemy.sql.expression.ColumnOperators.__rtruediv__(other: Any) →

      Implement the / operator in reverse.

      See ColumnOperators.__truediv__().

    • method __sa_operate__(op: OperatorType, *other: Any, **kwargs: Any) → Operators

      inherited from the sqlalchemy.sql.expression.Operators.__sa_operate__ method of

      Operate on an argument.

      This is the lowest level of operation, raises NotImplementedError by default.

      Overriding this on a subclass can allow common behavior to be applied to all operations. For example, overriding ColumnOperators to apply func.lower() to the left and right side:

      1. class MyComparator(ColumnOperators):
      2. def operate(self, op, other, **kwargs):
      3. return op(func.lower(self), func.lower(other), **kwargs)
      • Parameters:

        • op – Operator callable.

        • *other – the ‘other’ side of the operation. Will be a single scalar for most operations.

        • **kwargs – modifiers. These may be passed by special operators such as .

    • method sqlalchemy.sql.expression.ColumnOperators.__sub__(other: Any) →

      Implement the - operator.

      In a column context, produces the clause a - b.

    • method sqlalchemy.sql.expression.ColumnOperators.__truediv__(other: Any) →

      Implement the / operator.

      In a column context, produces the clause a / b, and considers the result type to be numeric.

      Changed in version 2.0: The truediv operator against two integers is now considered to return a numeric value. Behavior on specific backends may vary.

    • method sqlalchemy.sql.expression.ColumnOperators.all_() →

      Produce an all_() clause against the parent object.

      See the documentation for for examples.

      Note

      be sure to not confuse the newer ColumnOperators.all_() method with its older -specific counterpart, the Comparator.all() method, which a different calling syntax and usage pattern.

      New in version 1.1.

    • method any_() → ColumnOperators

      Produce an clause against the parent object.

      See the documentation for any_() for examples.

      Note

      be sure to not confuse the newer method with its older ARRAY-specific counterpart, the method, which a different calling syntax and usage pattern.

      New in version 1.1.

    • method sqlalchemy.sql.expression.ColumnOperators.asc() →

      Produce a asc() clause against the parent object.

    • method between(cleft: Any, cright: Any, symmetric: bool = False) → ColumnOperators

      Produce a clause against the parent object, given the lower and upper range.

    • method sqlalchemy.sql.expression.ColumnOperators.collate(collation: str) →

      Produce a collate() clause against the parent object, given the collation string.

      See also

    • method sqlalchemy.sql.expression.ColumnOperators.concat(other: Any) →

      Implement the ‘concat’ operator.

      In a column context, produces the clause a || b, or uses the concat() operator on MySQL.

    • method sqlalchemy.sql.expression.ColumnOperators.contains(other: Any, **kw: Any) →

      Implement the ‘contains’ operator.

      Produces a LIKE expression that tests against a match for the middle of a string value:

      1. column LIKE '%' || <other> || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.contains("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the ColumnOperators.contains.autoescape flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the ColumnOperators.contains.autoescape flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.contains("foo%bar", autoescape=True)

          Will render as:

          1. somecolumn LIKE '%' || :param || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.contains("foo/%bar", escape="^")

          Will render as:

          The parameter may also be combined with :

          1. somecolumn.contains("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    • method sqlalchemy.sql.expression.ColumnOperators.desc() →

      Produce a desc() clause against the parent object.

    • method distinct() → ColumnOperators

      Produce a clause against the parent object.

    • method sqlalchemy.sql.expression.ColumnOperators.endswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) →

      Implement the ‘endswith’ operator.

      Produces a LIKE expression that tests against a match for the end of a string value:

      1. column LIKE '%' || <other>

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.endswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the ColumnOperators.endswith.autoescape flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the ColumnOperators.endswith.autoescape flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.endswith("foo%bar", autoescape=True)

          Will render as:

          1. somecolumn LIKE '%' || :param ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.endswith("foo/%bar", escape="^")

          Will render as:

          1. somecolumn LIKE '%' || :param ESCAPE '^'

          The parameter may also be combined with :

          1. somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.startswith()](#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    3. [ColumnOperators.contains()](#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    4. [ColumnOperators.like()](#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method sqlalchemy.sql.expression.ColumnOperators.icontains(other: Any, **kw: Any) →

      Implement the icontains operator, e.g. case insensitive version of ColumnOperators.contains().

      Produces a LIKE expression that tests against an insensitive match for the middle of a string value:

      1. lower(column) LIKE '%' || lower(<other>) || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.icontains("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.icontains.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.icontains("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.icontains("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '^'

          The parameter may also be combined with ColumnOperators.contains.autoescape:

          1. somecolumn.icontains("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.contains()](#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    • method iendswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) → ColumnOperators

      Implement the iendswith operator, e.g. case insensitive version of .

      Produces a LIKE expression that tests against an insensitive match for the end of a string value:

      1. lower(column) LIKE '%' || lower(<other>)

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.iendswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the ColumnOperators.iendswith.autoescape flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the ColumnOperators.iendswith.autoescape flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.iendswith("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.iendswith("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '^'

          The parameter may also be combined with :

          1. somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.endswith()](#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    • method sqlalchemy.sql.expression.ColumnOperators.ilike(other: Any, escape: Optional[str] = None) →

      Implement the ilike operator, e.g. case insensitive LIKE.

      In a column context, produces an expression either of the form:

      1. lower(a) LIKE lower(other)

      Or on backends that support the ILIKE operator:

      1. a ILIKE other

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.ilike("%foobar%"))
      • Parameters:

        • other – expression to be compared

        • escape

          optional escape character, renders the ESCAPE keyword, e.g.:

          1. somecolumn.ilike("foo/%bar", escape="/")
    1. See also
    2. [ColumnOperators.like()](#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method sqlalchemy.sql.expression.ColumnOperators.in_(other: Any) →

      Implement the in operator.

      In a column context, produces the clause column IN <other>.

      The given parameter other may be:

      • A list of literal values, e.g.:

        1. stmt.where(column.in_([1, 2, 3]))

        In this calling form, the list of items is converted to a set of bound parameters the same length as the list given:

        1. WHERE COL IN (?, ?, ?)
      • A list of tuples may be provided if the comparison is against a tuple_() containing multiple expressions:

        1. from sqlalchemy import tuple_
        2. stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
      • An empty list, e.g.:

        1. stmt.where(column.in_([]))

        In this calling form, the expression renders an “empty set” expression. These expressions are tailored to individual backends and are generally trying to get an empty SELECT statement as a subquery. Such as on SQLite, the expression is:

        1. WHERE col IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)

        Changed in version 1.4: empty IN expressions now use an execution-time generated SELECT subquery in all cases.

      • A bound parameter, e.g. , may be used if it includes the bindparam.expanding flag:

        1. stmt.where(column.in_(bindparam('value', expanding=True)))

        In this calling form, the expression renders a special non-SQL placeholder expression that looks like:

        1. WHERE COL IN ([EXPANDING_value])

        This placeholder expression is intercepted at statement execution time to be converted into the variable number of bound parameter form illustrated earlier. If the statement were executed as:

        1. connection.execute(stmt, {"value": [1, 2, 3]})

        The database would be passed a bound parameter for each value:

        1. WHERE COL IN (?, ?, ?)

        New in version 1.2: added “expanding” bound parameters

        If an empty list is passed, a special “empty list” expression, which is specific to the database in use, is rendered. On SQLite this would be:

        1. WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)

        New in version 1.3: “expanding” bound parameters now support empty lists

      • a construct, which is usually a correlated scalar select:

        1. stmt.where(
        2. column.in_(
        3. select(othertable.c.y).
        4. where(table.c.x == othertable.c.x)
        5. )
        6. )

        In this calling form, ColumnOperators.in_() renders as given:

        1. WHERE COL IN (SELECT othertable.y
        2. FROM othertable WHERE othertable.x = table.x)
      • Parameters:

        other – a list of literals, a construct, or a bindparam() construct that includes the flag set to True.

    • method sqlalchemy.sql.expression.ColumnOperators.is_(other: Any) →

      Implement the IS operator.

      Normally, IS is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS may be desirable if comparing to boolean values on certain platforms.

      See also

      ColumnOperators.is_not()

    • method is_distinct_from(other: Any) → ColumnOperators

      Implement the IS DISTINCT FROM operator.

      Renders “a IS DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS NOT b”.

      New in version 1.1.

    • method is_not(other: Any) → ColumnOperators

      Implement the IS NOT operator.

      Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.

      Changed in version 1.4: The is_not() operator is renamed from isnot() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.sql.expression.ColumnOperators.is_not_distinct_from(other: Any) →

      Implement the IS NOT DISTINCT FROM operator.

      Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.

      Changed in version 1.4: The is_not_distinct_from() operator is renamed from isnot_distinct_from() in previous releases. The previous name remains available for backwards compatibility.

      New in version 1.1.

    • method sqlalchemy.sql.expression.ColumnOperators.isnot(other: Any) →

      Implement the IS NOT operator.

      Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.

      Changed in version 1.4: The is_not() operator is renamed from isnot() in previous releases. The previous name remains available for backwards compatibility.

      See also

      ColumnOperators.is_()

    • method isnot_distinct_from(other: Any) → ColumnOperators

      Implement the IS NOT DISTINCT FROM operator.

      Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.

      Changed in version 1.4: The is_not_distinct_from() operator is renamed from isnot_distinct_from() in previous releases. The previous name remains available for backwards compatibility.

      New in version 1.1.

    • method istartswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) → ColumnOperators

      Implement the istartswith operator, e.g. case insensitive version of .

      Produces a LIKE expression that tests against an insensitive match for the start of a string value:

      1. lower(column) LIKE lower(<other>) || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.istartswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the ColumnOperators.istartswith.autoescape flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the ColumnOperators.istartswith.autoescape flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.istartswith("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.istartswith("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '^'

          The parameter may also be combined with :

          1. somecolumn.istartswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.startswith()](#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    • method sqlalchemy.sql.expression.ColumnOperators.like(other: Any, escape: Optional[str] = None) →

      Implement the like operator.

      In a column context, produces the expression:

      1. a LIKE other

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.like("%foobar%"))
      • Parameters:

        • other – expression to be compared

        • escape

          optional escape character, renders the ESCAPE keyword, e.g.:

          1. somecolumn.like("foo/%bar", escape="/")
    1. See also
    2. [ColumnOperators.ilike()](#sqlalchemy.sql.expression.ColumnOperators.ilike "sqlalchemy.sql.expression.ColumnOperators.ilike")
    • method sqlalchemy.sql.expression.ColumnOperators.match(other: Any, **kwargs: Any) →

      Implements a database-specific ‘match’ operator.

      ColumnOperators.match() attempts to resolve to a MATCH-like function or operator provided by the backend. Examples include:

      • PostgreSQL - renders x @@ plainto_tsquery(y)

      • MySQL - renders MATCH (x) AGAINST (y IN BOOLEAN MODE)

        See also

        - MySQL specific construct with additional features.

      • Oracle - renders CONTAINS(x, y)

      • other backends may provide special implementations.

      • Backends without any special implementation will emit the operator as “MATCH”. This is compatible with SQLite, for example.

    • method sqlalchemy.sql.expression.ColumnOperators.not_ilike(other: Any, escape: Optional[str] = None) →

      implement the NOT ILIKE operator.

      This is equivalent to using negation with ColumnOperators.ilike(), i.e. ~x.ilike(y).

      Changed in version 1.4: The not_ilike() operator is renamed from notilike() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.sql.expression.ColumnOperators.not_in(other: Any) →

      implement the NOT IN operator.

      This is equivalent to using negation with ColumnOperators.in_(), i.e. ~x.in_(y).

      In the case that other is an empty sequence, the compiler produces an “empty not in” expression. This defaults to the expression “1 = 1” to produce true in all cases. The may be used to alter this behavior.

      Changed in version 1.4: The not_in() operator is renamed from notin_() in previous releases. The previous name remains available for backwards compatibility.

      Changed in version 1.2: The ColumnOperators.in_() and operators now produce a “static” expression for an empty IN sequence by default.

      See also

      ColumnOperators.in_()

    • method not_like(other: Any, escape: Optional[str] = None) → ColumnOperators

      implement the NOT LIKE operator.

      This is equivalent to using negation with , i.e. ~x.like(y).

      Changed in version 1.4: The not_like() operator is renamed from notlike() in previous releases. The previous name remains available for backwards compatibility.

      See also

      ColumnOperators.like()

    • method notilike(other: Any, escape: Optional[str] = None) → ColumnOperators

      implement the NOT ILIKE operator.

      This is equivalent to using negation with , i.e. ~x.ilike(y).

      Changed in version 1.4: The not_ilike() operator is renamed from notilike() in previous releases. The previous name remains available for backwards compatibility.

      See also

      ColumnOperators.ilike()

    • method notin_(other: Any) → ColumnOperators

      implement the NOT IN operator.

      This is equivalent to using negation with , i.e. ~x.in_(y).

      In the case that other is an empty sequence, the compiler produces an “empty not in” expression. This defaults to the expression “1 = 1” to produce true in all cases. The create_engine.empty_in_strategy may be used to alter this behavior.

      Changed in version 1.4: The not_in() operator is renamed from notin_() in previous releases. The previous name remains available for backwards compatibility.

      Changed in version 1.2: The and ColumnOperators.not_in() operators now produce a “static” expression for an empty IN sequence by default.

      See also

    • method sqlalchemy.sql.expression.ColumnOperators.notlike(other: Any, escape: Optional[str] = None) →

      implement the NOT LIKE operator.

      This is equivalent to using negation with ColumnOperators.like(), i.e. ~x.like(y).

      Changed in version 1.4: The not_like() operator is renamed from notlike() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.sql.expression.ColumnOperators.nulls_first() →

      Produce a nulls_first() clause against the parent object.

      Changed in version 1.4: The nulls_first() operator is renamed from nullsfirst() in previous releases. The previous name remains available for backwards compatibility.

    • method nulls_last() → ColumnOperators

      Produce a clause against the parent object.

      Changed in version 1.4: The nulls_last() operator is renamed from nullslast() in previous releases. The previous name remains available for backwards compatibility.

    • method sqlalchemy.sql.expression.ColumnOperators.nullsfirst() →

      Produce a nulls_first() clause against the parent object.

      Changed in version 1.4: The nulls_first() operator is renamed from nullsfirst() in previous releases. The previous name remains available for backwards compatibility.

    • method nullslast() → ColumnOperators

      Produce a clause against the parent object.

      Changed in version 1.4: The nulls_last() operator is renamed from nullslast() in previous releases. The previous name remains available for backwards compatibility.

    • method sqlalchemy.sql.expression.ColumnOperators.op(opstring: str, precedence: int = 0, is_comparison: bool = False, return_type: Optional[Union[Type[[Any]], TypeEngine[Any]]] = None, python_impl: Optional[Callable[…, Any]] = None) → Callable[[Any], ]

      inherited from the Operators.op() method of

      Produce a generic operator function.

      e.g.:

      1. somecolumn.op("*")(5)

      produces:

      1. somecolumn * 5

      This function can also be used to make bitwise operators explicit. For example:

      1. somecolumn.op('&')(0xff)

      is a bitwise AND of the value in somecolumn.

      • Parameters:

        • opstring – a string which will be output as the infix operator between this element and the expression passed to the generated function.

        • precedence

          precedence which the database is expected to apply to the operator in SQL expressions. This integer value acts as a hint for the SQL compiler to know when explicit parenthesis should be rendered around a particular operation. A lower number will cause the expression to be parenthesized when applied against another operator with higher precedence. The default value of 0 is lower than all operators except for the comma (,) and AS operators. A value of 100 will be higher or equal to all operators, and -100 will be lower than or equal to all operators.

          See also

          I’m using op() to generate a custom operator and my parenthesis are not coming out correctly - detailed description of how the SQLAlchemy SQL compiler renders parenthesis

        • is_comparison

          legacy; if True, the operator will be considered as a “comparison” operator, that is which evaluates to a boolean true/false value, like ==, >, etc. This flag is provided so that ORM relationships can establish that the operator is a comparison operator when used in a custom join condition.

          Using the is_comparison parameter is superseded by using the method instead; this more succinct operator sets this parameter automatically, but also provides correct PEP 484 typing support as the returned object will express a “boolean” datatype, i.e. BinaryExpression[bool].

        • return_type – a class or object that will force the return type of an expression produced by this operator to be of that type. By default, operators that specify Operators.op.is_comparison will resolve to , and those that do not will be of the same type as the left-hand operand.

        • python_impl

          an optional Python function that can evaluate two Python values in the same way as this operator works when run on the database server. Useful for in-Python SQL expression evaluation functions, such as for ORM hybrid attributes, and the ORM “evaluator” used to match objects in a session after a multi-row update or delete.

          e.g.:

          1. >>> expr = column('x').op('+', python_impl=lambda a, b: a + b)('y')

          The operator for the above expression will also work for non-SQL left and right objects:

          1. >>> expr.operator(5, 10)
          2. 15

          New in version 2.0.

    1. See also
    2. [Operators.bool\_op()](#sqlalchemy.sql.expression.Operators.bool_op "sqlalchemy.sql.expression.Operators.bool_op")
    3. [Redefining and Creating New Operators]($e8ad009010586d59.md#types-operators)
    4. [Using custom operators in join conditions]($b68ea79e4b407a37.md#relationship-custom-operator)
    • method sqlalchemy.sql.expression.ColumnOperators.operate(op: OperatorType, *other: Any, **kwargs: Any) →

      inherited from the Operators.operate() method of

      Operate on an argument.

      This is the lowest level of operation, raises NotImplementedError by default.

      Overriding this on a subclass can allow common behavior to be applied to all operations. For example, overriding ColumnOperators to apply func.lower() to the left and right side:

      1. class MyComparator(ColumnOperators):
      2. def operate(self, op, other, **kwargs):
      3. return op(func.lower(self), func.lower(other), **kwargs)
      • Parameters:

        • op – Operator callable.

        • *other – the ‘other’ side of the operation. Will be a single scalar for most operations.

        • **kwargs – modifiers. These may be passed by special operators such as .

    • method sqlalchemy.sql.expression.ColumnOperators.regexp_match(pattern: Any, flags: Optional[str] = None) →

      Implements a database-specific ‘regexp match’ operator.

      E.g.:

      1. stmt = select(table.c.some_column).where(
      2. table.c.some_column.regexp_match('^(b|c)')
      3. )

      ColumnOperators.regexp_match() attempts to resolve to a REGEXP-like function or operator provided by the backend, however the specific regular expression syntax and flags available are not backend agnostic.

      Examples include:

      • PostgreSQL - renders x ~ y or x !~ y when negated.

      • Oracle - renders REGEXP_LIKE(x, y)

      • SQLite - uses SQLite’s REGEXP placeholder operator and calls into the Python re.match() builtin.

      • other backends may provide special implementations.

      • Backends without any special implementation will emit the operator as “REGEXP” or “NOT REGEXP”. This is compatible with SQLite and MySQL, for example.

      Regular expression support is currently implemented for Oracle, PostgreSQL, MySQL and MariaDB. Partial support is available for SQLite. Support among third-party dialects may vary.

      • Parameters:

        • pattern – The regular expression pattern string or column clause.

        • flags – Any regular expression string flags to apply. Flags tend to be backend specific. It can be a string or a column clause. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern. When using the ignore case flag ‘i’ in PostgreSQL, the ignore case regexp match operator ~* or !~* will be used.

    1. New in version 1.4.
    2. See also
    3. [ColumnOperators.regexp\_replace()](#sqlalchemy.sql.expression.ColumnOperators.regexp_replace "sqlalchemy.sql.expression.ColumnOperators.regexp_replace")
    • method regexp_replace(pattern: Any, replacement: Any, flags: Optional[str] = None) → ColumnOperators

      Implements a database-specific ‘regexp replace’ operator.

      E.g.:

      1. stmt = select(
      2. table.c.some_column.regexp_replace(
      3. 'b(..)',
      4. 'XY',
      5. flags='g'
      6. )
      7. )

      attempts to resolve to a REGEXP_REPLACE-like function provided by the backend, that usually emit the function REGEXP_REPLACE(). However, the specific regular expression syntax and flags available are not backend agnostic.

      Regular expression replacement support is currently implemented for Oracle, PostgreSQL, MySQL 8 or greater and MariaDB. Support among third-party dialects may vary.

      • Parameters:

        • pattern – The regular expression pattern string or column clause.

        • pattern – The replacement string or column clause.

        • flags – Any regular expression string flags to apply. Flags tend to be backend specific. It can be a string or a column clause. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern.

    1. New in version 1.4.
    2. See also
    3. [ColumnOperators.regexp\_match()](#sqlalchemy.sql.expression.ColumnOperators.regexp_match "sqlalchemy.sql.expression.ColumnOperators.regexp_match")
    • method sqlalchemy.sql.expression.ColumnOperators.reverse_operate(op: OperatorType, other: Any, **kwargs: Any) →

      inherited from the Operators.reverse_operate() method of

      Reverse operate on an argument.

      Usage is the same as operate().

    • method startswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) → ColumnOperators

      Implement the startswith operator.

      Produces a LIKE expression that tests against a match for the start of a string value:

      1. column LIKE <other> || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.startswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.startswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.startswith("foo%bar", autoescape=True)

          Will render as:

          1. somecolumn LIKE :param || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.startswith("foo/%bar", escape="^")

          Will render as:

          1. somecolumn LIKE :param || '%' ESCAPE '^'

          The parameter may also be combined with ColumnOperators.startswith.autoescape:

          1. somecolumn.startswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.endswith()](#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    3. [ColumnOperators.contains()](#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    4. [ColumnOperators.like()](#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • attribute timetuple: Literal[None] = None

      Hack, allows datetime objects to be compared on the LHS.

    class sqlalchemy.sql.expression.Extract

    Represent a SQL EXTRACT clause, extract(field FROM expr).

    Class signature

    class sqlalchemy.sql.expression.Extract ()

    class sqlalchemy.sql.expression.False_

    Represent the false keyword, or equivalent, in a SQL statement.

    False_ is accessed as a constant via the function.

    Class signature

    class sqlalchemy.sql.expression.False_ (sqlalchemy.sql.expression.SingletonConstant, sqlalchemy.sql.roles.ConstExprRole, )

    class sqlalchemy.sql.expression.FunctionFilter

    Represent a function FILTER clause.

    This is a special operator against aggregate and window functions, which controls which rows are passed to it. It’s supported only by certain database backends.

    Invocation of FunctionFilter is via :

    1. func.count(1).filter(True)

    New in version 1.0.0.

    See also

    FunctionElement.filter()

    Members

    , over(),

    Class signature

    class sqlalchemy.sql.expression.FunctionFilter ()

    • method sqlalchemy.sql.expression.FunctionFilter.filter(*criterion)

      Produce an additional FILTER against the function.

      This method adds additional criteria to the initial criteria set up by .

      Multiple criteria are joined together at SQL render time via AND.

    • method sqlalchemy.sql.expression.FunctionFilter.over(partition_by: Optional[Union[Iterable[_ColumnExpressionArgument[Any]], _ColumnExpressionArgument[Any]]] = None, order_by: Optional[Union[Iterable[_ColumnExpressionArgument[Any]], _ColumnExpressionArgument[Any]]] = None, range\: Optional[typing_Tuple[Optional[int], Optional[int]]] = None, _rows: Optional[typing_Tuple[Optional[int], Optional[int]]] = None) → [_T]

      Produce an OVER clause against this filtered function.

      Used against aggregate or so-called “window” functions, for database backends that support window functions.

      The expression:

      1. func.rank().filter(MyClass.y > 5).over(order_by='x')

      is shorthand for:

      1. from sqlalchemy import over, funcfilter
      2. over(funcfilter(func.rank(), MyClass.y > 5), order_by='x')

      See over() for a full description.

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

    Represents a column label (AS).

    Represent a label, as typically applied to any column-level element using the AS sql keyword.

    Members

    , primary_key,

    Class signature

    class sqlalchemy.sql.expression.Label (sqlalchemy.sql.roles.LabeledColumnExprRole, sqlalchemy.sql.expression.NamedColumn)

    • attribute foreign_keys: AbstractSet[ForeignKey]

    • attribute primary_key: bool

    • method sqlalchemy.sql.expression.Label.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 self_group() method of just returns self.

    class sqlalchemy.sql.expression.Null

    Represent the NULL keyword in a SQL statement.

    Null is accessed as a constant via the function.

    Class signature

    class sqlalchemy.sql.expression.Null (sqlalchemy.sql.expression.SingletonConstant, sqlalchemy.sql.roles.ConstExprRole, )

    class sqlalchemy.sql.expression.Operators

    Base of comparison and logical operators.

    Implements base methods Operators.operate() and Operators.reverse_operate(), as well as Operators.__and__(), Operators.__or__(), Operators.__invert__().

    Members

    __and__(), , __or__(), , bool_op(), , operate(),

    Usually is used via its most common subclass ColumnOperators.

    • method __and__(other: Any) → Operators

      Implement the & operator.

      When used with SQL expressions, results in an AND operation, equivalent to , that is:

      1. a & b

      is equivalent to:

      1. from sqlalchemy import and_
      2. and_(a, b)

      Care should be taken when using & regarding operator precedence; the & operator has the highest precedence. The operands should be enclosed in parenthesis if they contain further sub expressions:

      1. (a == 2) & (b == 4)
    • method sqlalchemy.sql.expression.Operators.__invert__() →

      Implement the ~ operator.

      When used with SQL expressions, results in a NOT operation, equivalent to not_(), that is:

      1. ~a

      is equivalent to:

      1. from sqlalchemy import not_
      2. not_(a)
    • method __or__(other: Any) → Operators

      Implement the | operator.

      When used with SQL expressions, results in an OR operation, equivalent to , that is:

      1. a | b

      is equivalent to:

      1. from sqlalchemy import or_
      2. or_(a, b)

      Care should be taken when using | regarding operator precedence; the | operator has the highest precedence. The operands should be enclosed in parenthesis if they contain further sub expressions:

      1. (a == 2) | (b == 4)
    • method sqlalchemy.sql.expression.Operators.__sa_operate__(op: OperatorType, *other: Any, **kwargs: Any) →

      Operate on an argument.

      This is the lowest level of operation, raises NotImplementedError by default.

      Overriding this on a subclass can allow common behavior to be applied to all operations. For example, overriding ColumnOperators to apply func.lower() to the left and right side:

      1. class MyComparator(ColumnOperators):
      2. def operate(self, op, other, **kwargs):
      3. return op(func.lower(self), func.lower(other), **kwargs)
      • Parameters:

        • op – Operator callable.

        • *other – the ‘other’ side of the operation. Will be a single scalar for most operations.

        • **kwargs – modifiers. These may be passed by special operators such as .

    • method sqlalchemy.sql.expression.Operators.bool_op(opstring: str, precedence: int = 0, python_impl: Optional[Callable[[…], Any]] = None) → Callable[[Any], ]

      Return a custom boolean operator.

      This method is shorthand for calling Operators.op() and passing the flag with True. A key advantage to using Operators.bool_op() is that when using column constructs, the “boolean” nature of the returned expression will be present for purposes.

      See also

      Operators.op()

    • method op(opstring: str, precedence: int = 0, is_comparison: bool = False, return_type: Optional[Union[Type[TypeEngine[Any]], [Any]]] = None, python_impl: Optional[Callable[…, Any]] = None) → Callable[[Any], Operators]

      Produce a generic operator function.

      e.g.:

      1. somecolumn.op("*")(5)

      produces:

      1. somecolumn * 5

      This function can also be used to make bitwise operators explicit. For example:

      1. somecolumn.op('&')(0xff)

      is a bitwise AND of the value in somecolumn.

      • Parameters:

        • opstring – a string which will be output as the infix operator between this element and the expression passed to the generated function.

        • precedence

          precedence which the database is expected to apply to the operator in SQL expressions. This integer value acts as a hint for the SQL compiler to know when explicit parenthesis should be rendered around a particular operation. A lower number will cause the expression to be parenthesized when applied against another operator with higher precedence. The default value of 0 is lower than all operators except for the comma (,) and AS operators. A value of 100 will be higher or equal to all operators, and -100 will be lower than or equal to all operators.

          See also

          - detailed description of how the SQLAlchemy SQL compiler renders parenthesis

        • is_comparison

          legacy; if True, the operator will be considered as a “comparison” operator, that is which evaluates to a boolean true/false value, like ==, >, etc. This flag is provided so that ORM relationships can establish that the operator is a comparison operator when used in a custom join condition.

          Using the is_comparison parameter is superseded by using the Operators.bool_op() method instead; this more succinct operator sets this parameter automatically, but also provides correct typing support as the returned object will express a “boolean” datatype, i.e. BinaryExpression[bool].

        • return_type – a TypeEngine class or object that will force the return type of an expression produced by this operator to be of that type. By default, operators that specify will resolve to Boolean, and those that do not will be of the same type as the left-hand operand.

        • python_impl

          an optional Python function that can evaluate two Python values in the same way as this operator works when run on the database server. Useful for in-Python SQL expression evaluation functions, such as for ORM hybrid attributes, and the ORM “evaluator” used to match objects in a session after a multi-row update or delete.

          e.g.:

          1. >>> expr = column('x').op('+', python_impl=lambda a, b: a + b)('y')

          The operator for the above expression will also work for non-SQL left and right objects:

          1. >>> expr.operator(5, 10)
          2. 15

          New in version 2.0.

    1. See also
    2. [Operators.bool\_op()](#sqlalchemy.sql.expression.Operators.bool_op "sqlalchemy.sql.expression.Operators.bool_op")
    3. [Redefining and Creating New Operators]($e8ad009010586d59.md#types-operators)
    4. [Using custom operators in join conditions]($b68ea79e4b407a37.md#relationship-custom-operator)
    • method operate(op: OperatorType, *other: Any, **kwargs: Any) → Operators

      Operate on an argument.

      This is the lowest level of operation, raises NotImplementedError by default.

      Overriding this on a subclass can allow common behavior to be applied to all operations. For example, overriding to apply func.lower() to the left and right side:

      1. class MyComparator(ColumnOperators):
      2. def operate(self, op, other, **kwargs):
      3. return op(func.lower(self), func.lower(other), **kwargs)
      • Parameters:

        • op – Operator callable.

        • *other – the ‘other’ side of the operation. Will be a single scalar for most operations.

        • **kwargs – modifiers. These may be passed by special operators such as ColumnOperators.contains().

    • method reverse_operate(op: OperatorType, other: Any, **kwargs: Any) → Operators

      Reverse operate on an argument.

      Usage is the same as .

    class sqlalchemy.sql.expression.Over

    Represent an OVER clause.

    This is a special operator against a so-called “window” function, as well as any aggregate function, which produces results relative to the result set itself. Most modern SQL backends now support window functions.

    Members

    element

    Class signature

    class (sqlalchemy.sql.expression.ColumnElement)

    • attribute element: ColumnElement[_T]

      The underlying expression object to which this object refers towards.

    class sqlalchemy.sql.expression.SQLColumnExpression

    A type that may be used to indicate any SQL column element or object that acts in place of one.

    SQLColumnExpression is a base of , as well as within the bases of ORM elements such as InstrumentedAttribute, and may be used in typing to indicate arguments or return values that should behave as column expressions.

    New in version 2.0.0b4.

    Class signature

    class sqlalchemy.sql.expression.SQLColumnExpression (sqlalchemy.sql.expression.SQLCoreOperations, sqlalchemy.sql.roles.ExpressionElementRole, sqlalchemy.util.langhelpers.TypingOnly)

    class sqlalchemy.sql.expression.TextClause

    Represent a literal SQL text fragment.

    E.g.:

    1. from sqlalchemy import text
    2. t = text("SELECT * FROM users")
    3. result = connection.execute(t)

    The construct is produced using the text() function; see that function for full documentation.

    See also

    Members

    bindparams(), , self_group()

    Class signature

    class (sqlalchemy.sql.roles.DDLConstraintColumnRole, sqlalchemy.sql.roles.DDLExpressionRole, sqlalchemy.sql.roles.StatementOptionRole, sqlalchemy.sql.roles.WhereHavingRole, sqlalchemy.sql.roles.OrderByRole, sqlalchemy.sql.roles.FromClauseRole, sqlalchemy.sql.roles.SelectStatementRole, sqlalchemy.sql.roles.InElementRole, sqlalchemy.sql.expression.Generative, sqlalchemy.sql.expression.Executable, sqlalchemy.sql.expression.DQLDMLClauseElement, sqlalchemy.sql.roles.BinaryElementRole, sqlalchemy.inspection.Inspectable)

    • method bindparams(*binds: BindParameter[Any], **names_to_values: Any) → SelfTextClause

      Establish the values and/or types of bound parameters within this construct.

      Given a text construct such as:

      1. from sqlalchemy import text
      2. stmt = text("SELECT id, name FROM user WHERE name=:name "
      3. "AND timestamp=:timestamp")

      the TextClause.bindparams() method can be used to establish the initial value of :name and :timestamp, using simple keyword arguments:

      1. stmt = stmt.bindparams(name='jack',
      2. timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))

      Where above, new objects will be generated with the names name and timestamp, and values of jack and datetime.datetime(2012, 10, 8, 15, 12, 5), respectively. The types will be inferred from the values given, in this case String and .

      When specific typing behavior is needed, the positional *binds argument can be used in which to specify bindparam() constructs directly. These constructs must include at least the key argument, then an optional value and type:

      1. from sqlalchemy import bindparam
      2. stmt = stmt.bindparams(
      3. bindparam('name', value='jack', type_=String),
      4. bindparam('timestamp', type_=DateTime)
      5. )

      Above, we specified the type of for the timestamp bind, and the type of String for the name bind. In the case of name we also set the default value of "jack".

      Additional bound parameters can be supplied at statement execution time, e.g.:

      1. result = connection.execute(stmt,
      2. timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))

      The method can be called repeatedly, where it will re-use existing BindParameter objects to add new information. For example, we can call first with typing information, and a second time with value information, and it will be combined:

      1. stmt = text("SELECT id, name FROM user WHERE name=:name "
      2. "AND timestamp=:timestamp")
      3. stmt = stmt.bindparams(
      4. bindparam('name', type_=String),
      5. bindparam('timestamp', type_=DateTime)
      6. )
      7. stmt = stmt.bindparams(
      8. name='jack',
      9. timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)
      10. )

      The TextClause.bindparams() method also supports the concept of unique bound parameters. These are parameters that are “uniquified” on name at statement compilation time, so that multiple constructs may be combined together without the names conflicting. To use this feature, specify the BindParameter.unique flag on each object:

      1. stmt1 = text("select id from table where name=:name").bindparams(
      2. bindparam("name", value='name1', unique=True)
      3. )
      4. stmt2 = text("select id from table where name=:name").bindparams(
      5. bindparam("name", value='name2', unique=True)
      6. )
      7. union = union_all(
      8. stmt1.columns(column("id")),
      9. stmt2.columns(column("id"))
      10. )

      The above statement will render as:

      1. select id from table where name=:name_1
      2. UNION ALL select id from table where name=:name_2

      New in version 1.3.11: Added support for the BindParameter.unique flag to work with constructs.

    • method sqlalchemy.sql.expression.TextClause.columns(*cols, **types)

      Turn this object into a TextualSelect object that serves the same role as a SELECT statement.

      The is part of the SelectBase hierarchy and can be embedded into another statement by using the method to produce a Subquery object, which can then be SELECTed from.

      This function essentially bridges the gap between an entirely textual SELECT statement and the SQL expression language concept of a “selectable”:

      1. from sqlalchemy.sql import column, text
      2. stmt = text("SELECT id, name FROM some_table")
      3. stmt = stmt.columns(column('id'), column('name')).subquery('st')
      4. stmt = select(mytable).\
      5. select_from(
      6. mytable.join(stmt, mytable.c.name == stmt.c.name)
      7. ).where(stmt.c.id > 5)

      Above, we pass a series of elements to the TextClause.columns() method positionally. These elements now become first class elements upon the TextualSelect.selected_columns column collection, which then become part of the Subquery.c collection after is invoked.

      The column expressions we pass to TextClause.columns() may also be typed; when we do so, these objects become the effective return type of the column, so that SQLAlchemy’s result-set-processing systems may be used on the return values. This is often needed for types such as date or boolean types, as well as for unicode processing on some dialect configurations:

      1. stmt = text("SELECT id, name, timestamp FROM some_table")
      2. stmt = stmt.columns(
      3. column('id', Integer),
      4. column('name', Unicode),
      5. column('timestamp', DateTime)
      6. )
      7. for id, name, timestamp in connection.execute(stmt):
      8. print(id, name, timestamp)

      As a shortcut to the above syntax, keyword arguments referring to types alone may be used, if only type conversion is needed:

      1. stmt = text("SELECT id, name, timestamp FROM some_table")
      2. stmt = stmt.columns(
      3. id=Integer,
      4. name=Unicode,
      5. timestamp=DateTime
      6. )
      7. for id, name, timestamp in connection.execute(stmt):
      8. print(id, name, timestamp)

      The positional form of TextClause.columns() also provides the unique feature of positional column targeting, which is particularly useful when using the ORM with complex textual queries. If we specify the columns from our model to , the result set will match to those columns positionally, meaning the name or origin of the column in the textual SQL doesn’t matter:

      1. stmt = text("SELECT users.id, addresses.id, users.id, "
      2. "users.name, addresses.email_address AS email "
      3. "FROM users JOIN addresses ON users.id=addresses.user_id "
      4. "WHERE users.id = 1").columns(
      5. User.id,
      6. Address.id,
      7. Address.user_id,
      8. User.name,
      9. Address.email_address
      10. )
      11. query = session.query(User).from_statement(stmt).options(
      12. contains_eager(User.addresses))

      New in version 1.1: the TextClause.columns() method now offers positional column targeting in the result set when the column expressions are passed purely positionally.

      The method provides a direct route to calling FromClause.subquery() as well as SelectBase.cte() against a textual SELECT statement:

      1. stmt = stmt.columns(id=Integer, name=String).cte('st')
      2. stmt = select(sometable).where(sometable.c.id == stmt.c.id)
      • Parameters:

        • *cols – A series of objects, typically Column objects from a or ORM level column-mapped attributes, representing a set of columns that this textual string will SELECT from.

        • **types – A mapping of string names to TypeEngine type objects indicating the datatypes to use for names that are SELECTed from the textual string. Prefer to use the *cols argument as it also indicates positional ordering.

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

    Represent a SQL tuple.

    Members

    Class signature

    class sqlalchemy.sql.expression.Tuple (, sqlalchemy.sql.expression.ColumnElement)

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

    Represent a WITHIN GROUP (ORDER BY) clause.

    This is a special operator against so-called “ordered set aggregate” and “hypothetical set aggregate” functions, including percentile_cont(), rank(), dense_rank(), etc.

    It’s supported only by certain database backends, such as PostgreSQL, Oracle and MS SQL Server.

    The construct extracts its type from the method FunctionElement.within_group_type(). If this returns None, the function’s .type is used.

    Members

    Class signature

    class sqlalchemy.sql.expression.WithinGroup ()

    class sqlalchemy.sql.elements.WrapsColumnExpression

    Mixin that defines a as a wrapper with special labeling behavior for an expression that already has a name.

    New in version 1.4.

    See also

    Improved column labeling for simple column expressions using CAST or similar

    Class signature

    class sqlalchemy.sql.expression.WrapsColumnExpression ()

    class sqlalchemy.sql.expression.True_

    Represent the true keyword, or equivalent, in a SQL statement.

    True_ is accessed as a constant via the function.

    Class signature

    class sqlalchemy.sql.expression.True_ (sqlalchemy.sql.expression.SingletonConstant, sqlalchemy.sql.roles.ConstExprRole, )

    class sqlalchemy.sql.expression.TypeCoerce

    Represent a Python-side type-coercion wrapper.

    TypeCoerce supplies the function; see that function for usage details.

    Changed in version 1.1: The type_coerce() function now produces a persistent wrapper object rather than translating the given object in place.

    See also

    type_coerce()

    Members

    self_group()

    Class signature

    class (sqlalchemy.sql.expression.WrapsColumnExpression)

    • method sqlalchemy.sql.expression.TypeCoerce.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 self_group() method of just returns self.

    class sqlalchemy.sql.expression.UnaryExpression

    Define a ‘unary’ expression.

    A unary expression has a single column expression and an operator. The operator can be placed on the left (where it is called the ‘operator’) or right (where it is called the ‘modifier’) of the column expression.

    UnaryExpression is the basis for several unary operators including those used by , asc(), , nulls_first() and .

    Members

    self_group()

    Class signature

    class (sqlalchemy.sql.expression.ColumnElement)