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)
| 3089 | return loading.merge_result(self, iterator, load) |
| 3090 | |
| 3091 | def exists(self) -> Exists: |
| 3092 | """A convenience method that turns a query into an EXISTS subquery |
| 3093 | of the form EXISTS (SELECT 1 FROM ... WHERE ...). |
| 3094 | |
| 3095 | e.g.:: |
| 3096 | |
| 3097 | q = session.query(User).filter(User.name == "fred") |
| 3098 | session.query(q.exists()) |
| 3099 | |
| 3100 | Producing SQL similar to: |
| 3101 | |
| 3102 | .. sourcecode:: sql |
| 3103 | |
| 3104 | SELECT EXISTS ( |
| 3105 | SELECT 1 FROM users WHERE users.name = :name_1 |
| 3106 | ) AS anon_1 |
| 3107 | |
| 3108 | The EXISTS construct is usually used in the WHERE clause:: |
| 3109 | |
| 3110 | session.query(User.id).filter(q.exists()).scalar() |
| 3111 | |
| 3112 | Note that some databases such as SQL Server don't allow an |
| 3113 | EXISTS expression to be present in the columns clause of a |
| 3114 | SELECT. To select a simple boolean value based on the exists |
| 3115 | as a WHERE, use :func:`.literal`:: |
| 3116 | |
| 3117 | from sqlalchemy import literal |
| 3118 | |
| 3119 | session.query(literal(True)).filter(q.exists()).scalar() |
| 3120 | |
| 3121 | .. seealso:: |
| 3122 | |
| 3123 | :meth:`_sql.Select.exists` - v2 comparable method. |
| 3124 | |
| 3125 | """ |
| 3126 | |
| 3127 | # .add_columns() for the case that we are a query().select_from(X), |
| 3128 | # so that ".statement" can be produced (#2995) but also without |
| 3129 | # omitting the FROM clause from a query(X) (#2818); |
| 3130 | # .with_only_columns() after we have a core select() so that |
| 3131 | # we get just "SELECT 1" without any entities. |
| 3132 | |
| 3133 | inner = ( |
| 3134 | self.enable_eagerloads(False) |
| 3135 | .add_columns(sql.literal_column("1")) |
| 3136 | .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) |
| 3137 | ._get_select_statement_only() |
| 3138 | .with_only_columns(1) |
| 3139 | ) |
| 3140 | |
| 3141 | ezero = self._entity_from_pre_ent_zero() |
| 3142 | if ezero is not None: |
| 3143 | inner = inner.select_from(ezero) |
| 3144 | |
| 3145 | return sql.exists(inner) |
| 3146 | |
| 3147 | def count(self) -> int: |
| 3148 | r"""Return a count of rows this the SQL formed by this :class:`Query` |