class documentation

class ColumnOperators(Operators):

Known subclasses: sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance, sqlalchemy.orm.interfaces.PropComparator, sqlalchemy.sql.expression.ColumnElement, sqlalchemy.types.TypeEngine.Comparator, sqlalchemy.orm.evaluator._NoObject, sqlalchemy.sql.lambdas.PyWrapper

View In Hierarchy

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

By default, all methods call down to .operate 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:

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

Where operators.eq is essentially:

def eq(a, b):
    return a == b

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

See Also

:ref:`types_operators`

.TypeEngine.comparator_factory

.ColumnOperators

.PropComparator

Method __add__ Implement the + operator.
Method __contains__ Undocumented
Method __div__ Implement the / operator.
Method __eq__ Implement the == operator.
Method __ge__ Implement the >= operator.
Method __getitem__ Implement the [] operator.
Method __gt__ Implement the > operator.
Method __le__ Implement the <= operator.
Method __lshift__ implement the << operator.
Method __lt__ Implement the < operator.
Method __mod__ Implement the % operator.
Method __mul__ Implement the * operator.
Method __ne__ Implement the != operator.
Method __neg__ Implement the - operator.
Method __radd__ Implement the + operator in reverse.
Method __rdiv__ Implement the / operator in reverse.
Method __rmod__ Implement the % operator in reverse.
Method __rmul__ Implement the * operator in reverse.
Method __rshift__ implement the >> operator.
Method __rsub__ Implement the - operator in reverse.
Method __rtruediv__ Implement the // operator in reverse.
Method __sub__ Implement the - operator.
Method __truediv__ Implement the // operator.
Method all​_ Produce an _expression.all_ clause against the parent object.
Method any​_ Produce an _expression.any_ clause against the parent object.
Method asc Produce a _expression.asc clause against the parent object.
Method between Produce a _expression.between clause against the parent object, given the lower and upper range.
Method collate Produce a _expression.collate clause against the parent object, given the collation string.
Method concat Implement the 'concat' operator.
Method contains Implement the 'contains' operator.
Method desc Produce a _expression.desc clause against the parent object.
Method distinct Produce a _expression.distinct clause against the parent object.
Method endswith Implement the 'endswith' operator.
Method ilike Implement the ilike operator, e.g. case insensitive LIKE.
Method in​_ Implement the in operator.
Method is​_ Implement the IS operator.
Method is​_distinct​_from Implement the IS DISTINCT FROM operator.
Method is​_not Implement the IS NOT operator.
Method is​_not​_distinct​_from Implement the IS NOT DISTINCT FROM operator.
Method like Implement the like operator.
Method match Implements a database-specific 'match' operator.
Method not​_ilike implement the NOT ILIKE operator.
Method not​_in implement the NOT IN operator.
Method not​_like implement the NOT LIKE operator.
Method nulls​_first Produce a _expression.nulls_first clause against the parent object.
Method nulls​_last Produce a _expression.nulls_last clause against the parent object.
Method regexp​_match Implements a database-specific 'regexp match' operator.
Method regexp​_replace Implements a database-specific 'regexp replace' operator.
Method startswith Implement the startswith operator.
Class Variable __slots__ Undocumented
Class Variable timetuple Hack, allows datetime objects to be compared on the LHS.

Inherited from Operators:

Method __and__ Implement the & operator.
Method __invert__ Implement the ~ operator.
Method __or__ Implement the | operator.
Method bool​_op Return a custom boolean operator.
Method op Produce a generic operator function.
Method operate Operate on an argument.
Method reverse​_operate Reverse operate on an argument.
def __add__(self, other):

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.

def __contains__(self, other):

Undocumented

def __div__(self, other):

Implement the / operator.

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

def __eq__(self, other):
def __ge__(self, other):

Implement the >= operator.

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

def __getitem__(self, index):

Implement the [] operator.

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

def __gt__(self, other):

Implement the > operator.

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

def __le__(self, other):

Implement the <= operator.

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

def __lshift__(self, other):

implement the << operator.

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

def __lt__(self, other):

Implement the < operator.

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

def __mod__(self, other):

Implement the % operator.

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

def __mul__(self, other):

Implement the * operator.

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

def __ne__(self, other):

Implement the != operator.

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

def __neg__(self):

Implement the - operator.

In a column context, produces the clause -a.

def __radd__(self, other):

Implement the + operator in reverse.

See .ColumnOperators.__add__.

def __rdiv__(self, other):

Implement the / operator in reverse.

See .ColumnOperators.__div__.

def __rmod__(self, other):

Implement the % operator in reverse.

See .ColumnOperators.__mod__.

def __rmul__(self, other):

Implement the * operator in reverse.

See .ColumnOperators.__mul__.

def __rshift__(self, other):

implement the >> operator.

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

def __rsub__(self, other):

Implement the - operator in reverse.

See .ColumnOperators.__sub__.

def __rtruediv__(self, other):

Implement the // operator in reverse.

See .ColumnOperators.__truediv__.

def __sub__(self, other):

Implement the - operator.

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

def __truediv__(self, other):

Implement the // operator.

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

def all_(self):

Produce an _expression.all_ clause against the parent object.

