SQLAlchemy 0.8 Documentation

Release: 0.8.2 | Release Date: July 3, 2013
SQLAlchemy 0.8 Documentation » SQLAlchemy Core » SQL Statements and Expressions API

SQL Statements and Expressions API

SQL Statements and Expressions API

This section presents the API reference for the SQL Expression Language. For a full introduction to its usage, see SQL Expression Language Tutorial.

Functions

The expression package uses functions to construct SQL expressions. The return value of each function is an object instance which is a subclass of ClauseElement.

sqlalchemy.sql.expression.alias(selectable, name=None)

Return an Alias object.

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

Similar functionality is available via the alias() method available on all FromClause subclasses.

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

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

The name parameter is optional, and provides the name to use in the rendered SQL. If blank, an “anonymous” name will be deterministically generated at compile time. Deterministic means the name is guaranteed to be unique against other constructs used in the same statement, and will also be the same name for each successive compilation of the same statement object.

Parameters:
  • selectable – any FromClause subclass, such as a table, select statement, etc.
  • name – string name to be assigned as the alias. If None, a name will be deterministically generated at compile time.
sqlalchemy.sql.expression.and_(*clauses)

Join a list of clauses together using the AND operator.

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

sqlalchemy.sql.expression.asc(column)

Return an ascending ORDER BY clause element.

e.g.:

someselect.order_by(asc(table1.mycol))

produces:

ORDER BY mycol ASC
sqlalchemy.sql.expression.between(ctest, cleft, cright)

Return a BETWEEN predicate clause.

Equivalent of SQL clausetest BETWEEN clauseleft AND clauseright.

The between() method on all ColumnElement subclasses provides similar functionality.

sqlalchemy.sql.expression.bindparam(key, value=<symbol 'NO_ARG>, type_=None, unique=False, required=<symbol 'NO_ARG>, quote=None, callable_=None)

Create a bind parameter clause with the given key.

Parameters:
  • key – the key 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 BindParameter objects exist with the same key, or if its length is too long and truncation is required.
  • value

    Initial value for this bind param. This value may be overridden by the dictionary of parameters sent to statement compilation/execution.

    Defaults to None, however if neither value nor callable are passed explicitly, the required flag will be set to True which has the effect of requiring a value be present when the statement is actually executed.

    Changed in version 0.8: The required flag is set to True automatically if value or callable is not passed.

  • 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 object that will be used to pre-process the value corresponding to this BindParameter at execution time.
  • unique – if True, the key name of this BindParamClause will be modified if another BindParameter of the same name already has been located within the containing ClauseElement.
  • required

    If True, a value is required at execution time. If not passed, is set to True or False based on whether or not one of value or callable were passed..

    Changed in version 0.8: If the required flag is not specified, it will be set automatically to True or False depending on whether or not the value or callable parameters were specified.

  • 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.
sqlalchemy.sql.expression.case(whens, value=None, else_=None)

Produce a CASE statement.

whens
A sequence of pairs, or alternatively a dict, to be translated into “WHEN / THEN” clauses.
value
Optional for simple case statements, produces a column expression as in “CASE <expr> WHEN ...”
else_
Optional as well, for case defaults produces the “ELSE” portion of the “CASE” statement.

The expressions used for THEN and ELSE, when specified as strings, will be interpreted as bound values. To specify textual SQL expressions for these, use the literal_column() construct.

The expressions used for the WHEN criterion may only be literal strings when “value” is present, i.e. CASE table.somecol WHEN “x” THEN “y”. Otherwise, literal strings are not accepted in this position, and either the text(<string>) or literal(<string>) constructs must be used to interpret raw string values.

Usage examples:

case([(orderline.c.qty > 100, item.c.specialprice),
      (orderline.c.qty > 10, item.c.bulkprice)
    ], else_=item.c.regularprice)
case(value=emp.c.type, whens={
        'engineer': emp.c.salary * 1.1,
        'manager':  emp.c.salary * 3,
    })

Using literal_column(), to allow for databases that do not support bind parameters in the then clause. The type can be specified which determines the type of the case() construct overall:

case([(orderline.c.qty > 100,
        literal_column("'greaterthan100'", String)),
      (orderline.c.qty > 10, literal_column("'greaterthan10'",
        String))
    ], else_=literal_column("'lethan10'", String))
sqlalchemy.sql.expression.cast(clause, totype, **kwargs)

Return a CAST function.

Equivalent of SQL CAST(clause AS totype).

Use with a TypeEngine subclass, i.e:

cast(table.c.unit_price * table.c.qty, Numeric(10,4))

or:

cast(table.c.timestamp, DATE)
sqlalchemy.sql.expression.column(text, type_=None)

Return a textual column clause, as would be in the columns clause of a SELECT statement.

The object returned is an instance of ColumnClause, which represents the “syntactical” portion of the schema-level Column object. It is often used directly within select() constructs or with lightweight table() constructs.

Note that the column() function is not part of the sqlalchemy namespace. It must be imported from the sql package:

from sqlalchemy.sql import table, column
Parameters:
  • text – the name of the column. Quoting rules will be applied to the clause like any other column name. For textual column constructs that are not to be quoted, use the literal_column() function.
  • type_ – an optional TypeEngine object which will provide result-set translation for this column.

See ColumnClause for further examples.

sqlalchemy.sql.expression.collate(expression, collation)

Return the clause expression COLLATE collation.

e.g.:

collate(mycolumn, 'utf8_bin')

produces:

mycolumn COLLATE utf8_bin
sqlalchemy.sql.expression.delete(table, whereclause=None, **kwargs)

Represent a DELETE statement via the Delete SQL construct.

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

Parameters:
  • table – The table to be updated.
  • whereclause – A ClauseElement describing the WHERE condition of the UPDATE statement. Note that the where() generative method may be used instead.

See also

Deletes - SQL Expression Tutorial

sqlalchemy.sql.expression.desc(column)

Return a descending ORDER BY clause element.

e.g.:

someselect.order_by(desc(table1.mycol))

produces:

ORDER BY mycol DESC
sqlalchemy.sql.expression.distinct(expr)

Return a DISTINCT clause.

e.g.:

distinct(a)

renders:

DISTINCT a
sqlalchemy.sql.expression.except_(*selects, **kwargs)

Return an EXCEPT of multiple selectables.

The returned object is an instance of CompoundSelect.

*selects
a list of Select instances.
**kwargs
available keyword arguments are the same as those of select().
sqlalchemy.sql.expression.except_all(*selects, **kwargs)

Return an EXCEPT ALL of multiple selectables.

The returned object is an instance of CompoundSelect.

*selects
a list of Select instances.
**kwargs
available keyword arguments are the same as those of select().
sqlalchemy.sql.expression.exists(*args, **kwargs)

Return an EXISTS clause as applied to a Select object.

Calling styles are of the following forms:

# use on an existing select()
s = select([table.c.col1]).where(table.c.col2==5)
s = exists(s)

# construct a select() at once
exists(['*'], **select_arguments).where(criterion)

# columns argument is optional, generates "EXISTS (SELECT *)"
# by default.
exists().where(table.c.col2==5)
sqlalchemy.sql.expression.extract(field, expr)

Return the clause extract(field FROM expr).

sqlalchemy.sql.expression.false()

Return a False_ object, which compiles to false, or the boolean equivalent for the target dialect.

sqlalchemy.sql.expression.func = <sqlalchemy.sql.expression._FunctionGenerator object at 0x1019b9b10>

Generate SQL function expressions.

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

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

The element is a column-oriented SQL element like any other, and is used in that way:

>>> print select([func.count(table.c.id)])
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:

>>> print func.current_timestamp()
CURRENT_TIMESTAMP

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

>>> print func.stats.yield_curve(5, 10)
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 Unicode as the type:

>>> print func.my_string(u'hi', type_=Unicode) + ' ' + \
... func.my_string(u'there', type_=Unicode)
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 Function. This object meets the “column” interface, including comparison and labeling functions. The object can also be passed the execute() method of a Connection or Engine, where it will be wrapped inside of a SELECT statement first:

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 cast() or extract(), as these names have well-known meaning but are not exactly the same as “functions” from a SQLAlchemy perspective.

New in version 0.8: func can return non-function expression constructs for common quasi-functional names like cast() and extract().

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

sqlalchemy.sql.expression.insert(table, values=None, inline=False, **kwargs)

Represent an INSERT statement via the Insert SQL construct.

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

Parameters:
  • tableTableClause which is the subject of the insert.
  • values – collection of values to be inserted; see Insert.values() for a description of allowed formats here. Can be omitted entirely; a Insert construct will also dynamically render the VALUES clause at execution time based on the parameters passed to Connection.execute().
  • inline – if True, SQL defaults will be compiled ‘inline’ into the statement and not pre-executed.

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

The keys within values can be either Column objects or their string identifiers. Each key may reference one of:

  • a literal data value (i.e. string, number, etc.);
  • a Column object;
  • a SELECT statement.

If a SELECT statement is specified which references this INSERT statement’s table, the statement will be correlated against the INSERT statement.

See also

Insert Expressions - SQL Expression Tutorial

Inserts, Updates and Deletes - SQL Expression Tutorial

sqlalchemy.sql.expression.intersect(*selects, **kwargs)

Return an INTERSECT of multiple selectables.

The returned object is an instance of CompoundSelect.

*selects
a list of Select instances.
**kwargs
available keyword arguments are the same as those of select().
sqlalchemy.sql.expression.intersect_all(*selects, **kwargs)

Return an INTERSECT ALL of multiple selectables.

The returned object is an instance of CompoundSelect.

*selects
a list of Select instances.
**kwargs
available keyword arguments are the same as those of select().
sqlalchemy.sql.expression.join(left, right, onclause=None, isouter=False)

Return a JOIN clause element (regular inner join).

The returned object is an instance of Join.

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

Parameters:
  • left – The left side of the join.
  • right – The right side of the join.
  • onclause – Optional criterion for the ON clause, is derived from foreign key relationships established between left and right otherwise.

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

sqlalchemy.sql.expression.label(name, obj)

Return a Label 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 label() method on ColumnElement.

name
label name
obj
a ColumnElement.
sqlalchemy.sql.expression.literal(value, type_=None)

Return a literal clause, bound to a bind parameter.

Literal clauses are created automatically when non- ClauseElement objects (such as strings, ints, dates, etc.) are used in a comparison operation with a ColumnElement subclass, such as a Column 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 TypeEngine which will provide bind-parameter translation for this literal.
sqlalchemy.sql.expression.literal_column(text, type_=None)

Return a textual column expression, as would be in the columns clause of a SELECT statement.

The object returned supports further expressions in the same way as any other column object, including comparison, math and string operations. The type_ parameter is important to determine proper expression behavior (such as, ‘+’ means string concatenation or numerical addition based on the type).

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 column() 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 NullType.
sqlalchemy.sql.expression.not_(clause)

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.

sqlalchemy.sql.expression.null()

Return a Null object, which compiles to NULL.

sqlalchemy.sql.expression.nullsfirst(column)

Return a NULLS FIRST ORDER BY clause element.

e.g.:

someselect.order_by(desc(table1.mycol).nullsfirst())

produces:

ORDER BY mycol DESC NULLS FIRST
sqlalchemy.sql.expression.nullslast(column)

Return a NULLS LAST ORDER BY clause element.

e.g.:

someselect.order_by(desc(table1.mycol).nullslast())

produces:

ORDER BY mycol DESC NULLS LAST
sqlalchemy.sql.expression.or_(*clauses)

Join a list of clauses together using the OR operator.

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

sqlalchemy.sql.expression.outparam(key, type_=None)

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 ResultProxy object via its out_parameters attribute, which returns a dictionary containing the values.

sqlalchemy.sql.expression.outerjoin(left, right, onclause=None)

Return an OUTER JOIN clause element.

The returned object is an instance of Join.

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

Parameters:
  • left – The left side of the join.
  • right – The right side of the join.
  • onclause – Optional criterion for the ON clause, is derived from foreign key relationships established between left and right otherwise.

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

sqlalchemy.sql.expression.over(func, partition_by=None, order_by=None)

Produce an OVER clause against a function.

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

E.g.:

from sqlalchemy import over
over(func.row_number(), order_by='x')

Would produce “ROW_NUMBER() OVER(ORDER BY x)”.

Parameters:
  • func – a FunctionElement construct, typically generated by func.
  • 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.

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

New in version 0.7.

sqlalchemy.sql.expression.select(columns=None, whereclause=None, from_obj=[], **kwargs)

Returns a SELECT clause element.

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

The returned object is an instance of Select.

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

See also

Selecting - Core Tutorial description of select().

Parameters:
  • columns

    A list of ClauseElement objects, typically ColumnElement objects or subclasses, which will form the columns clause of the resulting statement. For all members which are instances of Selectable, the individual ColumnElement members of the Selectable will be added individually to the columns clause. For example, specifying a Table instance will result in all the contained Column objects within to be added to the columns clause.

    This argument is not present on the form of select() available on Table.

  • whereclause – A ClauseElement expression which will be used to form the WHERE clause.
  • from_obj – A list of ClauseElement objects which will be added to the FROM clause of the resulting statement. Note that “from” objects are automatically located within the columns and whereclause ClauseElements. Use this parameter to explicitly specify “from” objects which are not automatically locatable. This could include Table objects that aren’t otherwise present, or Join objects whose presence will supercede that of the Table objects already located in the other clauses.
  • autocommit – Deprecated. Use .execution_options(autocommit=<True|False>) to set the autocommit option.
  • bind=None – an Engine or Connection instance to which the resulting Select object will be bound. The Select object will otherwise automatically bind to whatever Connectable instances can be located within its contained ClauseElement members.
  • correlate=True – indicates that this Select object should have its contained FromClause elements “correlated” to an enclosing Select object. This means that any ClauseElement instance within the “froms” collection of this Select which is also present in the “froms” collection of an enclosing select will not be rendered in the FROM clause of this select statement.
  • distinct=False

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

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

    distinct is also available via the distinct() generative method.

  • for_update=False

    when True, applies FOR UPDATE to the end of the resulting statement.

    Certain database dialects also support alternate values for this parameter:

    • With the MySQL dialect, the value "read" translates to LOCK IN SHARE MODE.
    • With the Oracle and Postgresql dialects, the value "nowait" translates to FOR UPDATE NOWAIT.
    • With the Postgresql dialect, the values “read” and "read_nowait" translate to FOR SHARE and FOR SHARE NOWAIT, respectively.

      New in version 0.7.7.

  • group_by – a list of ClauseElement objects which will comprise the GROUP BY clause of the resulting select.
  • having – a ClauseElement that will comprise the HAVING clause of the resulting select when GROUP BY is used.
  • limit=None – a numerical value which usually compiles to a LIMIT expression in the resulting select. Databases that don’t support LIMIT will attempt to provide similar functionality.
  • offset=None – a numeric value which usually compiles to an OFFSET expression in the resulting select. Databases that don’t support OFFSET will attempt to provide similar functionality.
  • order_by – a scalar or list of ClauseElement objects which will comprise the ORDER BY clause of the resulting select.
  • use_labels=False

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

    use_labels is also available via the apply_labels() generative method.

sqlalchemy.sql.expression.subquery(alias, *args, **kwargs)

Return an Alias object derived from a Select.

name
alias name

*args, **kwargs

all other arguments are delivered to the select() function.
sqlalchemy.sql.expression.table(name, *columns)

Represent a textual table clause.

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

Note that the table() function is not part of the sqlalchemy namespace. It must be imported from the sql package:

from sqlalchemy.sql import table, column
Parameters:
  • name – Name of the table.
  • columns – A collection of column() constructs.

See TableClause for further examples.

sqlalchemy.sql.expression.text(text, bind=None, *args, **kwargs)

Create a SQL construct that is represented by a literal string.

E.g.:

t = text("SELECT * FROM users")
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.

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

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

To invoke SQLAlchemy typing logic for bind parameters, the bindparams list allows specification of bindparam() constructs which specify the type for a given name:

t = text("SELECT id FROM users WHERE updated_at>:updated",
            bindparams=[bindparam('updated', DateTime())]
        )

