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

Method count

lib/sqlalchemy/orm/query.py:3093–3154  ·  view source on GitHub ↗

r"""Return a count of rows this the SQL formed by this :class:`Query` would return. This generates the SQL for this Query as follows: .. sourcecode:: sql SELECT count(1) AS count_1 FROM ( SELECT ) AS anon_1

(self)

Source from the content-addressed store, hash-verified

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`
3095 would return.
3096
3097 This generates the SQL for this Query as follows:
3098
3099 .. sourcecode:: sql
3100
3101 SELECT count(1) AS count_1 FROM (
3102 SELECT <rest of query follows...>
3103 ) AS anon_1
3104
3105 The above SQL returns a single row, which is the aggregate value
3106 of the count function; the :meth:`_query.Query.count`
3107 method then returns
3108 that single integer value.
3109
3110 .. warning::
3111
3112 It is important to note that the value returned by
3113 count() is **not the same as the number of ORM objects that this
3114 Query would return from a method such as the .all() method**.
3115 The :class:`_query.Query` object,
3116 when asked to return full entities,
3117 will **deduplicate entries based on primary key**, meaning if the
3118 same primary key value would appear in the results more than once,
3119 only one object of that primary key would be present. This does
3120 not apply to a query that is against individual columns.
3121
3122 .. seealso::
3123
3124 :ref:`faq_query_deduplicating`
3125
3126 For fine grained control over specific columns to count, to skip the
3127 usage of a subquery or otherwise control of the FROM clause, or to use
3128 other aggregate functions, use :attr:`~sqlalchemy.sql.expression.func`
3129 expressions in conjunction with :meth:`~.Session.query`, i.e.::
3130
3131 from sqlalchemy import func
3132
3133 # count User records, without
3134 # using a subquery.
3135 session.query(func.count(User.id))
3136
3137 # return count of user "id" grouped
3138 # by "name"
3139 session.query(func.count(User.id)).group_by(User.name)
3140
3141 from sqlalchemy import distinct
3142
3143 # count distinct "name" values
3144 session.query(func.count(distinct(User.name)))
3145
3146 .. seealso::
3147
3148 :ref:`migration_20_query_usage`
3149
3150 """

Callers 10

run_testMethod · 0.45
counterFunction · 0.45
check_winFunction · 0.45
check_loseFunction · 0.45
filter_public.pyFile · 0.45
nested_sets.pyFile · 0.45
test_external_idMethod · 0.45

Calls 3

_legacy_from_selfMethod · 0.95
enable_eagerloadsMethod · 0.80
scalarMethod · 0.45

Tested by 3

test_external_idMethod · 0.36