See the documentation for _sql.all_ for examples.

Note

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

New in version 1.1.
def any_(self):

Produce an _expression.any_ clause against the parent object.

See the documentation for _sql.any_ for examples.

Note

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

New in version 1.1.
def asc(self):
Produce a _expression.asc clause against the parent object.
def between(self, cleft, cright, symmetric=False):
Produce a _expression.between clause against the parent object, given the lower and upper range.
def collate(self, collation):

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

See Also

_expression.collate

def concat(self, other):

Implement the 'concat' operator.

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

def contains(self, other, **kwargs):

Implement the 'contains' operator.

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

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

E.g.:

stmt = select(sometable).\
    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 :paramref:`.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 :paramref:`.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.

See Also

.ColumnOperators.startswith

.ColumnOperators.endswith

.ColumnOperators.like

Parameters
otherexpression 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 :paramref:`.ColumnOperators.contains.autoescape` flag is set to True.
**kwargsUndocumented
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:

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

Will render as:

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:

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

Will render as:

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

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

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.

def desc(self):
Produce a _expression.desc clause against the parent object.
def distinct(self):
Produce a _expression.distinct clause against the parent object.
def endswith(self, other, **kwargs):

Implement the 'endswith' operator.

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

column LIKE '%' || <other>

E.g.:

stmt = select(sometable).\
    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 :paramref:`.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 :paramref:`.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.

See Also

.ColumnOperators.startswith

.ColumnOperators.contains

.ColumnOperators.like

Parameters
otherexpression 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 :paramref:`.ColumnOperators.endswith.autoescape` flag is set to True.
**kwargsUndocumented
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:

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

Will render as:

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:

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

Will render as:

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

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

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.

def ilike(self, other, escape=None):

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

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

lower(a) LIKE lower(other)

Or on backends that support the ILIKE operator:

a ILIKE other

E.g.:

stmt = select(sometable).\
    where(sometable.c.column.ilike("%foobar%"))

See Also

.ColumnOperators.like

Parameters
otherexpression to be compared
escape

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

somecolumn.ilike("foo/%bar", escape="/")
def in_(self, other):

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

    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:

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

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

    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:

    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 :paramref:`.bindparam.expanding` flag:

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

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

    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:

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

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

    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:

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

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

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

    stmt.where(
        column.in_(
            select(othertable.c.y).
            where(table.c.x == othertable.c.x)
        )
    )
    

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

    WHERE COL IN (SELECT othertable.y
    FROM othertable WHERE othertable.x = table.x)
    
Parameters
othera list of literals, a _expression.select construct, or a .bindparam construct that includes the :paramref:`.bindparam.expanding` flag set to True.
def is_(self, other):

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

def is_distinct_from(self, other):

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.
def is_not(self, other):

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_

def is_not_distinct_from(self, other):

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.
def like(self, other, escape=None):

Implement the like operator.

In a column context, produces the expression:

a LIKE other

E.g.:

stmt = select(sometable).\
    where(sometable.c.column.like("%foobar%"))

See Also

.ColumnOperators.ilike

Parameters
otherexpression to be compared
escape

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

somecolumn.like("foo/%bar", escape="/")
def match(self, other, **kwargs):

Implements a database-specific 'match' operator.

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

  • PostgreSQL - renders x @@ to_tsquery(y)

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

    See Also

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

def not_ilike(self, other, escape=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

.ColumnOperators.ilike

def not_in(self, other):

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 :paramref:`_sa.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 .ColumnOperators.in_ and .ColumnOperators.not_in operators now produce a "static" expression for an empty IN sequence by default.

See Also

.ColumnOperators.in_

def not_like(self, other, escape=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

.ColumnOperators.like

def nulls_first(self):

Produce a _expression.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.
def nulls_last(self):

Produce a _expression.nulls_last 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.
def regexp_match(self, pattern, flags=None):

Implements a database-specific 'regexp match' operator.

E.g.:

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

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

New in version 1.4.

See Also

_sql.ColumnOperators.regexp_replace

Parameters
patternThe regular expression pattern string or column clause.
flagsAny 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.
def regexp_replace(self, pattern, replacement, flags=None):

Implements a database-specific 'regexp replace' operator.

E.g.:

stmt = select(
    table.c.some_column.regexp_replace(
        'b(..)',
        'X\x01Y',
        flags='g'
    )
)

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

New in version 1.4.

See Also

_sql.ColumnOperators.regexp_match

Parameters
patternThe replacement string or column clause.
replacementUndocumented
flagsAny 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.
def startswith(self, other, **kwargs):

Implement the startswith operator.

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

column LIKE <other> || '%'

E.g.:

stmt = select(sometable).\
    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 :paramref:`.ColumnOperators.startswith.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 :paramref:`.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.

See Also

.ColumnOperators.endswith

.ColumnOperators.contains

.ColumnOperators.like

Parameters
otherexpression 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 :paramref:`.ColumnOperators.startswith.autoescape` flag is set to True.
**kwargsUndocumented
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:

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

Will render as:

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:

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

Will render as:

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

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

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.

timetuple =
Hack, allows datetime objects to be compared on the LHS.