Release: 1.0.8 | Release Date: July 22, 2015

SQLAlchemy 1.0 Documentation

Query API

The Query Object

Query is produced in terms of a given Session, using the query() method:

q = session.query(SomeMappedClass)

Following is the full interface for the Query object.

class sqlalchemy.orm.query.Query(entities, session=None)

ORM-level SQL construction object.

Query is the source of all SELECT statements generated by the ORM, both those formulated by end-user query operations as well as by high level internal operations such as related collection loading. It features a generative interface whereby successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.

Query objects are normally initially generated using the query() method of Session. For a full walkthrough of Query usage, see the Object Relational Tutorial.


Add a column expression to the list of result columns to be returned.

Pending deprecation: add_column() will be superseded by add_columns().


Add one or more column expressions to the list of result columns to be returned.

add_entity(entity, alias=None)

add a mapped entity to the list of result columns to be returned.


Return the results represented by this Query as a list.

This results in an execution of the underlying query.


Return the full SELECT statement represented by this Query, converted to a scalar subquery.

Analogous to sqlalchemy.sql.expression.SelectBase.as_scalar().

New in version 0.6.5.


Return a Query with a specific ‘autoflush’ setting.

Note that a Session with autoflush=False will not autoflush, even if this flag is set to True at the Query level. Therefore this flag is usually used only to disable autoflush for a specific Query.


Return metadata about the columns which would be returned by this Query.

Format is a list of dictionaries:

user_alias = aliased(User, name='user2')
q = sess.query(User,, user_alias)

# this expression:

# would return:
        'entity': User
        'entity': User
        'entity': user_alias

Return a Query construct which will correlate the given FROM clauses to that of an enclosing Query or select().

The method here accepts mapped classes, aliased() constructs, and mapper() constructs as arguments, which are resolved into expression constructs, in addition to appropriate expression constructs.

The correlation arguments are ultimately passed to Select.correlate() after coercion to expression constructs.

The correlation arguments take effect in such cases as when Query.from_self() is used, or when a subquery as returned by Query.subquery() is embedded in another select() construct.


Return a count of rows this Query would return.

This generates the SQL for this Query as follows:

SELECT count(1) AS count_1 FROM (
    SELECT <rest of query follows...>
) AS anon_1

Changed in version 0.7: The above scheme is newly refined as of 0.7b3.

For fine grained control over specific columns to count, to skip the usage of a subquery or otherwise control of the FROM clause, or to use other aggregate functions, use func expressions in conjunction with query(), i.e.:

from sqlalchemy import func

# count User records, without
# using a subquery.

# return count of user "id" grouped
# by "name"

from sqlalchemy import distinct

# count distinct "name" values
cte(name=None, recursive=False)

Return the full SELECT statement represented by this Query represented as a common table expression (CTE).

New in version 0.7.6.

Parameters and usage are the same as those of the SelectBase.cte() method; see that method for further details.

Here is the Postgresql WITH RECURSIVE example. Note that, in this example, the included_parts cte and the incl_alias alias of it are Core selectables, which means the columns are accessed via the .c. attribute. The parts_alias object is an orm.aliased() instance of the Part entity, so column-mapped attributes are available directly:

from sqlalchemy.orm import aliased

class Part(Base):
    __tablename__ = 'part'
    part = Column(String, primary_key=True)
    sub_part = Column(String, primary_key=True)
    quantity = Column(Integer)

