logo

Extra Block Types (EBT) - New Layout Builder experience❗

Extra Block Types (EBT) - styled, customizable block types: Slideshows, Tabs, Cards, Accordions and many others. Built-in settings for background, DOM Box, javascript plugins. Experience the future of layout building today.

Demo EBT modules Download EBT modules

❗Extra Paragraph Types (EPT) - New Paragraphs experience

Extra Paragraph Types (EPT) - analogical paragraph based set of modules.

Demo EPT modules Download EPT modules

Scroll
12/04/2025, by Ivan

To group by a given field, use the groupBy() method.

$query->groupBy('uid');

The code above instructs the query to group by the uid field. Note that the field name here must be the alias created by the addField() or addExpression() methods, so in most cases you will want to use the return value from those methods to ensure the correct alias is used.

To get the count of rows grouped by a field, such as uid, you can do the following:

$query->addExpression('count(uid)', 'uid_node_count');

To group by multiple fields, simply call groupBy() several times in the desired order.

Having

You can add a condition on aggregated values.

$query->having('COUNT(uid) >= :matches', [':matches' => $limit]);

In this example, it will find cases where the number of uid identifiers is greater than or equal to $limit. Note that the first parameter of having is not filtered before being sent to the database, so user values must be passed through the second parameter.

Examples of groupBy and having

The following code counts the number of nodes per UID:

$query = $connection->select('node', 'n')
  ->fields('n', ['uid']);
$query->addExpression('count(uid)', 'uid_node_count');
$query->groupBy("n.uid");
$query->execute();

The following block of code takes the previous example of counting nodes per uid and restricts the results to uids that have at least 2 records.

$query = $connection->select('node', 'n')
    ->fields('n',['uid']);
$query->addExpression('count(uid)', 'uid_node_count');
$query->groupBy("n.uid");
$query->having('COUNT(uid) >= :matches', [':matches' => 2]);
$results = $query->execute();