MCPcopy Create free account
hub / github.com/sqlalchemy/sqlalchemy / exists

Method exists

lib/sqlalchemy/orm/query.py:3037–3091  ·  view source on GitHub ↗

A convenience method that turns a query into an EXISTS subquery of the form EXISTS (SELECT 1 FROM ... WHERE ...). e.g.:: q = session.query(User).filter(User.name == "fred") session.query(q.exists()) Producing SQL similar to: .. sourcecode::

(self)

Source from the content-addressed store, hash-verified

3035 return loading.merge_result(self, iterator, load)
3036
3037 def exists(self) -> Exists:
3038 """A convenience method that turns a query into an EXISTS subquery
3039 of the form EXISTS (SELECT 1 FROM ... WHERE ...).
3040
3041 e.g.::
3042
3043 q = session.query(User).filter(User.name == "fred")
3044 session.query(q.exists())
3045
3046 Producing SQL similar to:
3047
3048 .. sourcecode:: sql
3049
3050 SELECT EXISTS (
3051 SELECT 1 FROM users WHERE users.name = :name_1
3052 ) AS anon_1
3053
3054 The EXISTS construct is usually used in the WHERE clause::
3055
3056 session.query(User.id).filter(q.exists()).scalar()
3057
3058 Note that some databases such as SQL Server don't allow an
3059 EXISTS expression to be present in the columns clause of a
3060 SELECT. To select a simple boolean value based on the exists
3061 as a WHERE, use :func:`.literal`::
3062
3063 from sqlalchemy import literal
3064
3065 session.query(literal(True)).filter(q.exists()).scalar()
3066
3067 .. seealso::
3068
3069 :meth:`_sql.Select.exists` - v2 comparable method.
3070
3071 """
3072
3073 # .add_columns() for the case that we are a query().select_from(X),
3074 # so that ".statement" can be produced (#2995) but also without
3075 # omitting the FROM clause from a query(X) (#2818);
3076 # .with_only_columns() after we have a core select() so that
3077 # we get just "SELECT 1" without any entities.
3078
3079 inner = (
3080 self.enable_eagerloads(False)
3081 .add_columns(sql.literal_column("1"))
3082 .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
3083 ._get_select_statement_only()
3084 .with_only_columns(1)
3085 )
3086
3087 ezero = self._entity_from_pre_ent_zero()
3088 if ezero is not None:
3089 inner = inner.select_from(ezero)
3090
3091 return sql.exists(inner)
3092
3093 def count(self) -> int:
3094 r"""Return a count of rows this the SQL formed by this :class:`Query`

Callers 8

_testsFunction · 0.45
disposeFunction · 0.45
_criterion_existsMethod · 0.45
pytest_configureFunction · 0.45
__init__Method · 0.45
environment.pyFile · 0.45
bootstrapFunction · 0.45

Calls 7

enable_eagerloadsMethod · 0.95
with_only_columnsMethod · 0.80
set_label_styleMethod · 0.45
add_columnsMethod · 0.45
select_fromMethod · 0.45

Tested by 1

pytest_configureFunction · 0.36