Typing during result row processing is also an important concern. Result column types are specified using the typemap dictionary, where the keys match the names of columns. These names are taken from what the DBAPI returns as cursor.description:

t = text("SELECT id, name FROM users",
        typemap={
            'id':Integer,
            'name':Unicode
        }
)

The text() construct is used internally for most cases when a literal string is specified for part of a larger query, such as within select(), update(), insert() or delete(). In those cases, the same bind parameter syntax is applied:

s = select([users.c.id, users.c.name]).where("id=:user_id")
result = connection.execute(s, user_id=12)

Using text() explicitly usually implies the construction of a full, standalone statement. As such, SQLAlchemy refers to it as an Executable object, and it supports the Executable.execution_options() method. For example, a text() construct that should be subject to “autocommit” can be set explicitly so using the autocommit option:

t = text("EXEC my_procedural_thing()").\
        execution_options(autocommit=True)

Note that SQLAlchemy’s usual “autocommit” behavior applies to text() constructs - that is, statements which begin with a phrase such as INSERT, UPDATE, DELETE, or a variety of other phrases specific to certain backends, will be eligible for autocommit if no transaction is in progress.

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.
  • autocommit – Deprecated. Use .execution_options(autocommit=<True|False>) to set the autocommit option.
  • bind – an optional connection or engine to be used for this text query.
  • bindparams – a list of bindparam() instances which can be used to define the types and/or initial values for the bind parameters within the textual statement; the keynames of the bindparams must match those within the text of the statement. The types will be used for pre-processing on bind values.
  • typemap – a dictionary mapping the names of columns represented in the columns clause of a SELECT statement to type objects, which will be used to perform post-processing on columns within the result set. This argument applies to any expression that returns result sets.
sqlalchemy.sql.expression.true()

Return a True_ object, which compiles to true, or the boolean equivalent for the target dialect.

sqlalchemy.sql.expression.tuple_(*expr)

Return a SQL tuple.

Main usage is to produce a composite IN construct:

tuple_(table.c.col1, table.c.col2).in_(
    [(1, 2), (5, 12), (10, 19)]
)

Warning

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

sqlalchemy.sql.expression.type_coerce(expr, type_)

Coerce the given expression into the given type, on the Python side only.

type_coerce() is roughly similar to cast(), except no “CAST” expression is rendered - the given type is only applied towards expression typing and against received result values.

e.g.:

from sqlalchemy.types import TypeDecorator
import uuid

class AsGuid(TypeDecorator):
    impl = String

    def process_bind_param(self, value, dialect):
        if value is not None:
            return str(value)
        else:
            return None

    def process_result_value(self, value, dialect):
        if value is not None:
            return uuid.UUID(value)
        else:
            return None

conn.execute(
    select([type_coerce(mytable.c.ident, AsGuid)]).\
            where(
                type_coerce(mytable.c.ident, AsGuid) ==
                uuid.uuid3(uuid.NAMESPACE_URL, 'bar')
            )
)
sqlalchemy.sql.expression.union(*selects, **kwargs)

Return a UNION of multiple selectables.

The returned object is an instance of CompoundSelect.

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

*selects
a list of Select instances.
**kwargs
available keyword arguments are the same as those of select().
sqlalchemy.sql.expression.union_all(*selects, **kwargs)

Return a UNION ALL of multiple selectables.

The returned object is an instance of CompoundSelect.

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

*selects
a list of Select instances.
**kwargs
available keyword arguments are the same as those of select().
sqlalchemy.sql.expression.update(table, whereclause=None, values=None, inline=False, **kwargs)

Represent an UPDATE statement via the Update SQL construct.

E.g.:

from sqlalchemy import update

stmt = update(users).where(users.c.id==5).\
        values(name='user #5')

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

stmt = users.update().\
            where(users.c.id==5).\
            values(name='user #5')
Parameters:
  • table – A Table object representing the database table to be updated.
  • whereclause

    Optional SQL expression describing the WHERE condition of the UPDATE statement. Modern applications may prefer to use the generative where() method to specify the WHERE clause.

    The WHERE clause can refer to multiple tables. For databases which support this, an UPDATE FROM clause will be generated, or on MySQL, a multi-table update. The statement will fail on databases that don’t have support for multi-table update statements. A SQL-standard method of referring to additional tables in the WHERE clause is to use a correlated subquery:

    users.update().values(name='ed').where(
            users.c.name==select([addresses.c.email_address]).\
                        where(addresses.c.user_id==users.c.id).\
                        as_scalar()
            )

    Changed in version 0.7.4: The WHERE clause can refer to multiple tables.

  • values

    Optional dictionary which specifies the SET conditions of the UPDATE. If left as None, the SET conditions are determined from those parameters passed to the statement during the execution and/or compilation of the statement. When compiled standalone without any parameters, the SET clause generates for all columns.

    Modern applications may prefer to use the generative Update.values() method to set the values of the UPDATE statement.

  • inline – if True, SQL defaults present on Column objects via the default keyword will be compiled ‘inline’ into the statement and not pre-executed. This means that their values will not be available in the dictionary returned from ResultProxy.last_updated_params().

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

The keys within values can be either Column objects or their string identifiers (specifically the “key” of the Column, normally but not necessarily equivalent to its “name”). Normally, the Column objects used here are expected to be part of the target Table that is the table to be updated. However when using MySQL, a multiple-table UPDATE statement can refer to columns from any of the tables referred to in the WHERE clause.

The values referred to in values are typically:

  • a literal data value (i.e. string, number, etc.)
  • a SQL expression, such as a related Column, a scalar-returning select() construct, etc.

When combining select() constructs within the values clause of an update() construct, the subquery represented by the select() should be correlated to the parent table, that is, providing criterion which links the table inside the subquery to the outer table being updated:

users.update().values(
        name=select([addresses.c.email_address]).\
                where(addresses.c.user_id==users.c.id).\
                as_scalar()
    )

See also

Inserts, Updates and Deletes - SQL Expression Language Tutorial

Classes

class sqlalchemy.sql.expression.Alias(selectable, name=None)

Bases: sqlalchemy.sql.expression.FromClause

Represents an table or selectable alias (AS).

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

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

alias(name=None)
inherited from the alias() method of FromClause

return an alias of this FromClause.

This is shorthand for calling:

from sqlalchemy import alias
a = alias(self, name=name)

See alias() for details.

c
inherited from the c attribute of FromClause

An alias for the columns attribute.

columns
inherited from the columns attribute of FromClause

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

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

select([mytable]).where(mytable.c.somecolumn == 5)
compare(other, **kw)
inherited from the compare() method of ClauseElement

Compare this ClauseElement 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 ColumnElement)

compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
correspond_on_equivalents(column, equivalents)
inherited from the correspond_on_equivalents() method of FromClause

Return corresponding_column for the given column, or if None search for a match in the given dictionary.

corresponding_column(column, require_embedded=False)
inherited from the corresponding_column() method of FromClause

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

Parameters:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for

the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.

count(whereclause=None, **params)
inherited from the count() method of FromClause

return a SELECT COUNT generated against this FromClause.

foreign_keys
inherited from the foreign_keys attribute of FromClause

Return the collection of ForeignKey objects which this FromClause references.

join(right, onclause=None, isouter=False)
inherited from the join() method of FromClause

return a join of this FromClause against another FromClause.

outerjoin(right, onclause=None)
inherited from the outerjoin() method of FromClause

return an outer join of this FromClause against another FromClause.

params(*optionaldict, **kwargs)
inherited from the params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
primary_key
inherited from the primary_key attribute of FromClause

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

replace_selectable(old, alias)
inherited from the replace_selectable() method of FromClause

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

select(whereclause=None, **params)
inherited from the select() method of FromClause

return a SELECT of this FromClause.

See also

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