included_parts = session.query(
                    filter(Part.part=="our part").\
                    cte(name="included_parts", recursive=True)

incl_alias = aliased(included_parts, name="pr")
parts_alias = aliased(Part, name="p")
included_parts = included_parts.union_all(

q = session.query(

See also



Perform a bulk delete query.

Deletes rows matched by this query from the database.


sess.query(User).filter(User.age == 25).\

sess.query(User).filter(User.age == 25).\


The Query.delete() method is a “bulk” operation, which bypasses ORM unit-of-work automation in favor of greater performance. Please read all caveats and warnings below.


chooses the strategy for the removal of matched objects from the session. Valid values are:

False - don’t synchronize the session. This option is the most efficient and is reliable once the session is expired, which typically occurs after a commit(), or explicitly using expire_all(). Before the expiration, objects may still remain in the session which were in fact deleted which can lead to confusing results if they are accessed via get() or already loaded collections.

'fetch' - performs a select query before the delete to find objects that are matched by the delete query and need to be removed from the session. Matched objects are removed from the session.

'evaluate' - Evaluate the query’s criteria in Python straight on the objects in the session. If evaluation of the criteria isn’t implemented, an error is raised.

The expression evaluator currently doesn’t account for differing string collations between the database and Python.

Returns:the count of rows matched as returned by the database’s “row count” feature.


Additional Caveats for bulk query deletes

  • The method does not offer in-Python cascading of relationships - it is assumed that ON DELETE CASCADE/SET NULL/etc. is configured for any foreign key references which require it, otherwise the database may emit an integrity violation if foreign key references are being enforced.

    After the DELETE, dependent objects in the Session which were impacted by an ON DELETE may not contain the current state, or may have been deleted. This issue is resolved once the Session is expired, which normally occurs upon Session.commit() or can be forced by using Session.expire_all(). Accessing an expired object whose row has been deleted will invoke a SELECT to locate the row; when the row is not found, an ObjectDeletedError is raised.

  • The 'fetch' strategy results in an additional SELECT statement emitted and will significantly reduce performance.

  • The 'evaluate' strategy performs a scan of all matching objects within the Session; if the contents of the Session are expired, such as via a proceeding Session.commit() call, this will result in SELECT queries emitted for every matching object.

  • The MapperEvents.before_delete() and MapperEvents.after_delete() events are not invoked from this method. Instead, the SessionEvents.after_bulk_delete() method is provided to act upon a mass DELETE of entity rows.

See also


Inserts, Updates and Deletes - Core SQL tutorial


Apply a DISTINCT to the query and return the newly resulting Query.


The distinct() call includes logic that will automatically add columns from the ORDER BY of the query to the columns clause of the SELECT statement, to satisfy the common need of the database backend that ORDER BY columns be part of the SELECT list when DISTINCT is used. These columns are not added to the list of columns actually fetched by the Query, however, so would not affect results. The columns are passed through when using the Query.statement accessor, however.

Parameters:*expr – optional column expressions. When present, the Postgresql dialect will render a DISTINCT ON (<expressions>>) construct.

Control whether assertions are generated.

When set to False, the returned Query will not assert its state before certain operations, including that LIMIT/OFFSET has not been applied when filter() is called, no criterion exists when get() is called, and no “from_statement()” exists when filter()/order_by()/group_by() etc. is called. This more permissive mode is used by custom Query subclasses to specify criterion or other modifiers outside of the usual usage patterns.

Care should be taken to ensure that the usage pattern is even possible. A statement applied by from_statement() will override any criterion set by filter() or order_by(), for example.


Control whether or not eager joins and subqueries are rendered.

When set to False, the returned Query will not render eager joins regardless of joinedload(), subqueryload() options or mapper-level lazy='joined'/lazy='subquery' configurations.

This is used primarily when nesting the Query’s statement into a subquery or other selectable, or when using Query.yield_per().


Produce an EXCEPT of this Query against one or more queries.

Works the same way as union(). See that method for usage examples.


Produce an EXCEPT ALL of this Query against one or more queries.

Works the same way as union(). See that method for usage examples.


Set non-SQL options which take effect during execution.

The options are the same as those accepted by Connection.execution_options().

Note that the stream_results execution option is enabled automatically if the yield_per() method is used.


A convenience method that turns a query into an EXISTS subquery of the form EXISTS (SELECT 1 FROM ... WHERE ...).


q = session.query(User).filter( == 'fred')

Producing SQL similar to:

    SELECT 1 FROM users WHERE = :name_1
) AS anon_1

The EXISTS construct is usually used in the WHERE clause:


Note that some databases such as SQL Server don’t allow an EXISTS expression to be present in the columns clause of a SELECT. To select a simple boolean value based on the exists as a WHERE, use literal():

from sqlalchemy import literal


New in version 0.8.1.


apply the given filtering criterion to a copy of this Query, using SQL expressions.


session.query(MyClass).filter( == 'some name')

Multiple criteria are joined together by AND:

    filter( == 'some name', > 5)

The criterion is any SQL expression object applicable to the WHERE clause of a select. String expressions are coerced into SQL expression constructs via the text() construct.

Changed in version 0.7.5: Multiple criteria joined by AND.

See also

Query.filter_by() - filter on keyword expressions.


apply the given filtering criterion to a copy of this Query, using keyword expressions.


session.query(MyClass).filter_by(name = 'some name')

Multiple criteria are joined together by AND:

    filter_by(name = 'some name', id = 5)

The keyword expressions are extracted from the primary entity of the query, or the last entity that was the target of a call to Query.join().

See also

Query.filter() - filter on SQL expressions.


Return the first result of this Query or None if the result doesn’t contain any row.

first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present).

Calling first() results in an execution of the underlying query.


return a Query that selects from this Query’s SELECT statement.

*entities - optional list of entities which will replace those being selected.


Execute the given SELECT statement and return results.

This method bypasses all internal statement compilation, and the statement is executed without modification.

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

See also

Using Textual SQL - usage examples in the ORM tutorial


Return an instance based on the given primary key identifier, or None if not found.


my_user = session.query(User).get(5)

some_object = session.query(VersionedFoo).get((5, 10))

get() is special in that it provides direct access to the identity map of the owning Session. If the given primary key identifier is present in the local identity map, the object is returned directly from this collection and no SQL is emitted, unless the object has been marked fully expired. If not present, a SELECT is performed in order to locate the object.

get() also will perform a check if the object is present in the identity map and marked as expired - a SELECT is emitted to refresh the object as well as to ensure that the row is still present. If not, ObjectDeletedError is raised.

get() is only used to return a single mapped instance, not multiple instances or individual column constructs, and strictly on a single primary key value. The originating Query must be constructed in this way, i.e. against a single mapped entity, with no additional filtering criterion. Loading options via options() may be applied however, and will be used if the object is not yet locally present.

A lazy-loading, many-to-one attribute configured by relationship(), using a simple foreign-key-to-primary-key criterion, will also use an operation equivalent to get() in order to retrieve the target value from the local identity map before querying the database. See Relationship Loading Techniques for further details on relationship loading.

Parameters:ident – A scalar or tuple value representing the primary key. For a composite primary key, the order of identifiers corresponds in most cases to that of the mapped Table object’s primary key columns. For a mapper() that was given the primary key argument during construction, the order of identifiers corresponds to the elements present in this collection.
Returns:The object instance, or None.

apply one or more GROUP BY criterion to the query and return the newly resulting Query


apply a HAVING criterion to the query and return the newly resulting Query.

having() is used in conjunction with group_by().

HAVING criterion makes it possible to use filters on aggregate functions like COUNT, SUM, AVG, MAX, and MIN, eg.:

q = session.query(\
            having(func.count( > 2)
instances(cursor, _Query__context=None)

Given a ResultProxy cursor as returned by connection.execute(), return an ORM result as an iterator.


result = engine.execute("select * from users")
for u in session.query(User).instances(result):
    print u

Produce an INTERSECT of this Query against one or more queries.

Works the same way as union(). See that method for usage examples.


Produce an INTERSECT ALL of this Query against one or more queries.

Works the same way as union(). See that method for usage examples.

join(*props, **kwargs)

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

Simple Relationship Joins

Consider a mapping between two classes User and Address, with a relationship User.addresses representing a collection of Address objects associated with each User. The most common usage of join() is to create a JOIN along this relationship, using the User.addresses attribute as an indicator for how this should occur:

q = session.query(User).join(User.addresses)

Where above, the call to join() along User.addresses will result in SQL equivalent to:

SELECT user.* FROM user JOIN address ON = address.user_id

In the above example we refer to User.addresses as passed to join() as the on clause, that is, it indicates how the “ON” portion of the JOIN should be constructed. For a single-entity query such as the one above (i.e. we start by selecting only from User and nothing else), the relationship can also be specified by its string name:

q = session.query(User).join("addresses")

join() can also accommodate multiple “on clause” arguments to produce a chain of joins, such as below where a join across four related entities is constructed:

q = session.query(User).join("orders", "items", "keywords")

The above would be shorthand for three separate calls to join(), each using an explicit attribute to indicate the source entity:

q = session.query(User).\

Joins to a Target Entity or Selectable

A second form of join() allows any mapped entity or core selectable construct as a target. In this usage, join() will attempt to create a JOIN along the natural foreign key relationship between two entities:

q = session.query(User).join(Address)

The above calling form of join() will raise an error if either there are no foreign keys between the two entities, or if there are multiple foreign key linkages between them. In the above calling form, join() is called upon to create the “on clause” automatically for us. The target can be any mapped entity or selectable, such as a Table:

q = session.query(User).join(addresses_table)

Joins to a Target with an ON Clause

The third calling form allows both the target entity as well as the ON clause to be passed explicitly. Suppose for example we wanted to join to Address twice, using an alias the second time. We use aliased() to create a distinct alias of Address, and join to it using the target, onclause form, so that the alias can be specified explicitly as the target along with the relationship to instruct how the ON clause should proceed:

a_alias = aliased(Address)

q = session.query(User).\
        join(a_alias, User.addresses).\

Where above, the generated SQL would be similar to:

SELECT user.* FROM user
    JOIN address ON = address.user_id
    JOIN address AS address_1 ON
    WHERE address.email_address = :email_address_1
    AND address_1.email_address = :email_address_2

The two-argument calling form of join() also allows us to construct arbitrary joins with SQL-oriented “on clause” expressions, not relying upon configured relationships at all. Any SQL expression can be passed as the ON clause when using the two-argument form, which should refer to the target entity in some way as well as an applicable source entity:

q = session.query(User).join(Address,

Changed in version 0.7: In SQLAlchemy 0.6 and earlier, the two argument form of join() requires the usage of a tuple: query(User).join((Address, This calling form is accepted in 0.7 and further, though is not necessary unless multiple join conditions are passed to a single join() call, which itself is also not generally necessary as it is now equivalent to multiple calls (this wasn’t always the case).

Advanced Join Targeting and Adaption

There is a lot of flexibility in what the “target” can be when using join(). As noted previously, it also accepts Table constructs and other selectables such as alias() and select() constructs, with either the one or two-argument forms:

addresses_q = select([Address.user_id]).\

q = session.query(User).\

join() also features the ability to adapt a relationship() -driven ON clause to the target selectable. Below we construct a JOIN from User to a subquery against Address, allowing the relationship denoted by User.addresses to adapt itself to the altered target:

address_subq = session.query(Address).\
                filter(Address.email_address == '').\

q = session.query(User).join(address_subq, User.addresses)

Producing SQL similar to:

SELECT user.* FROM user
    JOIN (
        SELECT AS id,
                address.user_id AS user_id,
                address.email_address AS email_address
        FROM address
        WHERE address.email_address = :email_address_1
    ) AS anon_1 ON = anon_1.user_id

The above form allows one to fall back onto an explicit ON clause at any time:

q = session.query(User).\

Controlling what to Join From

While join() exclusively deals with the “right” side of the JOIN, we can also control the “left” side, in those cases where it’s needed, using select_from(). Below we construct a query against Address but can still make usage of User.addresses as our ON clause by instructing the Query to select first from the User entity:

q = session.query(Address).select_from(User).\
                filter( == 'ed')

Which will produce SQL similar to:

SELECT address.* FROM user
    JOIN address ON
    WHERE = :name_1

Constructing Aliases Anonymously

join() can construct anonymous aliases using the aliased=True flag. This feature is useful when a query is being joined algorithmically, such as when querying self-referentially to an arbitrary depth:

q = session.query(Node).\
        join("children", "children", aliased=True)

When aliased=True is used, the actual “alias” construct is not explicitly available. To work with it, methods such as Query.filter() will adapt the incoming entity to the last join point:

q = session.query(Node).\
        join("children", "children", aliased=True).\
        filter( == 'grandchild 1')

When using automatic aliasing, the from_joinpoint=True argument can allow a multi-node join to be broken into multiple calls to join(), so that each path along the way can be further filtered:

q = session.query(Node).\
        join("children", aliased=True).\
        filter('child 1').\
        join("children", aliased=True, from_joinpoint=True).\
        filter( == 'grandchild 1')

The filtering aliases above can then be reset back to the original Node entity using reset_joinpoint():

q = session.query(Node).\
        join("children", "children", aliased=True).\
        filter( == 'grandchild 1').\
        filter( == 'parent 1)

For an example of aliased=True, see the distribution example XML Persistence which illustrates an XPath-like query system using algorithmic joins.

  • *props – A collection of one or more join conditions, each consisting of a relationship-bound attribute or string relationship name representing an “on clause”, or a single target entity, or a tuple in the form of (target, onclause). A special two-argument calling form of the form target, onclause is also accepted.
  • aliased=False – If True, indicate that the JOIN target should be anonymously aliased. Subsequent calls to filter() and similar will adapt the incoming criterion to the target alias, until reset_joinpoint() is called.
  • isouter=False

    If True, the join used will be a left outer join, just as if the Query.outerjoin() method were called. This flag is here to maintain consistency with the same flag as accepted by FromClause.join() and other Core constructs.

    New in version 1.0.0.

  • from_joinpoint=False – When using aliased=True, a setting of True here will cause the join to be from the most recent joined target, rather than starting back from the original FROM clauses of the query.

See also

Querying with Joins in the ORM tutorial.

Mapping Class Inheritance Hierarchies for details on how join() is used for inheritance relationships.

orm.join() - a standalone ORM-level join function, used internally by Query.join(), which in previous SQLAlchemy versions was the primary ORM-level joining interface.


Return the full SELECT statement represented by this Query, converted to a scalar subquery with a label of the given name.

Analogous to sqlalchemy.sql.expression.SelectBase.label().

New in version 0.6.5.


Apply a LIMIT to the query and return the newly resulting


merge_result(iterator, load=True)

Merge a result into this Query object’s Session.

Given an iterator returned by a Query of the same structure as this one, return an identical iterator of results, with all mapped instances merged into the session using Session.merge(). This is an optimized method which will merge all mapped instances, preserving the structure of the result rows and unmapped columns with less method overhead than that of calling Session.merge() explicitly for each value.

The structure of the results is determined based on the column list of this Query - if these do not correspond, unchecked errors will occur.

The ‘load’ argument is the same as that of Session.merge().

For an example of how merge_result() is used, see the source code for the example Dogpile Caching, where merge_result() is used to efficiently restore state from a cache back into a target Session.


Apply an OFFSET to the query and return the newly resulting Query.


Return exactly one result or raise an exception.

Raises sqlalchemy.orm.exc.NoResultFound if the query selects no rows. Raises sqlalchemy.orm.exc.MultipleResultsFound if multiple object identities are returned, or if multiple rows are returned for a query that does not return object identities.

Note that an entity query, that is, one which selects one or more mapped classes as opposed to individual column attributes, may ultimately represent many rows but only one row of unique entity or entities - this is a successful result for one().

Calling one() results in an execution of the underlying query.

Changed in version 0.6: one() fully fetches all results instead of applying any kind of limit, so that the “unique”-ing of entities does not conceal multiple object identities.


Return a new Query object, applying the given list of mapper options.

Most supplied options regard changing how column- and relationship-mapped attributes are loaded. See the sections Deferred Column Loading and Relationship Loading Techniques for reference documentation.


apply one or more ORDER BY criterion to the query and return the newly resulting Query

All existing ORDER BY settings can be suppressed by passing None - this will suppress any ORDER BY configured on mappers as well.

Alternatively, an existing ORDER BY setting on the Query object can be entirely cancelled by passing False as the value - use this before calling methods where an ORDER BY is invalid.

outerjoin(*props, **kwargs)

Create a left outer join against this Query object’s criterion and apply generatively, returning the newly resulting Query.

Usage is the same as the join() method.

params(*args, **kwargs)

add values for bind parameters which may have been specified in filter().

parameters may be specified using **kwargs, or optionally a single dictionary as the first positional argument. The reason for both is that **kwargs is convenient, however some parameter dictionaries contain unicode keys in which case **kwargs cannot be used.


Return a Query that will expire and refresh all instances as they are loaded, or reused from the current Session.

populate_existing() does not improve behavior when the ORM is used normally - the Session object’s usual behavior of maintaining a transaction and expiring all attributes after rollback or commit handles object state automatically. This method is not intended for general use.


Apply the prefixes to the query and return the newly resulting Query.

Parameters:*prefixes – optional prefixes, typically strings, not using any commas. In particular is useful for MySQL keywords.


query = sess.query(\
    prefix_with('SQL_SMALL_RESULT', 'ALL')

Would render:

FROM users

New in version 0.7.7.


Return a new Query, where the “join point” has been reset back to the base FROM entities of the query.

This method is usually used in conjunction with the aliased=True feature of the join() method. See the example in join() for how this is used.


Return the first element of the first result or None if no rows present. If multiple rows are returned, raises MultipleResultsFound.

>>> session.query(Item).scalar()
>>> session.query(
>>> session.query( < 0).scalar()
>>> session.query(,
>>> session.query(func.count(

This results in an execution of the underlying query.


Set the FROM clause of this Query to a core selectable, applying it as a replacement FROM clause for corresponding mapped entities.

This method is similar to the Query.select_from() method, in that it sets the FROM clause of the query. However, where Query.select_from() only affects what is placed in the FROM, this method also applies the given selectable to replace the FROM which the selected entities would normally select from.

The given from_obj must be an instance of a FromClause, e.g. a select() or Alias construct.

An example would be a Query that selects User entities, but uses Query.select_entity_from() to have the entities selected from a select() construct instead of the base user table:

select_stmt = select([User]).where( == 7)

q = session.query(User).\
        filter( == 'ed')

The query generated will select User entities directly from the given select() construct, and will be:

SELECT AS anon_1_id, AS anon_1_name
FROM (SELECT "user".id AS id, "user".name AS name
FROM "user"
WHERE "user".id = :id_1) AS anon_1
WHERE = :name_1

Notice above that even the WHERE criterion was “adapted” such that the anon_1 subquery effectively replaces all references to the user table, except for the one that it refers to internally.

Compare this to Query.select_from(), which as of version 0.9, does not affect existing entities. The statement below:

q = session.query(User).\
        filter( == 'ed')

Produces SQL where both the user table as well as the select_stmt construct are present as separate elements in the FROM clause. No “adaptation” of the user table is applied:

SELECT "user".id AS user_id, "user".name AS user_name
FROM "user", (SELECT "user".id AS id, "user".name AS name
FROM "user"
WHERE "user".id = :id_1) AS anon_1
WHERE "user".name = :name_1

Query.select_entity_from() maintains an older behavior of Query.select_from(). In modern usage, similar results can also be achieved using aliased():

select_stmt = select([User]).where( == 7)
user_from_select = aliased(User, select_stmt.alias())

q = session.query(user_from_select)
Parameters:from_obj – a FromClause object that will replace the FROM clause of this Query.

New in version 0.8: Query.select_entity_from() was added to specify the specific behavior of entity replacement, however the Query.select_from() maintains this behavior as well until 0.9.


Set the FROM clause of this Query explicitly.

Query.select_from() is often used in conjunction with Query.join() in order to control which entity is selected from on the “left” side of the join.

The entity or selectable object here effectively replaces the “left edge” of any calls to join(), when no joinpoint is otherwise established - usually, the default “join point” is the leftmost entity in the Query object’s list of entities to be selected.

A typical example:

q = session.query(Address).select_from(User).\
    filter( == 'ed')

Which produces SQL equivalent to:

SELECT address.* FROM user
JOIN address ON
WHERE = :name_1
Parameters:*from_obj – collection of one or more entities to apply to the FROM clause. Entities can be mapped classes, AliasedClass objects, Mapper objects as well as core FromClause elements like subqueries.

Changed in version 0.9: This method no longer applies the given FROM object to be the selectable from which matching entities select from; the select_entity_from() method now accomplishes this. See that method for a description of this behavior.


Return the Select object emitted by this Query.

Used for inspect() compatibility, this is equivalent to:

slice(start, stop)

apply LIMIT/OFFSET to the Query based on a ” “range and return the newly resulting Query.


The full SELECT statement represented by this Query.

The statement by default will not have disambiguating labels applied to the construct unless with_labels(True) is called first.

subquery(name=None, with_labels=False, reduce_columns=False)

return the full SELECT statement represented by this Query, embedded within an Alias.

Eager JOIN generation within the query is disabled.

  • name – string name to be assigned as the alias; this is passed through to FromClause.alias(). If None, a name will be deterministically generated at compile time.
  • with_labels – if True, with_labels() will be called on the Query first to apply table-qualified labels to all columns.
  • reduce_columns

    if True, Select.reduce_columns() will be called on the resulting select() construct, to remove same-named columns where one also refers to the other via foreign key or WHERE clause equivalence.

    Changed in version 0.8: the with_labels and reduce_columns keyword arguments were added.


Apply the suffix to the query and return the newly resulting Query.

Parameters:*suffixes – optional suffixes, typically strings, not using any commas.

New in version 1.0.0.


Produce a UNION of this Query against one or more queries.


q1 = sess.query(SomeClass).filter('bar')
q2 = sess.query(SomeClass).filter('foo')

q3 = q1.union(q2)

The method accepts multiple Query objects so as to control the level of nesting. A series of union() calls such as:


will nest on each union(), and produces:

                SELECT * FROM y) UNION SELECT * FROM Z)


x.union(y, z).all()


                SELECT * FROM Z)

Note that many database backends do not allow ORDER BY to be rendered on a query called within UNION, EXCEPT, etc. To disable all ORDER BY clauses including those configured on mappers, issue query.order_by(None) - the resulting Query object will not render ORDER BY within its SELECT statement.


Produce a UNION ALL of this Query against one or more queries.

Works the same way as union(). See that method for usage examples.

update(values, synchronize_session='evaluate', update_args=None)

Perform a bulk update query.

Updates rows matched by this query in the database.


sess.query(User).filter(User.age == 25).\
    update({User.age: User.age - 10}, synchronize_session=False)

sess.query(User).filter(User.age == 25).\
    update({"age": User.age - 10}, synchronize_session='evaluate')


The Query.update() method is a “bulk” operation, which bypasses ORM unit-of-work automation in favor of greater performance. Please read all caveats and warnings below.

  • values

    a dictionary with attributes names, or alternatively mapped attributes or SQL expressions, as keys, and literal values or sql expressions as values.

    Changed in version 1.0.0: - string names in the values dictionary are now resolved against the mapped entity; previously, these strings were passed as literal column names with no mapper-level translation.

  • synchronize_session

    chooses the strategy to update the attributes on objects in the session. Valid values are:

    False - don’t synchronize the session. This option is the most efficient and is reliable once the session is expired, which typically occurs after a commit(), or explicitly using expire_all(). Before the expiration, updated objects may still remain in the session with stale values on their attributes, which can lead to confusing results.

    'fetch' - performs a select query before the update to find objects that are matched by the update query. The updated attributes are expired on matched objects.

    'evaluate' - Evaluate the Query’s criteria in Python straight on the objects in the session. If evaluation of the criteria isn’t implemented, an exception is raised.

    The expression evaluator currently doesn’t account for differing string collations between the database and Python.

  • update_args

    Optional dictionary, if present will be passed to the underlying update() construct as the **kw for the object. May be used to pass dialect-specific arguments such as mysql_limit.

    New in version 1.0.0.


the count of rows matched as returned by the database’s “row count” feature.


Additional Caveats for bulk query updates

  • The method does not offer in-Python cascading of relationships - it is assumed that ON UPDATE CASCADE is configured for any foreign key references which require it, otherwise the database may emit an integrity violation if foreign key references are being enforced.

    After the UPDATE, dependent objects in the Session which were impacted by an ON UPDATE CASCADE may not contain the current state; this issue is resolved once the Session is expired, which normally occurs upon Session.commit() or can be forced by using Session.expire_all().

  • The 'fetch' strategy results in an additional SELECT statement emitted and will significantly reduce performance.

  • The 'evaluate' strategy performs a scan of all matching objects within the Session; if the contents of the Session are expired, such as via a proceeding Session.commit() call, this will result in SELECT queries emitted for every matching object.

  • The method supports multiple table updates, as detailed in Multiple Table Updates, and this behavior does extend to support updates of joined-inheritance and other multiple table mappings. However, the join condition of an inheritance mapper is not automatically rendered. Care must be taken in any multiple-table update to explicitly include the joining condition between those tables, even in mappings where this is normally automatic. E.g. if a class Engineer subclasses Employee, an UPDATE of the Engineer local table using criteria against the Employee local table might look like:

        filter( ==\
        filter( == 'dilbert').\
        update({"engineer_type": "programmer"})
  • The MapperEvents.before_update() and MapperEvents.after_update() events are not invoked from this method. Instead, the SessionEvents.after_bulk_update() method is provided to act upon a mass UPDATE of entity rows.

See also


Inserts, Updates and Deletes - Core SQL tutorial


Return a scalar result corresponding to the given column expression.


Return an iterator yielding result tuples corresponding to the given list of columns


A readonly attribute which returns the current WHERE criterion for this Query.

This returned value is a SQL expression construct, or None if no criterion has been established.


Return a new Query replacing the SELECT list with the given entities.


# Users, filtered on some arbitrary criterion
# and then ordered by related email address
q = session.query(User).\

# given *only*,, and 'q', what
# would the *next* User in the result be ?
subq = q.with_entities(\
q = q.join((subq, <\

New in version 0.6.5.

with_for_update(read=False, nowait=False, of=None)

return a new Query with the specified options for the FOR UPDATE clause.

The behavior of this method is identical to that of SelectBase.with_for_update(). When called with no arguments, the resulting SELECT statement will have a FOR UPDATE clause appended. When additional arguments are specified, backend-specific options such as FOR UPDATE NOWAIT or LOCK IN SHARE MODE can take effect.


q = sess.query(User).with_for_update(nowait=True, of=User)

The above query on a Postgresql backend will render like:


New in version 0.9.0: Query.with_for_update() supersedes the Query.with_lockmode() method.

See also

GenerativeSelect.with_for_update() - Core level method with full argument and behavioral description.

with_hint(selectable, text, dialect_name='*')

Add an indexing or other executional context hint for the given entity or selectable to this Query.

Functionality is passed straight through to with_hint(), with the addition that selectable can be a Table, Alias, or ORM entity / mapped class /etc.


Apply column labels to the return value of Query.statement.

Indicates that this Query’s statement accessor should return a SELECT statement that applies labels to all columns in the form <tablename>_<columnname>; this is commonly used to disambiguate columns from multiple tables which have the same name.

When the Query actually issues SQL to load rows, it always uses column labeling.


The Query.with_labels() method only applies the output of Query.statement, and not to any of the result-row invoking systems of Query itself, e.g. Query.first(), Query.all(), etc. To execute a query using Query.with_labels(), invoke the Query.statement using Session.execute():

result = session.execute(query.with_labels().statement)

Return a new Query object with the specified “locking mode”, which essentially refers to the FOR UPDATE clause.

Deprecated since version 0.9.0: superseded by Query.with_for_update().


a string representing the desired locking mode. Valid values are:

  • None - translates to no lockmode
  • 'update' - translates to FOR UPDATE (standard SQL, supported by most dialects)
  • 'update_nowait' - translates to FOR UPDATE NOWAIT (supported by Oracle, PostgreSQL 8.1 upwards)
  • 'read' - translates to LOCK IN SHARE MODE (for MySQL), and FOR SHARE (for PostgreSQL)

See also

Query.with_for_update() - improved API for specifying the FOR UPDATE clause.

with_parent(instance, property=None)

Add filtering criterion that relates the given instance to a child object or collection, using its attribute state as well as an established relationship() configuration.

The method uses the with_parent() function to generate the clause, the result of which is passed to Query.filter().

Parameters are the same as with_parent(), with the exception that the given property can be None, in which case a search is performed against this Query object’s target mapper.

with_polymorphic(cls_or_mappers, selectable=None, polymorphic_on=None)

Load columns for inheriting classes.

Query.with_polymorphic() applies transformations to the “main” mapped class represented by this Query. The “main” mapped class here means the Query object’s first argument is a full class, i.e. session.query(SomeClass). These transformations allow additional tables to be present in the FROM clause so that columns for a joined-inheritance subclass are available in the query, both for the purposes of load-time efficiency as well as the ability to use these columns at query time.

See the documentation section Basic Control of Which Tables are Queried for details on how this method is used.

Changed in version 0.8: A new and more flexible function orm.with_polymorphic() supersedes Query.with_polymorphic(), as it can apply the equivalent functionality to any set of columns or classes in the Query, not just the “zero mapper”. See that function for a description of arguments.


Return a Query that will use the given Session.

with_statement_hint(text, dialect_name='*')

add a statement hint to this Select.

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

This feature calls down into Select.with_statement_hint().

New in version 1.0.0.


Return a new Query object transformed by the given function.


def filter_something(criterion):
    def transform(q):
        return q.filter(criterion)
    return transform

q = q.with_transformation(filter_something(x==5))

This allows ad-hoc recipes to be created for Query objects. See the example at Building Transformers.

New in version 0.7.4.


Yield only count rows at a time.

The purpose of this method is when fetching very large result sets (> 10K rows), to batch results in sub-collections and yield them out partially, so that the Python interpreter doesn’t need to declare very large areas of memory which is both time consuming and leads to excessive memory use. The performance from fetching hundreds of thousands of rows can often double when a suitable yield-per setting (e.g. approximately 1000) is used, even with DBAPIs that buffer rows (which are most).

The Query.yield_per() method is not compatible with most eager loading schemes, including subqueryload and joinedload with collections. For this reason, it may be helpful to disable eager loads, either unconditionally with Query.enable_eagerloads():

q = sess.query(Object).yield_per(100).enable_eagerloads(False)

Or more selectively using lazyload(); such as with an asterisk to specify the default loader scheme:

q = sess.query(Object).yield_per(100).\
    options(lazyload('*'), joinedload(Object.some_related))


Use this method with caution; if the same instance is present in more than one batch of rows, end-user changes to attributes will be overwritten.

In particular, it’s usually impossible to use this setting with eagerly loaded collections (i.e. any lazy=’joined’ or ‘subquery’) since those collections will be cleared for a new load when encountered in a subsequent result batch. In the case of ‘subquery’ loading, the full result for all rows is fetched which generally defeats the purpose of yield_per().

Also note that while yield_per() will set the stream_results execution option to True, currently this is only understood by psycopg2 dialect which will stream results using server side cursors instead of pre-buffer all rows for this query. Other DBAPIs pre-buffer all rows before making them available. The memory use of raw database rows is much less than that of an ORM-mapped object, but should still be taken into consideration when benchmarking.

ORM-Specific Query Constructs

sqlalchemy.orm.aliased(element, alias=None, name=None, flat=False, adapt_on_names=False)

Produce an alias of the given element, usually an AliasedClass instance.


my_alias = aliased(MyClass)

session.query(MyClass, my_alias).filter( >

The aliased() function is used to create an ad-hoc mapping of a mapped class to a new selectable. By default, a selectable is generated from the normally mapped selectable (typically a Table) using the FromClause.alias() method. However, aliased() can also be used to link the class to a new select() statement. Also, the with_polymorphic() function is a variant of aliased() that is intended to specify a so-called “polymorphic selectable”, that corresponds to the union of several joined-inheritance subclasses at once.

For convenience, the aliased() function also accepts plain FromClause constructs, such as a Table or select() construct. In those cases, the FromClause.alias() method is called on the object and the new Alias object returned. The returned Alias is not ORM-mapped in this case.

  • element – element to be aliased. Is normally a mapped class, but for convenience can also be a FromClause element.
  • alias – Optional selectable unit to map the element to. This should normally be a Alias object corresponding to the Table to which the class is mapped, or to a select() construct that is compatible with the mapping. By default, a simple anonymous alias of the mapped table is generated.
  • name – optional string name to use for the alias, if not specified by the alias parameter. The name, among other things, forms the attribute name that will be accessible via tuples returned by a Query object.
  • flat

    Boolean, will be passed through to the FromClause.alias() call so that aliases of Join objects don’t include an enclosing SELECT. This can lead to more efficient queries in many circumstances. A JOIN against a nested JOIN will be rewritten as a JOIN against an aliased SELECT subquery on backends that don’t support this syntax.

    New in version 0.9.0.

    See also


  • adapt_on_names

    if True, more liberal “matching” will be used when mapping the mapped columns of the ORM entity to those of the given selectable - a name-based match will be performed if the given selectable doesn’t otherwise have a column that corresponds to one on the entity. The use case for this is when associating an entity with some derived selectable such as one that uses aggregate functions:

    class UnitPrice(Base):
        __tablename__ = 'unit_price'
        unit_id = Column(Integer)
        price = Column(Numeric)
    aggregated_unit_price = Session.query(
    aggregated_unit_price = aliased(UnitPrice,
                alias=aggregated_unit_price, adapt_on_names=True)

    Above, functions on aggregated_unit_price which refer to .price will return the fund.sum(UnitPrice.price).label('price') column, as it is matched on the name “price”. Ordinarily, the “price” function wouldn’t have any “column correspondence” to the actual UnitPrice.price column as it is not a proxy of the original.

    New in version 0.7.3.

class sqlalchemy.orm.util.AliasedClass(cls, alias=None, name=None, flat=False, adapt_on_names=False, with_polymorphic_mappers=(), with_polymorphic_discriminator=None, base_alias=None, use_mapper_path=False)

Represents an “aliased” form of a mapped class for usage with Query.

The ORM equivalent of a sqlalchemy.sql.expression.alias() construct, this object mimics the mapped class using a __getattr__ scheme and maintains a reference to a real Alias object.

Usage is via the orm.aliased() function, or alternatively via the orm.with_polymorphic() function.

Usage example:

# find all pairs of users with the same name
user_alias = aliased(User)
session.query(User, user_alias).\
                join((user_alias, >\

The resulting object is an instance of AliasedClass. This object implements an attribute scheme which produces the same attribute and method interface as the original mapped class, allowing AliasedClass to be compatible with any attribute technique which works on the original class, including hybrid attributes (see Hybrid Attributes).

The AliasedClass can be inspected for its underlying Mapper, aliased selectable, and other information using inspect():

from sqlalchemy import inspect
my_alias = aliased(MyClass)
insp = inspect(my_alias)

The resulting inspection object is an instance of AliasedInsp.

See aliased() and with_polymorphic() for construction argument descriptions.

class sqlalchemy.orm.util.AliasedInsp(entity, mapper, selectable, name, with_polymorphic_mappers, polymorphic_on, _base_alias, _use_mapper_path, adapt_on_names)

Bases: sqlalchemy.orm.base.InspectionAttr

Provide an inspection interface for an AliasedClass object.

The AliasedInsp object is returned given an AliasedClass using the inspect() function:

from sqlalchemy import inspect
from sqlalchemy.orm import aliased

my_alias = aliased(MyMappedClass)
insp = inspect(my_alias)

Attributes on AliasedInsp include:

  • entity - the AliasedClass represented.
  • mapper - the Mapper mapping the underlying class.
  • selectable - the Alias construct which ultimately represents an aliased Table or Select construct.
  • name - the name of the alias. Also is used as the attribute name when returned in a result tuple from Query.
  • with_polymorphic_mappers - collection of Mapper objects indicating all those mappers expressed in the select construct for the AliasedClass.
  • polymorphic_on - an alternate column or SQL expression which will be used as the “discriminator” for a polymorphic load.
class sqlalchemy.orm.query.Bundle(name, *exprs, **kw)

Bases: sqlalchemy.orm.base.InspectionAttr

A grouping of SQL expressions that are returned by a Query under one namespace.

The Bundle essentially allows nesting of the tuple-based results returned by a column-oriented Query object. It also is extensible via simple subclassing, where the primary capability to override is that of how the set of expressions should be returned, allowing post-processing as well as custom return types, without involving ORM identity-mapped classes.

New in version 0.9.0.

See also

Column Bundles

__init__(name, *exprs, **kw)

Construct a new Bundle.


bn = Bundle("mybundle", MyClass.x, MyClass.y)

for row in session.query(bn).filter(
        bn.c.x == 5).filter(bn.c.y == 4):
    print(row.mybundle.x, row.mybundle.y)
  • name – name of the bundle.
  • *exprs – columns or SQL expressions comprising the bundle.
  • single_entity=False – if True, rows for this Bundle can be returned as a “single entity” outside of any enclosing tuple in the same manner as a mapped entity.
c = None

An alias for Bundle.columns.

columns = None

A namespace of SQL expressions referred to by this Bundle.


bn = Bundle("mybundle", MyClass.x, MyClass.y)

q = sess.query(bn).filter(bn.c.x == 5)

Nesting of bundles is also supported:

b1 = Bundle("b1",
        Bundle('b2', MyClass.a, MyClass.b),
        Bundle('b3', MyClass.x, MyClass.y)

q = sess.query(b1).filter(
    b1.c.b2.c.a == 5).filter(b1.c.b3.c.y == 9)

See also


create_row_processor(query, procs, labels)

Produce the “row processing” function for this Bundle.

May be overridden by subclasses.

See also

Column Bundles - includes an example of subclassing.


Provide a copy of this Bundle passing a new label.

single_entity = False

If True, queries for a single Bundle will be returned as a single entity, rather than an element within a keyed tuple.

class sqlalchemy.util.KeyedTuple

Bases: sqlalchemy.util._collections.AbstractKeyedTuple

tuple subclass that adds labeled names.


>>> k = KeyedTuple([1, 2, 3], labels=["one", "two", "three"])
>>> k.two

Result rows returned by Query that contain multiple ORM entities and/or column expressions make use of this class to return rows.

The KeyedTuple exhibits similar behavior to the collections.namedtuple() construct provided in the Python standard library, however is architected very differently. Unlike collections.namedtuple(), KeyedTuple is does not rely on creation of custom subtypes in order to represent a new series of keys, instead each KeyedTuple instance receives its list of keys in place. The subtype approach of collections.namedtuple() introduces significant complexity and performance overhead, which is not necessary for the Query object’s use case.

Changed in version 0.8: Compatibility methods with collections.namedtuple() have been added including KeyedTuple._fields and KeyedTuple._asdict().

See also



Return the contents of this KeyedTuple as a dictionary.

This method provides compatibility with collections.namedtuple(), with the exception that the dictionary returned is not ordered.

New in version 0.8.


Return a tuple of string key names for this KeyedTuple.

This method provides compatibility with collections.namedtuple().

New in version 0.8.


Return a list of string key names for this KeyedTuple.

class sqlalchemy.orm.strategy_options.Load(entity)

Bases: sqlalchemy.sql.expression.Generative, sqlalchemy.orm.interfaces.MapperOption

Represents loader options which modify the state of a Query in order to affect how various mapped attributes are loaded.

New in version 0.9.0: The Load() system is a new foundation for the existing system of loader options, including options such as orm.joinedload(), orm.defer(), and others. In particular, it introduces a new method-chained system that replaces the need for dot-separated paths as well as “_all()” options such as orm.joinedload_all().

A Load object can be used directly or indirectly. To use one directly, instantiate given the parent class. This style of usage is useful when dealing with a Query that has multiple entities, or when producing a loader option that can be applied generically to any style of query:

myopt = Load(MyClass).joinedload("widgets")

The above myopt can now be used with Query.options():


The Load construct is invoked indirectly whenever one makes use of the various loader options that are present in sqlalchemy.orm, including options such as orm.joinedload(), orm.defer(), orm.subqueryload(), and all the rest. These constructs produce an “anonymous” form of the Load object which tracks attributes and options, but is not linked to a parent class until it is associated with a parent Query:

# produce "unbound" Load object
myopt = joinedload("widgets")

# when applied using options(), the option is "bound" to the
# class observed in the given query, e.g. MyClass

Whether the direct or indirect style is used, the Load object returned now represents a specific “path” along the entities of a Query. This path can be traversed using a standard method-chaining approach. Supposing a class hierarchy such as User, User.addresses -> Address, User.orders -> Order and Order.items -> Item, we can specify a variety of loader options along each element in the “path”:


Where above, the addresses collection will be joined-loaded, the orders collection will be subquery-loaded, and within that subquery load the items collection will be joined-loaded.

baked_lazyload(loadopt, attr)

Produce a new Load object with the orm.baked_lazyload() option applied.

See orm.baked_lazyload() for usage examples.

contains_eager(loadopt, attr, alias=None)

Produce a new Load object with the orm.contains_eager() option applied.

See orm.contains_eager() for usage examples.

defaultload(loadopt, attr)

Produce a new Load object with the orm.defaultload() option applied.

See orm.defaultload() for usage examples.

defer(loadopt, key)

Produce a new Load object with the orm.defer() option applied.

See orm.defer() for usage examples.

immediateload(loadopt, attr)

Produce a new Load object with the orm.immediateload() option applied.

See orm.immediateload() for usage examples.

joinedload(loadopt, attr, innerjoin=None)

Produce a new Load object with the orm.joinedload() option applied.

See orm.joinedload() for usage examples.

lazyload(loadopt, attr)

Produce a new Load object with the orm.lazyload() option applied.

See orm.lazyload() for usage examples.

load_only(loadopt, *attrs)

Produce a new Load object with the orm.load_only() option applied.

See orm.load_only() for usage examples.

noload(loadopt, attr)

Produce a new Load object with the orm.noload() option applied.

See orm.noload() for usage examples.

subqueryload(loadopt, attr)

Produce a new Load object with the orm.subqueryload() option applied.

See orm.subqueryload() for usage examples.

undefer(loadopt, key)

Produce a new Load object with the orm.undefer() option applied.

See orm.undefer() for usage examples.

undefer_group(loadopt, name)

Produce a new Load object with the orm.undefer_group() option applied.

See orm.undefer_group() for usage examples.

sqlalchemy.orm.join(left, right, onclause=None, isouter=False, join_to_left=None)

Produce an inner join between left and right clauses.

orm.join() is an extension to the core join interface provided by sql.expression.join(), where the left and right selectables may be not only core selectable objects such as Table, but also mapped classes or AliasedClass instances. The “on” clause can be a SQL expression, or an attribute or string name referencing a configured relationship().

orm.join() is not commonly needed in modern usage, as its functionality is encapsulated within that of the Query.join() method, which features a significant amount of automation beyond orm.join() by itself. Explicit usage of orm.join() with Query involves usage of the Query.select_from() method, as in:

from sqlalchemy.orm import join
    select_from(join(User, Address, User.addresses)).\

In modern SQLAlchemy the above join can be written more succinctly as:


See Query.join() for information on modern usage of ORM level joins.

Changed in version 0.8.1: - the join_to_left parameter is no longer used, and is deprecated.

sqlalchemy.orm.outerjoin(left, right, onclause=None, join_to_left=None)

Produce a left outer join between left and right clauses.

This is the “outer join” version of the orm.join() function, featuring the same behavior except that an OUTER JOIN is generated. See that function’s documentation for other usage details.

sqlalchemy.orm.with_parent(instance, prop)

Create filtering criterion that relates this query’s primary entity to the given related instance, using established relationship() configuration.

The SQL rendered is the same as that rendered when a lazy loader would fire off from the given parent on that attribute, meaning that the appropriate state is taken from the parent object in Python without the need to render joins to the parent table in the rendered statement.

Changed in version 0.6.4: This method accepts parent instances in all persistence states, including transient, persistent, and detached. Only the requisite primary key/foreign key attributes need to be populated. Previous versions didn’t work with transient instances.

  • instance – An instance which has some relationship().
  • property – String property name, or class-bound attribute, which indicates what relationship from the instance should be used to reconcile the parent/child relationship.