How to get count on how many times a term is used on a node I'm about to create a Tag cloud module that shall have a block showing a list of all terms. The most used terms shall be in big text; the terms that not used often shall be in small text, as in the following screenshot.

I want to have a $count variable that holds the count of how many times each term is used.

I think that I can do so:

$database = \Drupal::database();
$terms_count = $database
-&gt;query('SELECT COUNT(tid) FROM {taxonomy_index}')
-&gt;execute();

foreach($terms_count as $term_count) {
  print $term_count;
}


But it doesn't show anything.
Here's the query you're going for.

SELECT count(*) AS count, tid FROM taxonomy_index GROUP BY tid ORDER BY count DESC LIMIT 100;


You'll need to use AddExpression to get the count in there.  

$query = $this-&gt;database-&gt;select('taxonomy_index', 'ti');
$query-&gt;addField('ti', 'tid', 'tid');

$query-&gt;addExpression("count(*)", 'count');
$query-&gt;groupBy('ti.tid');
$query-&gt;orderBy('count', 'DESC');
$query-&gt;range(0, 50);

$data = $raw_data = $query-&gt;execute()-&gt;fetchAll();


Here's how you might convert the data to a render array:

$term_storage = \Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term');

$build = [];
foreach ($data as $count_group) {
  $term = $term_storage-&gt;load($count_group-&gt;tid);
  $label = $term-&gt;label();
  $link = $term-&gt;toLink();
  $link-&gt;setText($this-&gt;t($label . ' (' . $count_group-&gt;count . ')'));
  $build[] = $link-&gt;toRenderable();
}

return $build;