self_group(against=None)
inherited from the self_group() method of ClauseElement

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 select() constructs when placed into the FROM clause of another select(). (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 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 self_group() method of ClauseElement just returns self.

unique_params(*optionaldict, **kwargs)
inherited from the unique_params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

class sqlalchemy.sql.expression.BinaryExpression(left, right, operator, type_=None, negate=None, modifiers=None)

Bases: sqlalchemy.sql.expression.ColumnElement

Represent an expression that is LEFT <operator> RIGHT.

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

>>> from sqlalchemy.sql import column
>>> column('a') + column('b')
<sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
>>> print column('a') + column('b')
a + b
__eq__(other)
inherited from the __eq__() method of ColumnOperators

Implement the == operator.

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

__le__(other)
inherited from the __le__() method of ColumnOperators

Implement the <= operator.

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

__lt__(other)
inherited from the __lt__() method of ColumnOperators

Implement the < operator.

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

__ne__(other)
inherited from the __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.

anon_label
inherited from the anon_label attribute of ColumnElement

provides a constant ‘anonymous label’ for this ColumnElement.

This is a label() expression which will be named at compile time. The same label() is returned each time anon_label is called so that expressions can reference anon_label multiple times, producing the same label name at compile time.

the compiler uses this function automatically at compile time for expressions that are known to be ‘unnamed’ like binary expressions and function calls.

asc()
inherited from the asc() method of ColumnOperators

Produce a asc() clause against the parent object.

between(cleft, cright)
inherited from the between() method of ColumnOperators

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

collate(collation)
inherited from the collate() method of ColumnOperators

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

compare(other, **kw)

Compare this BinaryExpression against the given BinaryExpression.

compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
concat(other)
inherited from the concat() method of ColumnOperators

Implement the ‘concat’ operator.

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

contains(other, **kwargs)
inherited from the contains() method of ColumnOperators

Implement the ‘contains’ operator.

In a column context, produces the clause LIKE '%<other>%'

desc()
inherited from the desc() method of ColumnOperators

Produce a desc() clause against the parent object.

distinct()
inherited from the distinct() method of ColumnOperators

Produce a distinct() clause against the parent object.

endswith(other, **kwargs)
inherited from the endswith() method of ColumnOperators

Implement the ‘endswith’ operator.

In a column context, produces the clause LIKE '%<other>'

expression
inherited from the expression attribute of ColumnElement

Return a column expression.

Part of the inspection interface; returns self.

ilike(other, escape=None)
inherited from the ilike() method of ColumnOperators

Implement the ilike operator.

In a column context, produces the clause a ILIKE other.

E.g.:

select([sometable]).where(sometable.c.column.ilike("%foobar%"))
Parameters:
  • other – expression to be compared
  • escape

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

    somecolumn.ilike("foo/%bar", escape="/")
in_(other)
inherited from the in_() method of ColumnOperators

Implement the in operator.

In a column context, produces the clause a IN other. “other” may be a tuple/list of column expressions, or a select() construct.

is_(other)
inherited from the is_() method of ColumnOperators

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.

New in version 0.7.9.

isnot(other)
inherited from the isnot() 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.

New in version 0.7.9.

label(name)
inherited from the label() method of ColumnElement

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

This is a shortcut to the label() function.

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

like(other, escape=None)
inherited from the like() method of ColumnOperators

Implement the like operator.

In a column context, produces the clause a LIKE other.

E.g.:

select([sometable]).where(sometable.c.column.like("%foobar%"))
Parameters:
  • other – expression to be compared
  • escape

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

    somecolumn.like("foo/%bar", escape="/")
match(other, **kwargs)
inherited from the match() method of ColumnOperators

Implements the ‘match’ operator.

In a column context, this produces a MATCH clause, i.e. MATCH '<other>'. The allowed contents of other are database backend specific.

notilike(other, escape=None)
inherited from the notilike() method of ColumnOperators

implement the NOT ILIKE operator.

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

New in version 0.8.

notin_(other)
inherited from the notin_() method of ColumnOperators

implement the NOT IN operator.

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

New in version 0.8.

notlike(other, escape=None)
inherited from the notlike() method of ColumnOperators

implement the NOT LIKE operator.

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

New in version 0.8.

nullsfirst()
inherited from the nullsfirst() method of ColumnOperators

Produce a nullsfirst() clause against the parent object.

nullslast()
inherited from the nullslast() method of ColumnOperators

Produce a nullslast() clause against the parent object.

op(opstring, precedence=0)
inherited from the op() method of Operators

produce a generic operator function.

e.g.:

somecolumn.op("*")(5)

produces:

somecolumn * 5

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

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

is a bitwise AND of the value in somecolumn.

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

    precedence to apply to the operator, when parenthesizing expressions. 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.

    New in version 0.8: - added the ‘precedence’ argument.

params(*optionaldict, **kwargs)
inherited from the params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
shares_lineage(othercolumn)
inherited from the shares_lineage() method of ColumnElement

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

startswith(other, **kwargs)
inherited from the startswith() method of ColumnOperators

Implement the startwith operator.

In a column context, produces the clause LIKE '<other>%'

unique_params(*optionaldict, **kwargs)
inherited from the unique_params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

class sqlalchemy.sql.expression.BindParameter(key, value, type_=None, unique=False, callable_=None, isoutparam=False, required=False, quote=None, _compared_to_operator=None, _compared_to_type=None)

Bases: sqlalchemy.sql.expression.ColumnElement

Represent a bind parameter.

Public constructor is the bindparam() function.

__eq__(other)
inherited from the __eq__() method of ColumnOperators

Implement the == operator.

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

__init__(key, value, type_=None, unique=False, callable_=None, isoutparam=False, required=False, quote=None, _compared_to_operator=None, _compared_to_type=None)

Construct a BindParameter.

Parameters:
  • key – the key 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 BindParameter objects exist with the same key, or if its length is too long and truncation is required.
  • value – Initial value for this bind param. This value may be overridden by the dictionary of parameters sent to statement compilation/execution.
  • 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 object that will be used to pre-process the value corresponding to this BindParameter at execution time.
  • unique – if True, the key name of this BindParamClause will be modified if another BindParameter of the same name already has been located within the containing ClauseElement.
  • 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.
  • required – a value is required at execution time.
  • isoutparam – if True, the parameter should be treated like a stored procedure “OUT” parameter.
__le__(other)
inherited from the __le__() method of ColumnOperators

Implement the <= operator.

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

__lt__(other)
inherited from the __lt__() method of ColumnOperators

Implement the < operator.

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

__ne__(other)
inherited from the __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.

anon_label
inherited from the anon_label attribute of ColumnElement

provides a constant ‘anonymous label’ for this ColumnElement.

This is a label() expression which will be named at compile time. The same label() is returned each time anon_label is called so that expressions can reference anon_label multiple times, producing the same label name at compile time.

the compiler uses this function automatically at compile time for expressions that are known to be ‘unnamed’ like binary expressions and function calls.

asc()
inherited from the asc() method of ColumnOperators

Produce a asc() clause against the parent object.

between(cleft, cright)
inherited from the between() method of ColumnOperators

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

collate(collation)
inherited from the collate() method of ColumnOperators

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

compare(other, **kw)

Compare this BindParameter to the given clause.

compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
concat(other)
inherited from the concat() method of ColumnOperators

Implement the ‘concat’ operator.

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

contains(other, **kwargs)
inherited from the contains() method of ColumnOperators

Implement the ‘contains’ operator.

In a column context, produces the clause LIKE '%<other>%'

desc()
inherited from the desc() method of ColumnOperators

Produce a desc() clause against the parent object.

distinct()
inherited from the distinct() method of ColumnOperators

Produce a distinct() clause against the parent object.

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.

endswith(other, **kwargs)
inherited from the endswith() method of ColumnOperators

Implement the ‘endswith’ operator.

In a column context, produces the clause LIKE '%<other>'

expression
inherited from the expression attribute of ColumnElement

Return a column expression.

Part of the inspection interface; returns self.

get_children(**kwargs)
inherited from the get_children() method of ClauseElement

Return immediate child elements of this ClauseElement.

This is used for visit traversal.

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

ilike(other, escape=None)
inherited from the ilike() method of ColumnOperators

Implement the ilike operator.

In a column context, produces the clause a ILIKE other.

E.g.:

select([sometable]).where(sometable.c.column.ilike("%foobar%"))
Parameters:
  • other – expression to be compared
  • escape

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

    somecolumn.ilike("foo/%bar", escape="/")
in_(other)
inherited from the in_() method of ColumnOperators

Implement the in operator.

In a column context, produces the clause a IN other. “other” may be a tuple/list of column expressions, or a select() construct.

is_(other)
inherited from the is_() method of ColumnOperators

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.

New in version 0.7.9.

isnot(other)
inherited from the isnot() 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.

New in version 0.7.9.

label(name)
inherited from the label() method of ColumnElement

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

This is a shortcut to the label() function.

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

like(other, escape=None)
inherited from the like() method of ColumnOperators

Implement the like operator.

In a column context, produces the clause a LIKE other.

E.g.:

select([sometable]).where(sometable.c.column.like("%foobar%"))
Parameters:
  • other – expression to be compared
  • escape

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

    somecolumn.like("foo/%bar", escape="/")
match(other, **kwargs)
inherited from the match() method of ColumnOperators

Implements the ‘match’ operator.

In a column context, this produces a MATCH clause, i.e. MATCH '<other>'. The allowed contents of other are database backend specific.

notilike(other, escape=None)
inherited from the notilike() method of ColumnOperators

implement the NOT ILIKE operator.

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

New in version 0.8.

notin_(other)
inherited from the notin_() method of ColumnOperators

implement the NOT IN operator.

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

New in version 0.8.

notlike(other, escape=None)
inherited from the notlike() method of ColumnOperators

implement the NOT LIKE operator.

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

New in version 0.8.

nullsfirst()
inherited from the nullsfirst() method of ColumnOperators

Produce a nullsfirst() clause against the parent object.

nullslast()
inherited from the nullslast() method of ColumnOperators

Produce a nullslast() clause against the parent object.

op(opstring, precedence=0)
inherited from the op() method of Operators

produce a generic operator function.

e.g.:

somecolumn.op("*")(5)

produces:

somecolumn * 5

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

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

is a bitwise AND of the value in somecolumn.

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

    precedence to apply to the operator, when parenthesizing expressions. 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.

    New in version 0.8: - added the ‘precedence’ argument.

params(*optionaldict, **kwargs)
inherited from the params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
self_group(against=None)
inherited from the self_group() method of ClauseElement

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 select() constructs when placed into the FROM clause of another select(). (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 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 self_group() method of ClauseElement just returns self.

shares_lineage(othercolumn)
inherited from the shares_lineage() method of ColumnElement

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

startswith(other, **kwargs)
inherited from the startswith() method of ColumnOperators

Implement the startwith operator.

In a column context, produces the clause LIKE '<other>%'

unique_params(*optionaldict, **kwargs)
inherited from the unique_params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

class sqlalchemy.sql.expression.ClauseElement

Bases: sqlalchemy.sql.visitors.Visitable

Base class for elements of a programmatically constructed SQL expression.

compare(other, **kw)

Compare this ClauseElement 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 ColumnElement)

compile(bind=None, dialect=None, **kw)

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
get_children(**kwargs)

Return immediate child elements of this ClauseElement.

This is used for visit traversal.

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

params(*optionaldict, **kwargs)

Return a copy with bindparam() elements replaced.

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

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
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 select() constructs when placed into the FROM clause of another select(). (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 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 self_group() method of ClauseElement just returns self.

unique_params(*optionaldict, **kwargs)

Return a copy with bindparam() elements replaced.

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

class sqlalchemy.sql.expression.ClauseList(*clauses, **kwargs)

Bases: sqlalchemy.sql.expression.ClauseElement

Describe a list of clauses, separated by an operator.

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

compare(other, **kw)

Compare this ClauseList to the given ClauseList, including a comparison of all the clause items.

class sqlalchemy.sql.expression.ColumnClause(text, selectable=None, type_=None, is_literal=False)

Bases: sqlalchemy.sql.expression.Immutable, sqlalchemy.sql.expression.ColumnElement

Represents a generic column expression from any textual string.

This includes columns associated with tables, aliases and select statements, but also any arbitrary text. May or may not be bound to an underlying Selectable.

ColumnClause is constructed by itself typically via the column() function. It may be placed directly into constructs such as select() constructs:

from sqlalchemy.sql import column, select

c1, c2 = column("c1"), column("c2")
s = select([c1, c2]).where(c1==5)

There is also a variant on column() known as literal_column() - the difference is that in the latter case, the string value is assumed to be an exact expression, rather than a column name, so that no quoting rules or similar are applied:

from sqlalchemy.sql import literal_column, select

s = select([literal_column("5 + 7")])

ColumnClause can also be used in a table-like fashion by combining the column() function with the table() function, to produce a “lightweight” form of table metadata:

from sqlalchemy.sql import table, column

user = table("user",
        column("id"),
        column("name"),
        column("description"),
)

The above construct can be created in an ad-hoc fashion and is not associated with any schema.MetaData, unlike it’s more full fledged schema.Table counterpart.

Parameters:
  • text – the text of the element.
  • selectable – parent selectable.
  • typetypes.TypeEngine object which can associate this ColumnClause 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 literal_column() function is usually used to create such a ColumnClause.
__eq__(other)
inherited from the __eq__() method of ColumnOperators

Implement the == operator.

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

__le__(other)
inherited from the __le__() method of ColumnOperators

Implement the <= operator.

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

__lt__(other)
inherited from the __lt__() method of ColumnOperators

Implement the < operator.

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

__ne__(other)
inherited from the __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.

anon_label
inherited from the anon_label attribute of ColumnElement

provides a constant ‘anonymous label’ for this ColumnElement.

This is a label() expression which will be named at compile time. The same label() is returned each time anon_label is called so that expressions can reference anon_label multiple times, producing the same label name at compile time.

the compiler uses this function automatically at compile time for expressions that are known to be ‘unnamed’ like binary expressions and function calls.

asc()
inherited from the asc() method of ColumnOperators

Produce a asc() clause against the parent object.

between(cleft, cright)
inherited from the between() method of ColumnOperators

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

collate(collation)
inherited from the collate() method of ColumnOperators

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

compare(other, use_proxies=False, equivalents=None, **kw)
inherited from the compare() method of ColumnElement

Compare this ColumnElement to another.

Special arguments understood:

Parameters:
  • use_proxies – when True, consider two columns that share a common base column as equivalent (i.e. shares_lineage())
  • equivalents – a dictionary of columns as keys mapped to sets of columns. If the given “other” column is present in this dictionary, if any of the columns in the corresponding set() pass the comparison test, the result is True. This is used to expand the comparison to other columns that may be known to be equivalent to this one via foreign key or other criterion.
compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
concat(other)
inherited from the concat() method of ColumnOperators

Implement the ‘concat’ operator.

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

contains(other, **kwargs)
inherited from the contains() method of ColumnOperators

Implement the ‘contains’ operator.

In a column context, produces the clause LIKE '%<other>%'

desc()
inherited from the desc() method of ColumnOperators

Produce a desc() clause against the parent object.

distinct()
inherited from the distinct() method of ColumnOperators

Produce a distinct() clause against the parent object.

endswith(other, **kwargs)
inherited from the endswith() method of ColumnOperators

Implement the ‘endswith’ operator.

In a column context, produces the clause LIKE '%<other>'

expression
inherited from the expression attribute of ColumnElement

Return a column expression.

Part of the inspection interface; returns self.

get_children(**kwargs)
inherited from the get_children() method of ClauseElement

Return immediate child elements of this ClauseElement.

This is used for visit traversal.

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

ilike(other, escape=None)
inherited from the ilike() method of ColumnOperators

Implement the ilike operator.

In a column context, produces the clause a ILIKE other.

E.g.:

select([sometable]).where(sometable.c.column.ilike("%foobar%"))
Parameters:
  • other – expression to be compared
  • escape

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

    somecolumn.ilike("foo/%bar", escape="/")
in_(other)
inherited from the in_() method of ColumnOperators

Implement the in operator.

In a column context, produces the clause a IN other. “other” may be a tuple/list of column expressions, or a select() construct.

is_(other)
inherited from the is_() method of ColumnOperators

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.

New in version 0.7.9.

isnot(other)
inherited from the isnot() 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.

New in version 0.7.9.

label(name)
inherited from the label() method of ColumnElement

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

This is a shortcut to the label() function.

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

like(other, escape=None)
inherited from the like() method of ColumnOperators

Implement the like operator.

In a column context, produces the clause a LIKE other.

E.g.:

select([sometable]).where(sometable.c.column.like("%foobar%"))
Parameters:
  • other – expression to be compared
  • escape

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

    somecolumn.like("foo/%bar", escape="/")
match(other, **kwargs)
inherited from the match() method of ColumnOperators

Implements the ‘match’ operator.

In a column context, this produces a MATCH clause, i.e. MATCH '<other>'. The allowed contents of other are database backend specific.

notilike(other, escape=None)
inherited from the notilike() method of ColumnOperators

implement the NOT ILIKE operator.

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

New in version 0.8.

notin_(other)
inherited from the notin_() method of ColumnOperators

implement the NOT IN operator.

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

New in version 0.8.

notlike(other, escape=None)
inherited from the notlike() method of ColumnOperators

implement the NOT LIKE operator.

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

New in version 0.8.

nullsfirst()
inherited from the nullsfirst() method of ColumnOperators

Produce a nullsfirst() clause against the parent object.

nullslast()
inherited from the nullslast() method of ColumnOperators

Produce a nullslast() clause against the parent object.

op(opstring, precedence=0)
inherited from the op() method of Operators

produce a generic operator function.

e.g.:

somecolumn.op("*")(5)

produces:

somecolumn * 5

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

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

is a bitwise AND of the value in somecolumn.

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

    precedence to apply to the operator, when parenthesizing expressions. 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.

    New in version 0.8: - added the ‘precedence’ argument.

self_group(against=None)
inherited from the self_group() method of ClauseElement

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 select() constructs when placed into the FROM clause of another select(). (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 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 self_group() method of ClauseElement just returns self.

shares_lineage(othercolumn)
inherited from the shares_lineage() method of ColumnElement

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

startswith(other, **kwargs)
inherited from the startswith() method of ColumnOperators

Implement the startwith operator.

In a column context, produces the clause LIKE '<other>%'

class sqlalchemy.sql.expression.ColumnCollection(*cols)

Bases: sqlalchemy.util._collections.OrderedProperties

An ordered dictionary that stores a list of ColumnElement instances.

Overrides the __eq__() method to produce SQL clauses between sets of correlated columns.

add(column)

Add a column to this collection.

The key attribute of the column will be used as the hash key for this dictionary.

replace(column)

add the given column to this collection, removing unaliased versions of this column as well as existing columns with the same key.

e.g.:

t = Table('sometable', metadata, Column('col1', Integer))
t.columns.replace(Column('col1', Integer, key='columnone'))

will remove the original ‘col1’ from the collection, and add the new column under the name ‘columnname’.

Used by schema.Column to override columns during table reflection.

class sqlalchemy.sql.expression.ColumnElement

Bases: sqlalchemy.sql.expression.ClauseElement, sqlalchemy.sql.operators.ColumnOperators

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 ColumnElement is the Column object, ColumnElement 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 ColumnElement 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 ColumnElement instances which are composed from other, more fundamental ColumnElement objects. For example, two ColumnClause objects can be added together with the addition operator + to produce a BinaryExpression. Both ColumnClause and BinaryExpression are subclasses of ColumnElement:

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

ColumnElement supports the ability to be a proxy element, which indicates that the ColumnElement may be associated with a Selectable which was derived from another Selectable. An example of a “derived” Selectable is an Alias of a Table. For the ambitious, an in-depth discussion of this concept can be found at Expression Transformations.

__eq__(other)
inherited from the __eq__() method of ColumnOperators

Implement the == operator.

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

__init__
inherited from the __init__ attribute of object

x.__init__(...) initializes x; see help(type(x)) for signature

__le__(other)
inherited from the __le__() method of ColumnOperators

Implement the <= operator.

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

__lt__(other)
inherited from the __lt__() method of ColumnOperators

Implement the < operator.

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

__ne__(other)
inherited from the __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.

anon_label

provides a constant ‘anonymous label’ for this ColumnElement.

This is a label() expression which will be named at compile time. The same label() is returned each time anon_label is called so that expressions can reference anon_label multiple times, producing the same label name at compile time.

the compiler uses this function automatically at compile time for expressions that are known to be ‘unnamed’ like binary expressions and function calls.

asc()
inherited from the asc() method of ColumnOperators

Produce a asc() clause against the parent object.

between(cleft, cright)
inherited from the between() method of ColumnOperators

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

collate(collation)
inherited from the collate() method of ColumnOperators

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

compare(other, use_proxies=False, equivalents=None, **kw)

Compare this ColumnElement to another.

Special arguments understood:

Parameters:
  • use_proxies – when True, consider two columns that share a common base column as equivalent (i.e. shares_lineage())
  • equivalents – a dictionary of columns as keys mapped to sets of columns. If the given “other” column is present in this dictionary, if any of the columns in the corresponding set() pass the comparison test, the result is True. This is used to expand the comparison to other columns that may be known to be equivalent to this one via foreign key or other criterion.
compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
concat(other)
inherited from the concat() method of ColumnOperators

Implement the ‘concat’ operator.

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

contains(other, **kwargs)
inherited from the contains() method of ColumnOperators

Implement the ‘contains’ operator.

In a column context, produces the clause LIKE '%<other>%'

desc()
inherited from the desc() method of ColumnOperators

Produce a desc() clause against the parent object.

distinct()
inherited from the distinct() method of ColumnOperators

Produce a distinct() clause against the parent object.

endswith(other, **kwargs)
inherited from the endswith() method of ColumnOperators

Implement the ‘endswith’ operator.

In a column context, produces the clause LIKE '%<other>'

expression

Return a column expression.

Part of the inspection interface; returns self.

get_children(**kwargs)
inherited from the get_children() method of ClauseElement

Return immediate child elements of this ClauseElement.

This is used for visit traversal.

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

ilike(other, escape=None)
inherited from the ilike() method of ColumnOperators

Implement the ilike operator.

In a column context, produces the clause a ILIKE other.

E.g.:

select([sometable]).where(sometable.c.column.ilike("%foobar%"))
Parameters:
  • other – expression to be compared
  • escape

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

    somecolumn.ilike("foo/%bar", escape="/")
in_(other)
inherited from the in_() method of ColumnOperators

Implement the in operator.

In a column context, produces the clause a IN other. “other” may be a tuple/list of column expressions, or a select() construct.

is_(other)
inherited from the is_() method of ColumnOperators

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.

New in version 0.7.9.

isnot(other)
inherited from the isnot() 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.

New in version 0.7.9.

label(name)

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

This is a shortcut to the label() function.

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

like(other, escape=None)
inherited from the like() method of ColumnOperators

Implement the like operator.

In a column context, produces the clause a LIKE other.

E.g.:

select([sometable]).where(sometable.c.column.like("%foobar%"))
Parameters:
  • other – expression to be compared
  • escape

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

    somecolumn.like("foo/%bar", escape="/")
match(other, **kwargs)
inherited from the match() method of ColumnOperators

Implements the ‘match’ operator.

In a column context, this produces a MATCH clause, i.e. MATCH '<other>'. The allowed contents of other are database backend specific.

notilike(other, escape=None)
inherited from the notilike() method of ColumnOperators

implement the NOT ILIKE operator.

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

New in version 0.8.

notin_(other)
inherited from the notin_() method of ColumnOperators

implement the NOT IN operator.

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

New in version 0.8.

notlike(other, escape=None)
inherited from the notlike() method of ColumnOperators

implement the NOT LIKE operator.

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

New in version 0.8.

nullsfirst()
inherited from the nullsfirst() method of ColumnOperators

Produce a nullsfirst() clause against the parent object.

nullslast()
inherited from the nullslast() method of ColumnOperators

Produce a nullslast() clause against the parent object.

op(opstring, precedence=0)
inherited from the op() method of Operators

produce a generic operator function.

e.g.:

somecolumn.op("*")(5)

produces:

somecolumn * 5

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

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

is a bitwise AND of the value in somecolumn.

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

    precedence to apply to the operator, when parenthesizing expressions. 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.

    New in version 0.8: - added the ‘precedence’ argument.

params(*optionaldict, **kwargs)
inherited from the params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
self_group(against=None)
inherited from the self_group() method of ClauseElement

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 select() constructs when placed into the FROM clause of another select(). (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 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 self_group() method of ClauseElement just returns self.

shares_lineage(othercolumn)

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

startswith(other, **kwargs)
inherited from the startswith() method of ColumnOperators

Implement the startwith operator.

In a column context, produces the clause LIKE '<other>%'

unique_params(*optionaldict, **kwargs)
inherited from the unique_params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

class sqlalchemy.sql.operators.ColumnOperators

Bases: sqlalchemy.sql.operators.Operators

Defines boolean, comparison, and other operators for 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 ColumnElement overrides Operators.operate() and others to return further ColumnElement constructs, so that the == operation above is replaced by a clause construct.

See also:

Redefining and Creating New Operators

TypeEngine.comparator_factory

ColumnOperators

PropComparator

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

__and__(other)
inherited from the __and__() method of Operators

Implement the & operator.

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

a & b

is equivalent to:

from sqlalchemy import and_
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:

(a == 2) & (b == 4)
__delattr__
inherited from the __delattr__ attribute of object

x.__delattr__(‘name’) <==> del x.name

__div__(other)

Implement the / operator.

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

__eq__(other)

Implement the == operator.

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

__format__()
inherited from the __format__() method of object

default object formatter

__ge__(other)

Implement the >= operator.

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

__getattribute__
inherited from the __getattribute__ attribute of object

x.__getattribute__(‘name’) <==> x.name

__getitem__(index)

Implement the [] operator.

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

__gt__(other)

Implement the > operator.

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

__hash__

x.__hash__() <==> hash(x)

__init__
inherited from the __init__ attribute of object

x.__init__(...) initializes x; see help(type(x)) for signature

__invert__()
inherited from the __invert__() method of Operators

Implement the ~ operator.

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

~a

is equivalent to:

from sqlalchemy import not_
not_(a)
__le__(other)

Implement the <= operator.

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

__lshift__(other)

implement the << operator.

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

__lt__(other)

Implement the < operator.

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

__mod__(other)

Implement the % operator.

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

__mul__(other)

Implement the * operator.

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

__ne__(other)

Implement the != operator.

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

__neg__()

Implement the - operator.

In a column context, produces the clause -a.

static __new__(S, ...) → a new object with type S, a subtype of T
inherited from the __new__() method of object
__or__(other)
inherited from the __or__() method of Operators

Implement the | operator.

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

a | b

is equivalent to:

from sqlalchemy import or_
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:

(a == 2) | (b == 4)
__radd__(other)

Implement the + operator in reverse.

See ColumnOperators.__add__().

__rdiv__(other)

Implement the / operator in reverse.

See ColumnOperators.__div__().

__reduce__()
inherited from the __reduce__() method of object

helper for pickle

__reduce_ex__()
inherited from the __reduce_ex__() method of object

helper for pickle

__repr__
inherited from the __repr__ attribute of object

x.__repr__() <==> repr(x)

__rmul__(other)

Implement the * operator in reverse.

See ColumnOperators.__mul__().

__rshift__(other)

implement the >> operator.

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

__rsub__(other)

Implement the - operator in reverse.

See ColumnOperators.__sub__().

__rtruediv__(other)

Implement the // operator in reverse.

See ColumnOperators.__truediv__().

__setattr__
inherited from the __setattr__ attribute of object

x.__setattr__(‘name’, value) <==> x.name = value

__sizeof__() → int
inherited from the __sizeof__() method of object

size of object in memory, in bytes

__str__
inherited from the __str__ attribute of object

x.__str__() <==> str(x)

__sub__(other)

Implement the - operator.

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

static __subclasshook__()
inherited from the __subclasshook__() method of object

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

__truediv__(other)

Implement the // operator.

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

__weakref__
inherited from the __weakref__ attribute of Operators

list of weak references to the object (if defined)

asc()

Produce a asc() clause against the parent object.

between(cleft, cright)

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

collate(collation)

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

concat(other)

Implement the ‘concat’ operator.

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

contains(other, **kwargs)

Implement the ‘contains’ operator.

In a column context, produces the clause LIKE '%<other>%'

desc()

Produce a desc() clause against the parent object.

distinct()

Produce a distinct() clause against the parent object.

endswith(other, **kwargs)

Implement the ‘endswith’ operator.

In a column context, produces the clause LIKE '%<other>'

ilike(other, escape=None)

Implement the ilike operator.

In a column context, produces the clause a ILIKE other.

E.g.:

select([sometable]).where(sometable.c.column.ilike("%foobar%"))
Parameters:
  • other – expression to be compared
  • escape

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

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

Implement the in operator.

In a column context, produces the clause a IN other. “other” may be a tuple/list of column expressions, or a select() construct.

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

New in version 0.7.9.

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

New in version 0.7.9.

like(other, escape=None)

Implement the like operator.

In a column context, produces the clause a LIKE other.

E.g.:

select([sometable]).where(sometable.c.column.like("%foobar%"))
Parameters:
  • other – expression to be compared
  • escape

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

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

Implements the ‘match’ operator.

In a column context, this produces a MATCH clause, i.e. MATCH '<other>'. The allowed contents of other are database backend specific.

notilike(other, escape=None)

implement the NOT ILIKE operator.

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

New in version 0.8.

notin_(other)

implement the NOT IN operator.

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

New in version 0.8.

notlike(other, escape=None)

implement the NOT LIKE operator.

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

New in version 0.8.

nullsfirst()

Produce a nullsfirst() clause against the parent object.

nullslast()

Produce a nullslast() clause against the parent object.

op(opstring, precedence=0)
inherited from the op() method of Operators

produce a generic operator function.

e.g.:

somecolumn.op("*")(5)

produces:

somecolumn * 5

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

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

is a bitwise AND of the value in somecolumn.

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

    precedence to apply to the operator, when parenthesizing expressions. 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.

    New in version 0.8: - added the ‘precedence’ argument.

operate(op, *other, **kwargs)
inherited from the operate() method of 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 ColumnOperators to apply func.lower() to the left and right side:

class MyComparator(ColumnOperators):
    def operate(self, op, other):
        return op(func.lower(self), func.lower(other))
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().
reverse_operate(op, other, **kwargs)
inherited from the reverse_operate() method of Operators

Reverse operate on an argument.

Usage is the same as operate().

startswith(other, **kwargs)

Implement the startwith operator.

In a column context, produces the clause LIKE '<other>%'

timetuple = None

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

class sqlalchemy.sql.expression.CompoundSelect(keyword, *selects, **kwargs)

Bases: sqlalchemy.sql.expression.SelectBase

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

alias(name=None)
inherited from the alias() method of FromClause

return an alias of this FromClause.

This is shorthand for calling:

from sqlalchemy import alias
a = alias(self, name=name)

See alias() for details.

append_group_by(*clauses)
inherited from the append_group_by() method of SelectBase

Append the given GROUP BY criterion applied to this selectable.

The criterion will be appended to any pre-existing GROUP BY criterion.

This is an in-place mutation method; the group_by() method is preferred, as it provides standard method chaining.

append_order_by(*clauses)
inherited from the append_order_by() method of SelectBase

Append the given ORDER BY criterion applied to this selectable.

The criterion will be appended to any pre-existing ORDER BY criterion.

This is an in-place mutation method; the order_by() method is preferred, as it provides standard method chaining.

apply_labels()
inherited from the apply_labels() method of SelectBase

return a new selectable with the ‘use_labels’ flag set to True.

This will result in column expressions being generated using labels against their table name, such as “SELECT somecolumn AS tablename_somecolumn”. This allows selectables which contain multiple FROM clauses to produce a unique set of column names regardless of name conflicts among the individual FROM clauses.

as_scalar()
inherited from the as_scalar() method of SelectBase

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

Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression.

The returned object is an instance of ScalarSelect.

autocommit()
inherited from the autocommit() method of SelectBase

return a new selectable with the ‘autocommit’ flag set to

Deprecated since version 0.6: autocommit() is deprecated. Use Executable.execution_options() with the ‘autocommit’ flag.

True.

c
inherited from the c attribute of FromClause

An alias for the columns attribute.

columns
inherited from the columns attribute of FromClause

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

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

select([mytable]).where(mytable.c.somecolumn == 5)
compare(other, **kw)
inherited from the compare() method of ClauseElement

Compare this ClauseElement 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 ColumnElement)

compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
correspond_on_equivalents(column, equivalents)
inherited from the correspond_on_equivalents() method of FromClause

Return corresponding_column for the given column, or if None search for a match in the given dictionary.

corresponding_column(column, require_embedded=False)
inherited from the corresponding_column() method of FromClause

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

Parameters:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for

the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.

count(whereclause=None, **params)
inherited from the count() method of FromClause

return a SELECT COUNT generated against this FromClause.

cte(name=None, recursive=False)
inherited from the cte() method of SelectBase

Return a new CTE, or Common Table Expression instance.

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

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

New in version 0.7.6.

Parameters:
  • name – name given to the common table expression. Like _FromClause.alias(), the name can be left as None in which case an anonymous symbol will be used at query compile time.
  • recursive – if True, will render WITH RECURSIVE. A recursive common table expression is intended to be used in conjunction with UNION ALL in order to derive rows from those already selected.

The following examples illustrate two examples from Postgresql’s documentation at http://www.postgresql.org/docs/8.4/static/queries-with.html.

Example 1, non recursive:

from sqlalchemy import Table, Column, String, Integer, MetaData, \
    select, func

metadata = MetaData()

orders = Table('orders', metadata,
    Column('region', String),
    Column('amount', Integer),
    Column('product', String),
    Column('quantity', Integer)
)

regional_sales = select([
                    orders.c.region,
                    func.sum(orders.c.amount).label('total_sales')
                ]).group_by(orders.c.region).cte("regional_sales")


top_regions = select([regional_sales.c.region]).\
        where(
            regional_sales.c.total_sales >
            select([
                func.sum(regional_sales.c.total_sales)/10
            ])
        ).cte("top_regions")

statement = select([
            orders.c.region,
            orders.c.product,
            func.sum(orders.c.quantity).label("product_units"),
            func.sum(orders.c.amount).label("product_sales")
    ]).where(orders.c.region.in_(
        select([top_regions.c.region])
    )).group_by(orders.c.region, orders.c.product)

result = conn.execute(statement).fetchall()

Example 2, WITH RECURSIVE:

from sqlalchemy import Table, Column, String, Integer, MetaData, \
    select, func

metadata = MetaData()

parts = Table('parts', metadata,
    Column('part', String),
    Column('sub_part', String),
    Column('quantity', Integer),
)

included_parts = select([
                    parts.c.sub_part,
                    parts.c.part,
                    parts.c.quantity]).\
                    where(parts.c.part=='our part').\
                    cte(recursive=True)


incl_alias = included_parts.alias()
parts_alias = parts.alias()
included_parts = included_parts.union_all(
    select([
        parts_alias.c.part,
        parts_alias.c.sub_part,
        parts_alias.c.quantity
    ]).
        where(parts_alias.c.part==incl_alias.c.sub_part)
)

statement = select([
            included_parts.c.sub_part,
            func.sum(included_parts.c.quantity).
              label('total_quantity')
        ]).                    select_from(included_parts.join(parts,
                    included_parts.c.part==parts.c.part)).\
        group_by(included_parts.c.sub_part)

result = conn.execute(statement).fetchall()

See also

orm.query.Query.cte() - ORM version of SelectBase.cte().

description
inherited from the description attribute of FromClause

a brief description of this FromClause.

Used primarily for error message formatting.

execute(*multiparams, **params)
inherited from the execute() method of Executable

Compile and execute this Executable.

execution_options(**kw)
inherited from the execution_options() method of Executable

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

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

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

statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)

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

foreign_keys
inherited from the foreign_keys attribute of FromClause

Return the collection of ForeignKey objects which this FromClause references.

group_by(*clauses)
inherited from the group_by() method of SelectBase

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

The criterion will be appended to any pre-existing GROUP BY criterion.

join(right, onclause=None, isouter=False)
inherited from the join() method of FromClause

return a join of this FromClause against another FromClause.

label(name)
inherited from the label() method of SelectBase

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

See also

as_scalar().

limit(limit)
inherited from the limit() method of SelectBase

return a new selectable with the given LIMIT criterion applied.

offset(offset)
inherited from the offset() method of SelectBase

return a new selectable with the given OFFSET criterion applied.

order_by(*clauses)
inherited from the order_by() method of SelectBase

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

The criterion will be appended to any pre-existing ORDER BY criterion.

outerjoin(right, onclause=None)
inherited from the outerjoin() method of FromClause

return an outer join of this FromClause against another FromClause.

params(*optionaldict, **kwargs)
inherited from the params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
primary_key
inherited from the primary_key attribute of FromClause

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

replace_selectable(old, alias)
inherited from the replace_selectable() method of FromClause

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

scalar(*multiparams, **params)
inherited from the scalar() method of Executable

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

select(whereclause=None, **params)
inherited from the select() method of FromClause

return a SELECT of this FromClause.

See also

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

unique_params(*optionaldict, **kwargs)
inherited from the unique_params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

class sqlalchemy.sql.operators.custom_op(opstring, precedence=0)

Represent a ‘custom’ operator.

custom_op is normally instantitated when the ColumnOperators.op() method is 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:

from sqlalchemy.sql import UnaryExpression
from sqlalchemy.sql import operators
from sqlalchemy import Numeric

unary = UnaryExpression(table.c.somecolumn,
        modifier=operators.custom_op("!"),
        type_=Numeric)
class sqlalchemy.sql.expression.CTE(selectable, name=None, recursive=False, cte_alias=False, _restates=frozenset([]))

Bases: sqlalchemy.sql.expression.Alias

Represent a Common Table Expression.

The CTE object is obtained using the SelectBase.cte() method from any selectable. See that method for complete examples.

New in version 0.7.6.

c
inherited from the c attribute of FromClause

An alias for the columns attribute.

columns
inherited from the columns attribute of FromClause

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

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

select([mytable]).where(mytable.c.somecolumn == 5)
compare(other, **kw)
inherited from the compare() method of ClauseElement

Compare this ClauseElement 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 ColumnElement)

compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
correspond_on_equivalents(column, equivalents)
inherited from the correspond_on_equivalents() method of FromClause

Return corresponding_column for the given column, or if None search for a match in the given dictionary.

corresponding_column(column, require_embedded=False)
inherited from the corresponding_column() method of FromClause

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

Parameters:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for

the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.

count(whereclause=None, **params)
inherited from the count() method of FromClause

return a SELECT COUNT generated against this FromClause.

foreign_keys
inherited from the foreign_keys attribute of FromClause

Return the collection of ForeignKey objects which this FromClause references.

join(right, onclause=None, isouter=False)
inherited from the join() method of FromClause

return a join of this FromClause against another FromClause.

outerjoin(right, onclause=None)
inherited from the outerjoin() method of FromClause

return an outer join of this FromClause against another FromClause.

params(*optionaldict, **kwargs)
inherited from the params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
primary_key
inherited from the primary_key attribute of FromClause

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

replace_selectable(old, alias)
inherited from the replace_selectable() method of FromClause

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

select(whereclause=None, **params)
inherited from the select() method of FromClause

return a SELECT of this FromClause.

See also

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

self_group(against=None)
inherited from the self_group() method of ClauseElement

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 select() constructs when placed into the FROM clause of another select(). (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 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 self_group() method of ClauseElement just returns self.

unique_params(*optionaldict, **kwargs)
inherited from the unique_params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

class sqlalchemy.sql.expression.Delete(table, whereclause, bind=None, returning=None, prefixes=None, **kwargs)

Bases: sqlalchemy.sql.expression.UpdateBase

Represent a DELETE construct.

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

bind
inherited from the bind attribute of UpdateBase

Return a ‘bind’ linked to this UpdateBase or a Table associated with it.

compare(other, **kw)
inherited from the compare() method of ClauseElement

Compare this ClauseElement 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 ColumnElement)

compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
execute(*multiparams, **params)
inherited from the execute() method of Executable

Compile and execute this Executable.

execution_options(**kw)
inherited from the execution_options() method of Executable

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

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

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

statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)

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

