Answers.Body: <p>When you call the |length twig filter you are implicitly treating the element query as an array. 
  This behaviour was depreciated in Craft 3, and also results in a DB query being sent that is equivalent to .count() (Craft 3) or .total() (Craft 2).</p>
  
  <p>To remain up to date, while still minimising SQL load for your page: either call the relevant command (.count(), .total()):</p>
  
  <pre><code>{% set productCount = craft.products.relatedTo(category).count() %}
  </code></pre>
  
  <p>Or, if you're going to be doing a full (limit: null) query at some point anyway, do that now and then use the length filter:</p>
  
  <pre><code>{% set products = craft.products.relatedTo(category).limit(null).all() %}
  {% set productCount = products|length %}
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-03-02T10:11:45.263Z
Answers.Text: Thanks for the explanation Nick.
Answers.UserDisplayName: nitech
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-02-28T17:20:01.107Z
Answers.LastActivityDate: 2020-02-28T17:20:01.107Z
Answers.UserDisplayName: Nick
Body: <p>Which is the least CPU intensive (SQL-intensive) way to get the sum of products that are <code>relatedTo</code> a category? </p>
  
  <p>Like this?</p>
  
  <p><code>{% set productCount = craft.products.relatedTo(category)|length %}</code></p>
  
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2020-02-28T16:47:11.737Z
Comments.Text: As far as I am aware, yes.
Comments.UserDisplayName: Darryl Hardin
Tags: <templating><sql>
Title: Least CPU intensive way to get number of matching elements?
ThreadText: # Least CPU intensive way to get number of matching elements?
  
  (Asked by: username_0 on 2020-02-28)
  
  Which is the least CPU intensive (SQL-intensive) way to get the sum of products that are `relatedTo` a category?
  
  Like this?
  
  `{% set productCount = craft.products.relatedTo(category)|length %}`
  
  **Tags:** templating, sql
  
  > **Comments:**
  > **username_1**: As far as I am aware, yes.  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_2 on 2020-02-28. Score: 3 | Accepted answer
  
  When you call the |length twig filter you are implicitly treating the element query as an array.
  This behaviour was depreciated in Craft 3, and also results in a DB query being sent that is equivalent to .count() (Craft 3) or .total() (Craft 2).
  
  To remain up to date, while still minimising SQL load for your page: either call the relevant command (.count(), .total()):
  
  ```
  {% set productCount = craft.products.relatedTo(category).count() %}
  
  ```
  
  Or, if you're going to be doing a full (limit: null) query at some point anyway, do that now and then use the length filter:
  
  ```
  {% set products = craft.products.relatedTo(category).limit(null).all() %}
  {% set productCount = products|length %}
  
  ```
  
  > **Comments:**
  > **username_0**: Thanks for the explanation username_2.  
  
  ---
  
  