Produce a UNION of this Query against one or more queries. e.g.:: q1 = sess.query(SomeClass).filter(SomeClass.foo == "bar") q2 = sess.query(SomeClass).filter(SomeClass.bar == "foo") q3 = q1.union(q2) The method accepts multiple Query objects so
(self, *q: Query[Any])
| 2156 | return self._from_selectable(expr_fn(*(list_of_queries)).subquery()) |
| 2157 | |
| 2158 | def union(self, *q: Query[Any]) -> Self: |
| 2159 | """Produce a UNION of this Query against one or more queries. |
| 2160 | |
| 2161 | e.g.:: |
| 2162 | |
| 2163 | q1 = sess.query(SomeClass).filter(SomeClass.foo == "bar") |
| 2164 | q2 = sess.query(SomeClass).filter(SomeClass.bar == "foo") |
| 2165 | |
| 2166 | q3 = q1.union(q2) |
| 2167 | |
| 2168 | The method accepts multiple Query objects so as to control |
| 2169 | the level of nesting. A series of ``union()`` calls such as:: |
| 2170 | |
| 2171 | x.union(y).union(z).all() |
| 2172 | |
| 2173 | will nest on each ``union()``, and produces: |
| 2174 | |
| 2175 | .. sourcecode:: sql |
| 2176 | |
| 2177 | SELECT * FROM (SELECT * FROM (SELECT * FROM X UNION |
| 2178 | SELECT * FROM y) UNION SELECT * FROM Z) |
| 2179 | |
| 2180 | Whereas:: |
| 2181 | |
| 2182 | x.union(y, z).all() |
| 2183 | |
| 2184 | produces: |
| 2185 | |
| 2186 | .. sourcecode:: sql |
| 2187 | |
| 2188 | SELECT * FROM (SELECT * FROM X UNION SELECT * FROM y UNION |
| 2189 | SELECT * FROM Z) |
| 2190 | |
| 2191 | Note that many database backends do not allow ORDER BY to |
| 2192 | be rendered on a query called within UNION, EXCEPT, etc. |
| 2193 | To disable all ORDER BY clauses including those configured |
| 2194 | on mappers, issue ``query.order_by(None)`` - the resulting |
| 2195 | :class:`_query.Query` object will not render ORDER BY within |
| 2196 | its SELECT statement. |
| 2197 | |
| 2198 | .. seealso:: |
| 2199 | |
| 2200 | :meth:`_sql.Select.union` - v2 equivalent method. |
| 2201 | |
| 2202 | """ |
| 2203 | return self._set_op(expression.union, *q) |
| 2204 | |
| 2205 | def union_all(self, *q: Query[Any]) -> Self: |
| 2206 | """Produce a UNION ALL of this Query against one or more queries. |
no test coverage detected