params(*arg, **kw)
inherited from the params() method of UpdateBase

Set the parameters for the statement.

This method raises NotImplementedError on the base class, and is overridden by ValuesBase to provide the SET/VALUES clause of UPDATE and INSERT.

prefix_with(*expr, **kw)
inherited from the prefix_with() method of HasPrefixes

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

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

E.g.:

stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")

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

Parameters:
  • *expr – textual or ClauseElement construct which will be rendered following the INSERT, UPDATE, or DELETE keyword.
  • **kw – A single keyword ‘dialect’ is accepted. This is an optional string dialect name which will limit rendering of this prefix to only that dialect.
returning(*cols)
inherited from the returning() method of UpdateBase

Add a RETURNING or equivalent clause to this statement.

The given list of columns represent columns within the table that is the target of the INSERT, UPDATE, or DELETE. Each element can be any column expression. Table objects will be expanded into their individual columns.

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

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

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

scalar(*multiparams, **params)
inherited from the scalar() method of Executable

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

self_group(against=None)
inherited from the self_group() method of ClauseElement

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 select() constructs when placed into the FROM clause of another select(). (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 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 self_group() method of ClauseElement just returns self.

unique_params(*optionaldict, **kwargs)
inherited from the unique_params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

where(whereclause)

Add the given WHERE clause to a newly returned delete construct.

with_hint(text, selectable=None, dialect_name='*')
inherited from the with_hint() method of UpdateBase

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

Note

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

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

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

mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql")

New in version 0.7.6.

Parameters:
  • text – Text of the hint.
  • selectable – optional Table that specifies an element of the FROM clause within an UPDATE or DELETE to be the subject of the hint - applies only to certain backends.
  • dialect_name – defaults to *, if specified as the name of a particular dialect, will apply these hints only when that dialect is in use.
class sqlalchemy.sql.expression.Executable

Bases: sqlalchemy.sql.expression.Generative

Mark a ClauseElement as supporting execution.

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

bind

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

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

execute(*multiparams, **params)

Compile and execute this Executable.

execution_options(**kw)

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

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

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

statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)

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

scalar(*multiparams, **params)

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

class sqlalchemy.sql.expression.FunctionElement(*clauses, **kwargs)

Bases: sqlalchemy.sql.expression.Executable, sqlalchemy.sql.expression.ColumnElement, sqlalchemy.sql.expression.FromClause

Base for SQL function-oriented constructs.

See also

Function - named SQL function.

func - namespace which produces registered or ad-hoc Function instances.

GenericFunction - allows creation of registered function types.

__eq__(other)
inherited from the __eq__() method of ColumnOperators

Implement the == operator.

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

__init__(*clauses, **kwargs)

Construct a FunctionElement.

__le__(other)
inherited from the __le__() method of ColumnOperators

Implement the <= operator.

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

__lt__(other)
inherited from the __lt__() method of ColumnOperators

Implement the < operator.

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

__ne__(other)
inherited from the __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.

alias(name=None)
inherited from the alias() method of FromClause

return an alias of this FromClause.

This is shorthand for calling:

from sqlalchemy import alias
a = alias(self, name=name)

See alias() for details.

anon_label
inherited from the anon_label attribute of ColumnElement

provides a constant ‘anonymous label’ for this ColumnElement.

This is a label() expression which will be named at compile time. The same label() is returned each time anon_label is called so that expressions can reference anon_label multiple times, producing the same label name at compile time.

the compiler uses this function automatically at compile time for expressions that are known to be ‘unnamed’ like binary expressions and function calls.

asc()
inherited from the asc() method of ColumnOperators

Produce a asc() clause against the parent object.

between(cleft, cright)
inherited from the between() method of ColumnOperators

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

bind
inherited from the bind attribute of Executable

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

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

c
inherited from the c attribute of FromClause

An alias for the columns attribute.

clauses

Return the underlying ClauseList which contains the arguments for this FunctionElement.

collate(collation)
inherited from the collate() method of ColumnOperators

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

columns

Fulfill the ‘columns’ contract of ColumnElement.

Returns a single-element list consisting of this object.

compare(other, use_proxies=False, equivalents=None, **kw)
inherited from the compare() method of ColumnElement

Compare this ColumnElement to another.

Special arguments understood:

Parameters:
  • use_proxies – when True, consider two columns that share a common base column as equivalent (i.e. shares_lineage())
  • equivalents – a dictionary of columns as keys mapped to sets of columns. If the given “other” column is present in this dictionary, if any of the columns in the corresponding set() pass the comparison test, the result is True. This is used to expand the comparison to other columns that may be known to be equivalent to this one via foreign key or other criterion.
compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
concat(other)
inherited from the concat() method of ColumnOperators

Implement the ‘concat’ operator.

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

contains(other, **kwargs)
inherited from the contains() method of ColumnOperators

Implement the ‘contains’ operator.

In a column context, produces the clause LIKE '%<other>%'

correspond_on_equivalents(column, equivalents)
inherited from the correspond_on_equivalents() method of FromClause

Return corresponding_column for the given column, or if None search for a match in the given dictionary.

corresponding_column(column, require_embedded=False)
inherited from the corresponding_column() method of FromClause

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

Parameters:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for

the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.

count(whereclause=None, **params)
inherited from the count() method of FromClause

return a SELECT COUNT generated against this FromClause.

desc()
inherited from the desc() method of ColumnOperators

Produce a desc() clause against the parent object.

description
inherited from the description attribute of FromClause

a brief description of this FromClause.

Used primarily for error message formatting.

distinct()
inherited from the distinct() method of ColumnOperators

Produce a distinct() clause against the parent object.

endswith(other, **kwargs)
inherited from the endswith() method of ColumnOperators

Implement the ‘endswith’ operator.

In a column context, produces the clause LIKE '%<other>'

execute()

Execute this FunctionElement against an embedded ‘bind’.

This first calls select() to produce a SELECT construct.

Note that FunctionElement can be passed to the Connectable.execute() method of Connection or Engine.

execution_options(**kw)
inherited from the execution_options() method of Executable

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

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

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

statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)

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

expression
inherited from the expression attribute of ColumnElement

Return a column expression.

Part of the inspection interface; returns self.

ilike(other, escape=None)
inherited from the ilike() method of ColumnOperators

Implement the ilike operator.

In a column context, produces the clause a ILIKE other.

E.g.:

select([sometable]).where(sometable.c.column.ilike("%foobar%"))
Parameters:
  • other – expression to be compared
  • escape

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

    somecolumn.ilike("foo/%bar", escape="/")
in_(other)
inherited from the in_() method of ColumnOperators

Implement the in operator.

In a column context, produces the clause a IN other. “other” may be a tuple/list of column expressions, or a select() construct.

is_(other)
inherited from the is_() method of ColumnOperators

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.

New in version 0.7.9.

is_derived_from(fromclause)
inherited from the is_derived_from() method of FromClause

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

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

isnot(other)
inherited from the isnot() 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.

New in version 0.7.9.

join(right, onclause=None, isouter=False)
inherited from the join() method of FromClause

return a join of this FromClause against another FromClause.

label(name)
inherited from the label() method of ColumnElement

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

This is a shortcut to the label() function.

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

like(other, escape=None)
inherited from the like() method of ColumnOperators

Implement the like operator.

In a column context, produces the clause a LIKE other.

E.g.:

select([sometable]).where(sometable.c.column.like("%foobar%"))
Parameters:
  • other – expression to be compared
  • escape

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

    somecolumn.like("foo/%bar", escape="/")
match(other, **kwargs)
inherited from the match() method of ColumnOperators

Implements the ‘match’ operator.

In a column context, this produces a MATCH clause, i.e. MATCH '<other>'. The allowed contents of other are database backend specific.

notilike(other, escape=None)
inherited from the notilike() method of ColumnOperators

implement the NOT ILIKE operator.

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

New in version 0.8.

notin_(other)
inherited from the notin_() method of ColumnOperators

implement the NOT IN operator.

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

New in version 0.8.

notlike(other, escape=None)
inherited from the notlike() method of ColumnOperators

implement the NOT LIKE operator.

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

New in version 0.8.

nullsfirst()
inherited from the nullsfirst() method of ColumnOperators

Produce a nullsfirst() clause against the parent object.

nullslast()
inherited from the nullslast() method of ColumnOperators

Produce a nullslast() clause against the parent object.

op(opstring, precedence=0)
inherited from the op() method of Operators

produce a generic operator function.

e.g.:

somecolumn.op("*")(5)

produces:

somecolumn * 5

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

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

is a bitwise AND of the value in somecolumn.

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

    precedence to apply to the operator, when parenthesizing expressions. 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.

    New in version 0.8: - added the ‘precedence’ argument.

outerjoin(right, onclause=None)
inherited from the outerjoin() method of FromClause

return an outer join of this FromClause against another FromClause.

over(partition_by=None, order_by=None)

Produce an OVER clause against this function.

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

The expression:

func.row_number().over(order_by='x')

is shorthand for:

from sqlalchemy import over
over(func.row_number(), order_by='x')

See over() for a full description.

New in version 0.7.

params(*optionaldict, **kwargs)
inherited from the params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
replace_selectable(old, alias)
inherited from the replace_selectable() method of FromClause

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

scalar()

Execute this FunctionElement against an embedded ‘bind’ and return a scalar value.

This first calls select() to produce a SELECT construct.

Note that FunctionElement can be passed to the Connectable.scalar() method of Connection or Engine.

select()

Produce a select() construct against this FunctionElement.

This is shorthand for:

s = select([function_element])
self_group(against=None)
inherited from the self_group() method of ClauseElement

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 select() constructs when placed into the FROM clause of another select(). (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 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 self_group() method of ClauseElement just returns self.

shares_lineage(othercolumn)
inherited from the shares_lineage() method of ColumnElement

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

startswith(other, **kwargs)
inherited from the startswith() method of ColumnOperators

Implement the startwith operator.

In a column context, produces the clause LIKE '<other>%'

unique_params(*optionaldict, **kwargs)
inherited from the unique_params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

class sqlalchemy.sql.expression.Function(name, *clauses, **kw)

Bases: sqlalchemy.sql.expression.FunctionElement

Describe a named SQL function.

See the superclass FunctionElement for a description of public methods.

See also

func - namespace which produces registered or ad-hoc Function instances.

GenericFunction - allows creation of registered function types.

__eq__(other)
inherited from the __eq__() method of ColumnOperators

Implement the == operator.

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

__init__(name, *clauses, **kw)

Construct a Function.

The func construct is normally used to construct new Function instances.

__le__(other)
inherited from the __le__() method of ColumnOperators

Implement the <= operator.

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

__lt__(other)
inherited from the __lt__() method of ColumnOperators

Implement the < operator.

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

__ne__(other)
inherited from the __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.

alias(name=None)
inherited from the alias() method of FromClause

return an alias of this FromClause.

This is shorthand for calling:

from sqlalchemy import alias
a = alias(self, name=name)

See alias() for details.

anon_label
inherited from the anon_label attribute of ColumnElement

provides a constant ‘anonymous label’ for this ColumnElement.

This is a label() expression which will be named at compile time. The same label() is returned each time anon_label is called so that expressions can reference anon_label multiple times, producing the same label name at compile time.

the compiler uses this function automatically at compile time for expressions that are known to be ‘unnamed’ like binary expressions and function calls.

asc()
inherited from the asc() method of ColumnOperators

Produce a asc() clause against the parent object.

between(cleft, cright)
inherited from the between() method of ColumnOperators

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

bind
inherited from the bind attribute of Executable

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

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

c
inherited from the c attribute of FromClause

An alias for the columns attribute.

clauses
inherited from the clauses attribute of FunctionElement

Return the underlying ClauseList which contains the arguments for this FunctionElement.

collate(collation)
inherited from the collate() method of ColumnOperators

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

columns
inherited from the columns attribute of FunctionElement

Fulfill the ‘columns’ contract of ColumnElement.

Returns a single-element list consisting of this object.

compare(other, use_proxies=False, equivalents=None, **kw)
inherited from the compare() method of ColumnElement

Compare this ColumnElement to another.

Special arguments understood:

Parameters:
  • use_proxies – when True, consider two columns that share a common base column as equivalent (i.e. shares_lineage())
  • equivalents – a dictionary of columns as keys mapped to sets of columns. If the given “other” column is present in this dictionary, if any of the columns in the corresponding set() pass the comparison test, the result is True. This is used to expand the comparison to other columns that may be known to be equivalent to this one via foreign key or other criterion.
compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
concat(other)
inherited from the concat() method of ColumnOperators

Implement the ‘concat’ operator.

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

contains(other, **kwargs)
inherited from the contains() method of ColumnOperators

Implement the ‘contains’ operator.

In a column context, produces the clause LIKE '%<other>%'

correspond_on_equivalents(column, equivalents)
inherited from the correspond_on_equivalents() method of FromClause

Return corresponding_column for the given column, or if None search for a match in the given dictionary.

corresponding_column(column, require_embedded=False)
inherited from the corresponding_column() method of FromClause

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

Parameters:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for

the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.

count(whereclause=None, **params)
inherited from the count() method of FromClause

return a SELECT COUNT generated against this FromClause.

desc()
inherited from the desc() method of ColumnOperators

Produce a desc() clause against the parent object.

description
inherited from the description attribute of FromClause

a brief description of this FromClause.

Used primarily for error message formatting.

distinct()
inherited from the distinct() method of ColumnOperators

Produce a distinct() clause against the parent object.

endswith(other, **kwargs)
inherited from the endswith() method of ColumnOperators

Implement the ‘endswith’ operator.

In a column context, produces the clause LIKE '%<other>'

execute()
inherited from the execute() method of FunctionElement

Execute this FunctionElement against an embedded ‘bind’.

This first calls select() to produce a SELECT construct.

Note that FunctionElement can be passed to the Connectable.execute() method of Connection or Engine.

execution_options(**kw)
inherited from the execution_options() method of Executable

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

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

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

statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)

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

expression
inherited from the expression attribute of ColumnElement

Return a column expression.

Part of the inspection interface; returns self.

ilike(other, escape=None)
inherited from the ilike() method of ColumnOperators

Implement the ilike operator.

In a column context, produces the clause a ILIKE other.

E.g.:

select([sometable]).where(sometable.c.column.ilike("%foobar%"))
Parameters:
  • other – expression to be compared
  • escape

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

    somecolumn.ilike("foo/%bar", escape="/")
in_(other)
inherited from the in_() method of ColumnOperators

Implement the in operator.

In a column context, produces the clause a IN other. “other” may be a tuple/list of column expressions, or a select() construct.

is_(other)
inherited from the is_() method of ColumnOperators

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.

New in version 0.7.9.

is_derived_from(fromclause)
inherited from the is_derived_from() method of FromClause

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

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

isnot(other)
inherited from the isnot() 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.

New in version 0.7.9.

join(right, onclause=None, isouter=False)
inherited from the join() method of FromClause

return a join of this FromClause against another FromClause.

label(name)
inherited from the label() method of ColumnElement

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

This is a shortcut to the label() function.

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

like(other, escape=None)
inherited from the like() method of ColumnOperators

Implement the like operator.

In a column context, produces the clause a LIKE other.

E.g.:

select([sometable]).where(sometable.c.column.like("%foobar%"))
Parameters:
  • other – expression to be compared
  • escape

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

    somecolumn.like("foo/%bar", escape="/")
match(other, **kwargs)
inherited from the match() method of ColumnOperators

Implements the ‘match’ operator.

In a column context, this produces a MATCH clause, i.e. MATCH '<other>'. The allowed contents of other are database backend specific.

notilike(other, escape=None)
inherited from the notilike() method of ColumnOperators

implement the NOT ILIKE operator.

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

New in version 0.8.

notin_(other)
inherited from the notin_() method of ColumnOperators

implement the NOT IN operator.

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

New in version 0.8.

notlike(other, escape=None)
inherited from the notlike() method of ColumnOperators

implement the NOT LIKE operator.

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

New in version 0.8.

nullsfirst()
inherited from the nullsfirst() method of ColumnOperators

Produce a nullsfirst() clause against the parent object.

nullslast()
inherited from the nullslast() method of ColumnOperators

Produce a nullslast() clause against the parent object.

op(opstring, precedence=0)
inherited from the op() method of Operators

produce a generic operator function.

e.g.:

somecolumn.op("*")(5)

produces:

somecolumn * 5

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

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

is a bitwise AND of the value in somecolumn.

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

    precedence to apply to the operator, when parenthesizing expressions. 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.

    New in version 0.8: - added the ‘precedence’ argument.

outerjoin(right, onclause=None)
inherited from the outerjoin() method of FromClause

return an outer join of this FromClause against another FromClause.

over(partition_by=None, order_by=None)
inherited from the over() method of FunctionElement

Produce an OVER clause against this function.

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

The expression:

func.row_number().over(order_by='x')

is shorthand for:

from sqlalchemy import over
over(func.row_number(), order_by='x')

See over() for a full description.

New in version 0.7.

params(*optionaldict, **kwargs)
inherited from the params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
replace_selectable(old, alias)
inherited from the replace_selectable() method of FromClause

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

scalar()
inherited from the scalar() method of FunctionElement

Execute this FunctionElement against an embedded ‘bind’ and return a scalar value.

This first calls select() to produce a SELECT construct.

Note that FunctionElement can be passed to the Connectable.scalar() method of Connection or Engine.

select()
inherited from the select() method of FunctionElement

Produce a select() construct against this FunctionElement.

This is shorthand for:

s = select([function_element])
self_group(against=None)
inherited from the self_group() method of ClauseElement

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 select() constructs when placed into the FROM clause of another select(). (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 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 self_group() method of ClauseElement just returns self.

shares_lineage(othercolumn)
inherited from the shares_lineage() method of ColumnElement

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

startswith(other, **kwargs)
inherited from the startswith() method of ColumnOperators

Implement the startwith operator.

In a column context, produces the clause LIKE '<other>%'

unique_params(*optionaldict, **kwargs)
inherited from the unique_params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

class sqlalchemy.sql.expression.FromClause

Bases: sqlalchemy.sql.expression.Selectable

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

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

alias(name=None)

return an alias of this FromClause.

This is shorthand for calling:

from sqlalchemy import alias
a = alias(self, name=name)

See alias() for details.

c

An alias for the columns attribute.

columns

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

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

select([mytable]).where(mytable.c.somecolumn == 5)
correspond_on_equivalents(column, equivalents)

Return corresponding_column for the given column, or if None search for a match in the given dictionary.

corresponding_column(column, require_embedded=False)

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

Parameters:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for

the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.

count(whereclause=None, **params)

return a SELECT COUNT generated against this FromClause.

description

a brief description of this FromClause.

Used primarily for error message formatting.

foreign_keys

Return the collection of ForeignKey objects which this FromClause references.

is_derived_from(fromclause)

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

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

join(right, onclause=None, isouter=False)

return a join of this FromClause against another FromClause.

outerjoin(right, onclause=None)

return an outer join of this FromClause against another FromClause.

primary_key

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

replace_selectable(old, alias)

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

select(whereclause=None, **params)

return a SELECT of this FromClause.

See also

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

class sqlalchemy.sql.expression.Insert(table, values=None, inline=False, bind=None, prefixes=None, returning=None, **kwargs)

Bases: sqlalchemy.sql.expression.ValuesBase

Represent an INSERT construct.

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

bind
inherited from the bind attribute of UpdateBase

Return a ‘bind’ linked to this UpdateBase or a Table associated with it.

compare(other, **kw)
inherited from the compare() method of ClauseElement

Compare this ClauseElement 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 ColumnElement)

compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
execute(*multiparams, **params)
inherited from the execute() method of Executable

Compile and execute this Executable.

execution_options(**kw)
inherited from the execution_options() method of Executable

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

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

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

statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)

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

params(*arg, **kw)
inherited from the params() method of UpdateBase

Set the parameters for the statement.

This method raises NotImplementedError on the base class, and is overridden by ValuesBase to provide the SET/VALUES clause of UPDATE and INSERT.

prefix_with(*expr, **kw)
inherited from the prefix_with() method of HasPrefixes

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

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

E.g.:

stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")

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

Parameters:
  • *expr – textual or ClauseElement construct which will be rendered following the INSERT, UPDATE, or DELETE keyword.
  • **kw – A single keyword ‘dialect’ is accepted. This is an optional string dialect name which will limit rendering of this prefix to only that dialect.
returning(*cols)
inherited from the returning() method of UpdateBase

Add a RETURNING or equivalent clause to this statement.

The given list of columns represent columns within the table that is the target of the INSERT, UPDATE, or DELETE. Each element can be any column expression. Table objects will be expanded into their individual columns.

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

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

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

scalar(*multiparams, **params)
inherited from the scalar() method of Executable

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

self_group(against=None)
inherited from the self_group() method of ClauseElement

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 select() constructs when placed into the FROM clause of another select(). (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 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 self_group() method of ClauseElement just returns self.

unique_params(*optionaldict, **kwargs)
inherited from the unique_params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

values(*args, **kwargs)
inherited from the values() method of ValuesBase

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

Note that the Insert and Update constructs support per-execution time formatting of the VALUES and/or SET clauses, based on the arguments passed to Connection.execute(). However, the ValuesBase.values() method can be used to “fix” a particular set of parameters into the statement.

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

Parameters:
  • **kwargs

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

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

    Alternatively, a dictionary, tuple or list of dictionaries or tuples can be passed as a single positional argument in order to form the VALUES or SET clause of the statement. The single dictionary form works the same as the kwargs form:

    users.insert().values({"name": "some name"})

    If a tuple is passed, the tuple should contain the same number of columns as the target Table:

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

    The Insert construct also supports multiply-rendered VALUES construct, for those backends which support this SQL syntax (SQLite, Postgresql, MySQL). This mode is indicated by passing a list of one or more dictionaries/tuples:

    users.insert().values([
                        {"name": "some name"},
                        {"name": "some other name"},
                        {"name": "yet another name"},
                    ])

    In the case of an Update construct, only the single dictionary/tuple form is accepted, else an exception is raised. It is also an exception case to attempt to mix the single-/multiple- value styles together, either through multiple ValuesBase.values() calls or by sending a list + kwargs at the same time.

    Note

    Passing a multiple values list is not the same as passing a multiple values list to the Connection.execute() method. Passing a list of parameter sets to ValuesBase.values() produces a construct of this form:

    INSERT INTO table (col1, col2, col3) VALUES
                    (col1_0, col2_0, col3_0),
                    (col1_1, col2_1, col3_1),
                    ...

    whereas a multiple list passed to Connection.execute() has the effect of using the DBAPI executemany() method, which provides a high-performance system of invoking a single-row INSERT statement many times against a series of parameter sets. The “executemany” style is supported by all database backends, as it does not depend on a special SQL syntax.

    New in version 0.8: Support for multiple-VALUES INSERT statements.

See also

Inserts, Updates and Deletes - SQL Expression Language Tutorial

insert() - produce an INSERT statement

update() - produce an UPDATE statement

with_hint(text, selectable=None, dialect_name='*')
inherited from the with_hint() method of UpdateBase

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

Note

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

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

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

mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql")

New in version 0.7.6.

Parameters:
  • text – Text of the hint.
  • selectable – optional Table that specifies an element of the FROM clause within an UPDATE or DELETE to be the subject of the hint - applies only to certain backends.
  • dialect_name – defaults to *, if specified as the name of a particular dialect, will apply these hints only when that dialect is in use.
class sqlalchemy.sql.expression.Join(left, right, onclause=None, isouter=False)

Bases: sqlalchemy.sql.expression.FromClause

represent a JOIN construct between two FromClause elements.

The public constructor function for Join is the module-level join() function, as well as the join() method available off all FromClause subclasses.

__init__(left, right, onclause=None, isouter=False)

Construct a new Join.

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

alias(name=None)

return an alias of this Join.

Used against a Join object, alias() calls the select() method first so that a subquery against a select() construct is generated. the select() construct also has the correlate flag set to False and will not auto-correlate inside an enclosing select() construct.

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

from sqlalchemy import select, alias
j = alias(
    select([j.left, j.right]).\
        select_from(j).\
        with_labels(True).\
        correlate(False),
    name=name
)

See alias() for further details on aliases.

c
inherited from the c attribute of FromClause

An alias for the columns attribute.

columns
inherited from the columns attribute of FromClause

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

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

select([mytable]).where(mytable.c.somecolumn == 5)
compare(other, **kw)
inherited from the compare() method of ClauseElement

Compare this ClauseElement 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 ColumnElement)

compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
correspond_on_equivalents(column, equivalents)
inherited from the correspond_on_equivalents() method of FromClause

Return corresponding_column for the given column, or if None search for a match in the given dictionary.

corresponding_column(column, require_embedded=False)
inherited from the corresponding_column() method of FromClause

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

Parameters:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for

the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.

count(whereclause=None, **params)
inherited from the count() method of FromClause

return a SELECT COUNT generated against this FromClause.

foreign_keys
inherited from the foreign_keys attribute of FromClause

Return the collection of ForeignKey objects which this FromClause references.

join(right, onclause=None, isouter=False)
inherited from the join() method of FromClause

return a join of this FromClause against another FromClause.

outerjoin(right, onclause=None)
inherited from the outerjoin() method of FromClause

return an outer join of this FromClause against another FromClause.

params(*optionaldict, **kwargs)
inherited from the params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
primary_key
inherited from the primary_key attribute of FromClause

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

replace_selectable(old, alias)
inherited from the replace_selectable() method of FromClause

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

select(whereclause=None, **kwargs)

Create a Select from this Join.

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

from sqlalchemy import select
j = select([j.left, j.right], **kw).\
            where(whereclause).\
            select_from(j)
Parameters:
  • whereclause – the WHERE criterion that will be sent to the select() function
  • **kwargs – all other kwargs are sent to the underlying select() function.
unique_params(*optionaldict, **kwargs)
inherited from the unique_params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

class sqlalchemy.sql.operators.Operators

Base of comparison and logical operators.

Implements base methods operate() and reverse_operate(), as well as __and__(), __or__(), __invert__().

Usually is used via its most common subclass ColumnOperators.

__and__(other)

Implement the & operator.

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

a & b

is equivalent to:

from sqlalchemy import and_
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:

(a == 2) & (b == 4)
__invert__()

Implement the ~ operator.

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

~a

is equivalent to:

from sqlalchemy import not_
not_(a)
__or__(other)

Implement the | operator.

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

a | b

is equivalent to:

from sqlalchemy import or_
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:

(a == 2) | (b == 4)
__weakref__

list of weak references to the object (if defined)

op(opstring, precedence=0)

produce a generic operator function.

e.g.:

somecolumn.op("*")(5)

produces:

somecolumn * 5

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

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

is a bitwise AND of the value in somecolumn.

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

    precedence to apply to the operator, when parenthesizing expressions. 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.

    New in version 0.8: - added the ‘precedence’ argument.

operate(op, *other, **kwargs)

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:

class MyComparator(ColumnOperators):
    def operate(self, op, other):
        return op(func.lower(self), func.lower(other))
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().
reverse_operate(op, other, **kwargs)

Reverse operate on an argument.

Usage is the same as operate().

class sqlalchemy.sql.expression.Select(columns, whereclause=None, from_obj=None, distinct=False, having=None, correlate=True, prefixes=None, **kwargs)

Bases: sqlalchemy.sql.expression.HasPrefixes, sqlalchemy.sql.expression.SelectBase

Represents a SELECT statement.

See also

select() - the function which creates a Select object.

Selecting - Core Tutorial description of select().

__init__(columns, whereclause=None, from_obj=None, distinct=False, having=None, correlate=True, prefixes=None, **kwargs)

Construct a Select object.

The public constructor for Select is the select() function; see that function for argument descriptions.

Additional generative and mutator methods are available on the SelectBase superclass.

alias(name=None)
inherited from the alias() method of FromClause

return an alias of this FromClause.

This is shorthand for calling:

from sqlalchemy import alias
a = alias(self, name=name)

See alias() for details.

append_column(column)

append the given column expression to the columns clause of this select() construct.

This is an in-place mutation method; the column() method is preferred, as it provides standard method chaining.

append_correlation(fromclause)

append the given correlation expression to this select() construct.

This is an in-place mutation method; the correlate() method is preferred, as it provides standard method chaining.

append_from(fromclause)

append the given FromClause expression to this select() construct’s FROM clause.

This is an in-place mutation method; the select_from() method is preferred, as it provides standard method chaining.

append_group_by(*clauses)
inherited from the append_group_by() method of SelectBase

Append the given GROUP BY criterion applied to this selectable.

The criterion will be appended to any pre-existing GROUP BY criterion.

This is an in-place mutation method; the group_by() method is preferred, as it provides standard method chaining.

append_having(having)

append the given expression to this select() construct’s HAVING criterion.

The expression will be joined to existing HAVING criterion via AND.

This is an in-place mutation method; the having() method is preferred, as it provides standard method chaining.

append_order_by(*clauses)
inherited from the append_order_by() method of SelectBase

Append the given ORDER BY criterion applied to this selectable.

The criterion will be appended to any pre-existing ORDER BY criterion.

This is an in-place mutation method; the order_by() method is preferred, as it provides standard method chaining.

append_prefix(clause)

append the given columns clause prefix expression to this select() construct.

This is an in-place mutation method; the prefix_with() method is preferred, as it provides standard method chaining.

append_whereclause(whereclause)

append the given expression to this select() construct’s WHERE criterion.

The expression will be joined to existing WHERE criterion via AND.

This is an in-place mutation method; the where() method is preferred, as it provides standard method chaining.

apply_labels()
inherited from the apply_labels() method of SelectBase

return a new selectable with the ‘use_labels’ flag set to True.

This will result in column expressions being generated using labels against their table name, such as “SELECT somecolumn AS tablename_somecolumn”. This allows selectables which contain multiple FROM clauses to produce a unique set of column names regardless of name conflicts among the individual FROM clauses.

as_scalar()
inherited from the as_scalar() method of SelectBase

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

Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression.

The returned object is an instance of ScalarSelect.

autocommit()
inherited from the autocommit() method of SelectBase

return a new selectable with the ‘autocommit’ flag set to

Deprecated since version 0.6: autocommit() is deprecated. Use Executable.execution_options() with the ‘autocommit’ flag.

True.

c
inherited from the c attribute of FromClause

An alias for the columns attribute.

column(column)

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

columns
inherited from the columns attribute of FromClause

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

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

select([mytable]).where(mytable.c.somecolumn == 5)
compare(other, **kw)
inherited from the compare() method of ClauseElement

Compare this ClauseElement 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 ColumnElement)

compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
correlate(*fromclauses)

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

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

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

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

Parameters:*fromclauses

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

Changed in version 0.8.0: ORM-mapped classes are accepted by Select.correlate().

Changed in version 0.8.0: The Select.correlate() method no longer unconditionally removes entries from the FROM clause; instead, the candidate FROM entries must also be matched by a FROM entry located in an enclosing Select, which ultimately encloses this one as present in the WHERE clause, ORDER BY clause, HAVING clause, or columns clause of an enclosing Select().

Changed in version 0.8.2: explicit correlation takes place via any level of nesting of Select objects; in previous 0.8 versions, correlation would only occur relative to the immediate enclosing Select construct.

correlate_except(*fromclauses)

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

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

Changed in version 0.8.2: The Select.correlate_except() method was improved to fully prevent FROM clauses specified here from being omitted from the immediate FROM clause of this Select.

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

Changed in version 0.8.2: calling correlate_except(None) will correctly auto-correlate all FROM clauses.

Parameters:*fromclauses – a list of one or more FromClause constructs, or other compatible constructs (i.e. ORM-mapped classes) to become part of the correlate-exception collection.
correspond_on_equivalents(column, equivalents)
inherited from the correspond_on_equivalents() method of FromClause

Return corresponding_column for the given column, or if None search for a match in the given dictionary.

corresponding_column(column, require_embedded=False)
inherited from the corresponding_column() method of FromClause

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

Parameters:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for

the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.

count(whereclause=None, **params)
inherited from the count() method of FromClause

return a SELECT COUNT generated against this FromClause.

cte(name=None, recursive=False)
inherited from the cte() method of SelectBase

Return a new CTE, or Common Table Expression instance.

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

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

New in version 0.7.6.

Parameters:
  • name – name given to the common table expression. Like _FromClause.alias(), the name can be left as None in which case an anonymous symbol will be used at query compile time.
  • recursive – if True, will render WITH RECURSIVE. A recursive common table expression is intended to be used in conjunction with UNION ALL in order to derive rows from those already selected.

The following examples illustrate two examples from Postgresql’s documentation at http://www.postgresql.org/docs/8.4/static/queries-with.html.

Example 1, non recursive:

from sqlalchemy import Table, Column, String, Integer, MetaData, \
    select, func

metadata = MetaData()

orders = Table('orders', metadata,
    Column('region', String),
    Column('amount', Integer),
    Column('product', String),
    Column('quantity', Integer)
)

regional_sales = select([
                    orders.c.region,
                    func.sum(orders.c.amount).label('total_sales')
                ]).group_by(orders.c.region).cte("regional_sales")


top_regions = select([regional_sales.c.region]).\
        where(
            regional_sales.c.total_sales >
            select([
                func.sum(regional_sales.c.total_sales)/10
            ])
        ).cte("top_regions")

statement = select([
            orders.c.region,
            orders.c.product,
            func.sum(orders.c.quantity).label("product_units"),
            func.sum(orders.c.amount).label("product_sales")
    ]).where(orders.c.region.in_(
        select([top_regions.c.region])
    )).group_by(orders.c.region, orders.c.product)

result = conn.execute(statement).fetchall()

Example 2, WITH RECURSIVE:

from sqlalchemy import Table, Column, String, Integer, MetaData, \
    select, func

metadata = MetaData()

parts = Table('parts', metadata,
    Column('part', String),
    Column('sub_part', String),
    Column('quantity', Integer),
)

included_parts = select([
                    parts.c.sub_part,
                    parts.c.part,
                    parts.c.quantity]).\
                    where(parts.c.part=='our part').\
                    cte(recursive=True)


incl_alias = included_parts.alias()
parts_alias = parts.alias()
included_parts = included_parts.union_all(
    select([
        parts_alias.c.part,
        parts_alias.c.sub_part,
        parts_alias.c.quantity
    ]).
        where(parts_alias.c.part==incl_alias.c.sub_part)
)

statement = select([
            included_parts.c.sub_part,
            func.sum(included_parts.c.quantity).
              label('total_quantity')
        ]).                    select_from(included_parts.join(parts,
                    included_parts.c.part==parts.c.part)).\
        group_by(included_parts.c.sub_part)

result = conn.execute(statement).fetchall()

See also

orm.query.Query.cte() - ORM version of SelectBase.cte().

description
inherited from the description attribute of FromClause

a brief description of this FromClause.

Used primarily for error message formatting.

distinct(*expr)

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

Parameters:*expr – optional column expressions. When present, the Postgresql dialect will render a DISTINCT ON (<expressions>>) construct.
except_(other, **kwargs)

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

except_all(other, **kwargs)

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

execute(*multiparams, **params)
inherited from the execute() method of Executable

Compile and execute this Executable.

execution_options(**kw)
inherited from the execution_options() method of Executable

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

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

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

statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)

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

foreign_keys
inherited from the foreign_keys attribute of FromClause

Return the collection of ForeignKey objects which this FromClause references.

froms

Return the displayed list of FromClause elements.

get_children(column_collections=True, **kwargs)

return child elements as per the ClauseElement specification.

group_by(*clauses)
inherited from the group_by() method of SelectBase

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

The criterion will be appended to any pre-existing GROUP BY criterion.

having(having)

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

inner_columns

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

intersect(other, **kwargs)

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

intersect_all(other, **kwargs)

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

join(right, onclause=None, isouter=False)
inherited from the join() method of FromClause

return a join of this FromClause against another FromClause.

label(name)
inherited from the label() method of SelectBase

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

See also

as_scalar().

limit(limit)
inherited from the limit() method of SelectBase

return a new selectable with the given LIMIT criterion applied.

locate_all_froms

return a Set of all FromClause elements referenced by this Select.

This set is a superset of that returned by the froms property, which is specifically for those FromClause elements that would actually be rendered.

offset(offset)
inherited from the offset() method of SelectBase

return a new selectable with the given OFFSET criterion applied.

order_by(*clauses)
inherited from the order_by() method of SelectBase

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

The criterion will be appended to any pre-existing ORDER BY criterion.

outerjoin(right, onclause=None)
inherited from the outerjoin() method of FromClause

return an outer join of this FromClause against another FromClause.

params(*optionaldict, **kwargs)
inherited from the params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
prefix_with(*expr, **kw)
inherited from the prefix_with() method of HasPrefixes

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

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

E.g.:

stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")

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

Parameters:
  • *expr – textual or ClauseElement construct which will be rendered following the INSERT, UPDATE, or DELETE keyword.
  • **kw – A single keyword ‘dialect’ is accepted. This is an optional string dialect name which will limit rendering of this prefix to only that dialect.
primary_key
inherited from the primary_key attribute of FromClause

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

reduce_columns(only_synonyms=True)

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

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

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

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

New in version 0.8.

replace_selectable(old, alias)
inherited from the replace_selectable() method of FromClause

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

scalar(*multiparams, **params)
inherited from the scalar() method of Executable

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

select(whereclause=None, **params)
inherited from the select() method of FromClause

return a SELECT of this FromClause.

See also

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

select_from(fromclause)

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

E.g.:

table1 = table('t1', column('a'))
table2 = table('t2', column('b'))
s = select([table1.c.a]).\
    select_from(
        table1.join(table2, table1.c.a==table2.c.b)
    )

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

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

select([func.count('*')]).select_from(table1)
self_group(against=None)

return a ‘grouping’ construct as per the ClauseElement specification.

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

union(other, **kwargs)

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

union_all(other, **kwargs)

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

unique_params(*optionaldict, **kwargs)
inherited from the unique_params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

where(whereclause)

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

with_hint(selectable, text, dialect_name='*')

Add an indexing hint for the given selectable to this Select.

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

select([mytable]).\
    with_hint(mytable, "+ index(%(name)s ix_mytable)")

Would render SQL as:

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

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

select([mytable]).\
    with_hint(mytable, "+ index(%(name)s ix_mytable)", 'oracle').\
    with_hint(mytable, "WITH INDEX ix_mytable", 'sybase')
with_only_columns(columns)

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

Changed in version 0.7.3: Due to a bug fix, this method has a slight behavioral change as of version 0.7.3. Prior to version 0.7.3, the FROM clause of a select() was calculated upfront and as new columns were added; in 0.7.3 and later it’s calculated at compile time, fixing an issue regarding late binding of columns to parent tables. This changes the behavior of Select.with_only_columns() in that FROM clauses no longer represented in the new list are dropped, but this behavior is more consistent in that the FROM clauses are consistently derived from the current columns clause. The original intent of this method is to allow trimming of the existing columns list to be fewer columns than originally present; the use case of replacing the columns list with an entirely different one hadn’t been anticipated until 0.7.3 was released; the usage guidelines below illustrate how this should be done.

This method is exactly equivalent to as if the original select() had been called with the given columns clause. I.e. a statement:

s = select([table1.c.a, table1.c.b])
s = s.with_only_columns([table1.c.b])

should be exactly equivalent to:

s = select([table1.c.b])

This means that FROM clauses which are only derived from the column list will be discarded if the new column list no longer contains that FROM:

>>> table1 = table('t1', column('a'), column('b'))
>>> table2 = table('t2', column('a'), column('b'))
>>> s1 = select([table1.c.a, table2.c.b])
>>> print s1
SELECT t1.a, t2.b FROM t1, t2
>>> s2 = s1.with_only_columns([table2.c.b])
>>> print s2
SELECT t2.b FROM t1

The preferred way to maintain a specific FROM clause in the construct, assuming it won’t be represented anywhere else (i.e. not in the WHERE clause, etc.) is to set it using Select.select_from():

>>> s1 = select([table1.c.a, table2.c.b]).\
...         select_from(table1.join(table2,
...                 table1.c.a==table2.c.a))
>>> s2 = s1.with_only_columns([table2.c.b])
>>> print s2
SELECT t2.b FROM t1 JOIN t2 ON t1.a=t2.a

Care should also be taken to use the correct set of column objects passed to Select.with_only_columns(). Since the method is essentially equivalent to calling the select() construct in the first place with the given columns, the columns passed to Select.with_only_columns() should usually be a subset of those which were passed to the select() construct, not those which are available from the .c collection of that select(). That is:

s = select([table1.c.a, table1.c.b]).select_from(table1)
s = s.with_only_columns([table1.c.b])

and not:

# usually incorrect
s = s.with_only_columns([s.c.b])

The latter would produce the SQL:

SELECT b
FROM (SELECT t1.a AS a, t1.b AS b
FROM t1), t1

Since the select() construct is essentially being asked to select both from table1 as well as itself.

class sqlalchemy.sql.expression.Selectable

Bases: sqlalchemy.sql.expression.ClauseElement

mark a class as being selectable

class sqlalchemy.sql.expression.SelectBase(use_labels=False, for_update=False, limit=None, offset=None, order_by=None, group_by=None, bind=None, autocommit=None)

Bases: sqlalchemy.sql.expression.Executable, sqlalchemy.sql.expression.FromClause

Base class for Select and CompoundSelects.

append_group_by(*clauses)

Append the given GROUP BY criterion applied to this selectable.

The criterion will be appended to any pre-existing GROUP BY criterion.

This is an in-place mutation method; the group_by() method is preferred, as it provides standard method chaining.

append_order_by(*clauses)

Append the given ORDER BY criterion applied to this selectable.

The criterion will be appended to any pre-existing ORDER BY criterion.

This is an in-place mutation method; the order_by() method is preferred, as it provides standard method chaining.

apply_labels()

return a new selectable with the ‘use_labels’ flag set to True.

This will result in column expressions being generated using labels against their table name, such as “SELECT somecolumn AS tablename_somecolumn”. This allows selectables which contain multiple FROM clauses to produce a unique set of column names regardless of name conflicts among the individual FROM clauses.

as_scalar()

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

Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression.

The returned object is an instance of ScalarSelect.

autocommit()

return a new selectable with the ‘autocommit’ flag set to

Deprecated since version 0.6: autocommit() is deprecated. Use Executable.execution_options() with the ‘autocommit’ flag.

True.

cte(name=None, recursive=False)

Return a new CTE, or Common Table Expression instance.

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

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

New in version 0.7.6.

Parameters:
  • name – name given to the common table expression. Like _FromClause.alias(), the name can be left as None in which case an anonymous symbol will be used at query compile time.
  • recursive – if True, will render WITH RECURSIVE. A recursive common table expression is intended to be used in conjunction with UNION ALL in order to derive rows from those already selected.

The following examples illustrate two examples from Postgresql’s documentation at http://www.postgresql.org/docs/8.4/static/queries-with.html.

Example 1, non recursive:

from sqlalchemy import Table, Column, String, Integer, MetaData, \
    select, func

metadata = MetaData()

orders = Table('orders', metadata,
    Column('region', String),
    Column('amount', Integer),
    Column('product', String),
    Column('quantity', Integer)
)

regional_sales = select([
                    orders.c.region,
                    func.sum(orders.c.amount).label('total_sales')
                ]).group_by(orders.c.region).cte("regional_sales")


top_regions = select([regional_sales.c.region]).\
        where(
            regional_sales.c.total_sales >
            select([
                func.sum(regional_sales.c.total_sales)/10
            ])
        ).cte("top_regions")

statement = select([
            orders.c.region,
            orders.c.product,
            func.sum(orders.c.quantity).label("product_units"),
            func.sum(orders.c.amount).label("product_sales")
    ]).where(orders.c.region.in_(
        select([top_regions.c.region])
    )).group_by(orders.c.region, orders.c.product)

result = conn.execute(statement).fetchall()

Example 2, WITH RECURSIVE:

from sqlalchemy import Table, Column, String, Integer, MetaData, \
    select, func

metadata = MetaData()

parts = Table('parts', metadata,
    Column('part', String),
    Column('sub_part', String),
    Column('quantity', Integer),
)

included_parts = select([
                    parts.c.sub_part,
                    parts.c.part,
                    parts.c.quantity]).\
                    where(parts.c.part=='our part').\
                    cte(recursive=True)


incl_alias = included_parts.alias()
parts_alias = parts.alias()
included_parts = included_parts.union_all(
    select([
        parts_alias.c.part,
        parts_alias.c.sub_part,
        parts_alias.c.quantity
    ]).
        where(parts_alias.c.part==incl_alias.c.sub_part)
)

statement = select([
            included_parts.c.sub_part,
            func.sum(included_parts.c.quantity).
              label('total_quantity')
        ]).                    select_from(included_parts.join(parts,
                    included_parts.c.part==parts.c.part)).\
        group_by(included_parts.c.sub_part)

result = conn.execute(statement).fetchall()

See also

orm.query.Query.cte() - ORM version of SelectBase.cte().

group_by(*clauses)

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

The criterion will be appended to any pre-existing GROUP BY criterion.

label(name)

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

See also

as_scalar().

limit(limit)

return a new selectable with the given LIMIT criterion applied.

offset(offset)

return a new selectable with the given OFFSET criterion applied.

order_by(*clauses)

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

The criterion will be appended to any pre-existing ORDER BY criterion.

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

Bases: sqlalchemy.sql.expression.Immutable, sqlalchemy.sql.expression.FromClause

Represents a minimal “table” construct.

The constructor for TableClause is the table() function. This produces a lightweight table object that has only a name and a collection of columns, which are typically produced by the column() function:

from sqlalchemy.sql import table, column

user = table("user",
        column("id"),
        column("name"),
        column("description"),
)

The TableClause construct serves as the base for the more commonly used Table object, providing the usual set of FromClause services including the .c. collection and statement generation methods.

It does not provide all the additional schema-level services of Table, including constraints, references to other tables, or support for MetaData-level services. It’s useful on its own as an ad-hoc construct used to generate quick SQL statements when a more fully fledged Table is not on hand.

alias(name=None)
inherited from the alias() method of FromClause

return an alias of this FromClause.

This is shorthand for calling:

from sqlalchemy import alias
a = alias(self, name=name)

See alias() for details.

c
inherited from the c attribute of FromClause

An alias for the columns attribute.

columns
inherited from the columns attribute of FromClause

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

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

select([mytable]).where(mytable.c.somecolumn == 5)
compare(other, **kw)
inherited from the compare() method of ClauseElement

Compare this ClauseElement 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 ColumnElement)

compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
correspond_on_equivalents(column, equivalents)
inherited from the correspond_on_equivalents() method of FromClause

Return corresponding_column for the given column, or if None search for a match in the given dictionary.

corresponding_column(column, require_embedded=False)
inherited from the corresponding_column() method of FromClause

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

Parameters:
  • column – the target ColumnElement to be matched
  • require_embedded – only return corresponding columns for

the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.

count(whereclause=None, **params)

return a SELECT COUNT generated against this TableClause.

delete(whereclause=None, **kwargs)

Generate a delete() construct against this TableClause.

E.g.:

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

See delete() for argument and usage information.

foreign_keys
inherited from the foreign_keys attribute of FromClause

Return the collection of ForeignKey objects which this FromClause references.

implicit_returning = False

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

insert(values=None, inline=False, **kwargs)

Generate an insert() construct against this TableClause.

E.g.:

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

See insert() for argument and usage information.

is_derived_from(fromclause)
inherited from the is_derived_from() method of FromClause

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

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

join(right, onclause=None, isouter=False)
inherited from the join() method of FromClause

return a join of this FromClause against another FromClause.

outerjoin(right, onclause=None)
inherited from the outerjoin() method of FromClause

return an outer join of this FromClause against another FromClause.

primary_key
inherited from the primary_key attribute of FromClause

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

replace_selectable(old, alias)
inherited from the replace_selectable() method of FromClause

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

select(whereclause=None, **params)
inherited from the select() method of FromClause

return a SELECT of this FromClause.

See also

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

self_group(against=None)
inherited from the self_group() method of ClauseElement

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 select() constructs when placed into the FROM clause of another select(). (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 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 self_group() method of ClauseElement just returns self.

update(whereclause=None, values=None, inline=False, **kwargs)

Generate an update() construct against this TableClause.

E.g.:

table.update().where(table.c.id==7).values(name='foo')

See update() for argument and usage information.

class sqlalchemy.sql.expression.UnaryExpression(element, operator=None, modifier=None, type_=None, negate=None)

Bases: sqlalchemy.sql.expression.ColumnElement

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.

compare(other, **kw)

Compare this UnaryExpression against the given ClauseElement.

class sqlalchemy.sql.expression.Update(table, whereclause, values=None, inline=False, bind=None, prefixes=None, returning=None, **kwargs)

Bases: sqlalchemy.sql.expression.ValuesBase

Represent an Update construct.

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

bind
inherited from the bind attribute of UpdateBase

Return a ‘bind’ linked to this UpdateBase or a Table associated with it.

compare(other, **kw)
inherited from the compare() method of ClauseElement

Compare this ClauseElement 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 ColumnElement)

compile(bind=None, dialect=None, **kw)
inherited from the compile() method of ClauseElement

Compile this SQL expression.

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

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • dialect – A Dialect instance from which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
execute(*multiparams, **params)
inherited from the execute() method of Executable

Compile and execute this Executable.

execution_options(**kw)
inherited from the execution_options() method of Executable

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

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

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

statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)

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

params(*arg, **kw)
inherited from the params() method of UpdateBase

Set the parameters for the statement.

This method raises NotImplementedError on the base class, and is overridden by ValuesBase to provide the SET/VALUES clause of UPDATE and INSERT.

prefix_with(*expr, **kw)
inherited from the prefix_with() method of HasPrefixes

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

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

E.g.:

stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")

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

Parameters:
  • *expr – textual or ClauseElement construct which will be rendered following the INSERT, UPDATE, or DELETE keyword.
  • **kw – A single keyword ‘dialect’ is accepted. This is an optional string dialect name which will limit rendering of this prefix to only that dialect.
returning(*cols)
inherited from the returning() method of UpdateBase

Add a RETURNING or equivalent clause to this statement.

The given list of columns represent columns within the table that is the target of the INSERT, UPDATE, or DELETE. Each element can be any column expression. Table objects will be expanded into their individual columns.

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

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

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

scalar(*multiparams, **params)
inherited from the scalar() method of Executable

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

self_group(against=None)
inherited from the self_group() method of ClauseElement

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 select() constructs when placed into the FROM clause of another select(). (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 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 self_group() method of ClauseElement just returns self.

unique_params(*optionaldict, **kwargs)
inherited from the unique_params() method of ClauseElement

Return a copy with bindparam() elements replaced.

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

values(*args, **kwargs)
inherited from the values() method of ValuesBase

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

Note that the Insert and Update constructs support per-execution time formatting of the VALUES and/or SET clauses, based on the arguments passed to Connection.execute(). However, the ValuesBase.values() method can be used to “fix” a particular set of parameters into the statement.

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

Parameters:
  • **kwargs

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

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

    Alternatively, a dictionary, tuple or list of dictionaries or tuples can be passed as a single positional argument in order to form the VALUES or SET clause of the statement. The single dictionary form works the same as the kwargs form:

    users.insert().values({"name": "some name"})

    If a tuple is passed, the tuple should contain the same number of columns as the target Table:

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

    The Insert construct also supports multiply-rendered VALUES construct, for those backends which support this SQL syntax (SQLite, Postgresql, MySQL). This mode is indicated by passing a list of one or more dictionaries/tuples:

    users.insert().values([
                        {"name": "some name"},
                        {"name": "some other name"},
                        {"name": "yet another name"},
                    ])

    In the case of an Update construct, only the single dictionary/tuple form is accepted, else an exception is raised. It is also an exception case to attempt to mix the single-/multiple- value styles together, either through multiple ValuesBase.values() calls or by sending a list + kwargs at the same time.

    Note

    Passing a multiple values list is not the same as passing a multiple values list to the Connection.execute() method. Passing a list of parameter sets to ValuesBase.values() produces a construct of this form:

    INSERT INTO table (col1, col2, col3) VALUES
                    (col1_0, col2_0, col3_0),
                    (col1_1, col2_1, col3_1),
                    ...

    whereas a multiple list passed to Connection.execute() has the effect of using the DBAPI executemany() method, which provides a high-performance system of invoking a single-row INSERT statement many times against a series of parameter sets. The “executemany” style is supported by all database backends, as it does not depend on a special SQL syntax.

    New in version 0.8: Support for multiple-VALUES INSERT statements.

See also

Inserts, Updates and Deletes - SQL Expression Language Tutorial

insert() - produce an INSERT statement

update() - produce an UPDATE statement

where(whereclause)

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

with_hint(text, selectable=None, dialect_name='*')
inherited from the with_hint() method of UpdateBase

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

Note

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

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

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

mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql")

New in version 0.7.6.

Parameters:
  • text – Text of the hint.
  • selectable – optional Table that specifies an element of the FROM clause within an UPDATE or DELETE to be the subject of the hint - applies only to certain backends.
  • dialect_name – defaults to *, if specified as the name of a particular dialect, will apply these hints only when that dialect is in use.
class sqlalchemy.sql.expression.UpdateBase

Bases: sqlalchemy.sql.expression.HasPrefixes, sqlalchemy.sql.expression.Executable, sqlalchemy.sql.expression.ClauseElement

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

bind

Return a ‘bind’ linked to this UpdateBase or a Table associated with it.

params(*arg, **kw)

Set the parameters for the statement.

This method raises NotImplementedError on the base class, and is overridden by ValuesBase to provide the SET/VALUES clause of UPDATE and INSERT.

returning(*cols)

Add a RETURNING or equivalent clause to this statement.

The given list of columns represent columns within the table that is the target of the INSERT, UPDATE, or DELETE. Each element can be any column expression. Table objects will be expanded into their individual columns.

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

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

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

with_hint(text, selectable=None, dialect_name='*')

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

Note

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

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

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

mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql")

New in version 0.7.6.

Parameters:
  • text – Text of the hint.
  • selectable – optional Table that specifies an element of the FROM clause within an UPDATE or DELETE to be the subject of the hint - applies only to certain backends.
  • dialect_name – defaults to *, if specified as the name of a particular dialect, will apply these hints only when that dialect is in use.
class sqlalchemy.sql.expression.ValuesBase(table, values, prefixes)

Bases: sqlalchemy.sql.expression.UpdateBase

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

values(*args, **kwargs)

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

Note that the Insert and Update constructs support per-execution time formatting of the VALUES and/or SET clauses, based on the arguments passed to Connection.execute(). However, the ValuesBase.values() method can be used to “fix” a particular set of parameters into the statement.

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

Parameters:
  • **kwargs

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

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

    Alternatively, a dictionary, tuple or list of dictionaries or tuples can be passed as a single positional argument in order to form the VALUES or SET clause of the statement. The single dictionary form works the same as the kwargs form:

    users.insert().values({"name": "some name"})

    If a tuple is passed, the tuple should contain the same number of columns as the target Table:

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

    The Insert construct also supports multiply-rendered VALUES construct, for those backends which support this SQL syntax (SQLite, Postgresql, MySQL). This mode is indicated by passing a list of one or more dictionaries/tuples:

    users.insert().values([
                        {"name": "some name"},
                        {"name": "some other name"},
                        {"name": "yet another name"},
                    ])

    In the case of an Update construct, only the single dictionary/tuple form is accepted, else an exception is raised. It is also an exception case to attempt to mix the single-/multiple- value styles together, either through multiple ValuesBase.values() calls or by sending a list + kwargs at the same time.

    Note

    Passing a multiple values list is not the same as passing a multiple values list to the Connection.execute() method. Passing a list of parameter sets to ValuesBase.values() produces a construct of this form:

    INSERT INTO table (col1, col2, col3) VALUES
                    (col1_0, col2_0, col3_0),
                    (col1_1, col2_1, col3_1),
                    ...

    whereas a multiple list passed to Connection.execute() has the effect of using the DBAPI executemany() method, which provides a high-performance system of invoking a single-row INSERT statement many times against a series of parameter sets. The “executemany” style is supported by all database backends, as it does not depend on a special SQL syntax.

    New in version 0.8: Support for multiple-VALUES INSERT statements.

See also

Inserts, Updates and Deletes - SQL Expression Language Tutorial

insert() - produce an INSERT statement

update() - produce an UPDATE statement

Generic Functions

SQL functions which are known to SQLAlchemy with regards to database-specific rendering, return types and argument behavior. Generic functions are invoked like all SQL functions, using the func attribute:

select([func.count()]).select_from(sometable)

Note that any name not known to func generates the function name as is - there is no restriction on what SQL functions can be called, known or unknown to SQLAlchemy, built-in or user defined. The section here only describes those functions where SQLAlchemy already knows what argument and return types are in use.

class sqlalchemy.sql.functions.AnsiFunction(**kwargs)

Bases: sqlalchemy.sql.functions.GenericFunction

identifier = 'AnsiFunction'
name = 'AnsiFunction'
class sqlalchemy.sql.functions.GenericFunction(*args, **kwargs)

Bases: sqlalchemy.sql.expression.Function

Define a ‘generic’ function.

A generic function is a pre-established Function class that is instantiated automatically when called by name from the func attribute. Note that calling any name from func has the effect that a new Function instance is created automatically, given that name. The primary use case for defining a GenericFunction class is so that a function of a particular name may be given a fixed return type. It can also include custom argument parsing schemes as well as additional methods.

Subclasses of GenericFunction are automatically registered under the name of the class. For example, a user-defined function as_utc() would be available immediately:

from sqlalchemy.sql.functions import GenericFunction
from sqlalchemy.types import DateTime

class as_utc(GenericFunction):
    type = DateTime

print select([func.as_utc()])

User-defined generic functions can be organized into packages by specifying the “package” attribute when defining GenericFunction. Third party libraries containing many functions may want to use this in order to avoid name conflicts with other systems. For example, if our as_utc() function were part of a package “time”:

class as_utc(GenericFunction):
    type = DateTime
    package = "time"

The above function would be available from func using the package name time:

print select([func.time.as_utc()])

A final option is to allow the function to be accessed from one name in func but to render as a different name. The identifier attribute will override the name used to access the function as loaded from func, but will retain the usage of name as the rendered name:

class GeoBuffer(GenericFunction):
    type = Geometry
    package = "geo"
    name = "ST_Buffer"
    identifier = "buffer"

The above function will render as follows:

>>> print func.geo.buffer()
ST_Buffer()

New in version 0.8: GenericFunction now supports automatic registration of new functions as well as package and custom naming support.

Changed in version 0.8: The attribute name type is used to specify the function’s return type at the class level. Previously, the name __return_type__ was used. This name is still recognized for backwards-compatibility.

coerce_arguments = True
identifier = 'GenericFunction'
name = 'GenericFunction'
class sqlalchemy.sql.functions.ReturnTypeFromArgs(*args, **kwargs)

Bases: sqlalchemy.sql.functions.GenericFunction

Define a function whose return type is the same as its arguments.

identifier = 'ReturnTypeFromArgs'
name = 'ReturnTypeFromArgs'
class sqlalchemy.sql.functions.char_length(arg, **kwargs)

Bases: sqlalchemy.sql.functions.GenericFunction

identifier = 'char_length'
name = 'char_length'
type

alias of Integer

class sqlalchemy.sql.functions.coalesce(*args, **kwargs)

Bases: sqlalchemy.sql.functions.ReturnTypeFromArgs

identifier = 'coalesce'
name = 'coalesce'
class sqlalchemy.sql.functions.concat(*args, **kwargs)

Bases: sqlalchemy.sql.functions.GenericFunction

identifier = 'concat'
name = 'concat'
type

alias of String

class sqlalchemy.sql.functions.count(expression=None, **kwargs)

Bases: sqlalchemy.sql.functions.GenericFunction

The ANSI COUNT aggregate function. With no arguments, emits COUNT *.

identifier = 'count'
name = 'count'
type

alias of Integer

class sqlalchemy.sql.functions.current_date(**kwargs)

Bases: sqlalchemy.sql.functions.AnsiFunction

identifier = 'current_date'
name = 'current_date'
type

alias of Date

class sqlalchemy.sql.functions.current_time(**kwargs)

Bases: sqlalchemy.sql.functions.AnsiFunction

identifier = 'current_time'
name = 'current_time'
type

alias of Time

class sqlalchemy.sql.functions.current_timestamp(**kwargs)

Bases: sqlalchemy.sql.functions.AnsiFunction

identifier = 'current_timestamp'
name = 'current_timestamp'
type

alias of DateTime

class sqlalchemy.sql.functions.current_user(**kwargs)

Bases: sqlalchemy.sql.functions.AnsiFunction

identifier = 'current_user'
name = 'current_user'
type

alias of String

class sqlalchemy.sql.functions.localtime(**kwargs)

Bases: sqlalchemy.sql.functions.AnsiFunction

identifier = 'localtime'
name = 'localtime'
type

alias of DateTime

class sqlalchemy.sql.functions.localtimestamp(**kwargs)

Bases: sqlalchemy.sql.functions.AnsiFunction

identifier = 'localtimestamp'
name = 'localtimestamp'
type

alias of DateTime

class sqlalchemy.sql.functions.max(*args, **kwargs)

Bases: sqlalchemy.sql.functions.ReturnTypeFromArgs

identifier = 'max'
name = 'max'
class sqlalchemy.sql.functions.min(*args, **kwargs)

Bases: sqlalchemy.sql.functions.ReturnTypeFromArgs

identifier = 'min'
name = 'min'
class sqlalchemy.sql.functions.next_value(seq, **kw)

Bases: sqlalchemy.sql.functions.GenericFunction

Represent the ‘next value’, given a Sequence as it’s single argument.

Compiles into the appropriate function on each backend, or will raise NotImplementedError if used on a backend that does not provide support for sequences.

identifier = 'next_value'
name = 'next_value'
type = Integer()
class sqlalchemy.sql.functions.now(*args, **kwargs)

Bases: sqlalchemy.sql.functions.GenericFunction

identifier = 'now'
name = 'now'
type

alias of DateTime

class sqlalchemy.sql.functions.random(*args, **kwargs)

Bases: sqlalchemy.sql.functions.GenericFunction

identifier = 'random'
name = 'random'
sqlalchemy.sql.functions.register_function(identifier, fn, package='_default')

Associate a callable with a particular func. name.

This is normally called by _GenericMeta, but is also available by itself so that a non-Function construct can be associated with the func accessor (i.e. CAST, EXTRACT).

class sqlalchemy.sql.functions.session_user(**kwargs)

Bases: sqlalchemy.sql.functions.AnsiFunction

identifier = 'session_user'
name = 'session_user'
type

alias of String

class sqlalchemy.sql.functions.sum(*args, **kwargs)

Bases: sqlalchemy.sql.functions.ReturnTypeFromArgs

identifier = 'sum'
name = 'sum'
class sqlalchemy.sql.functions.sysdate(**kwargs)

Bases: sqlalchemy.sql.functions.AnsiFunction

identifier = 'sysdate'
name = 'sysdate'
type

alias of DateTime

class sqlalchemy.sql.functions.user(**kwargs)

Bases: sqlalchemy.sql.functions.AnsiFunction

identifier = 'user'
name = 'user'
type

alias of String