How to remove view results duplicates programmatically?

| | 1 min read

"My Drupal 7 view result is displaying a few records multiple times. How can I get rid of these duplicates?". The immediate solution that comes to our mind will be applying GROUP BY or DISTINCT by enabling views aggregation settings and simply remove the duplicate records.

To be little more specific, here are the steps:

  • Step 1. Go and edit your View
  • Step 2. Go to Advanced » OTHER section and enable Use aggregation: Yes
  • Step 3. Go to FIELDS or FILTER CRITERIA section, select and apply Aggregation settings for which fields you want to group by or distinct.

"I already checked the distinct option in the Query settings but that also does not work. Is there any other way to remove the duplicates?". Yes! Using hook_query_alter().

Here is a sample code:

function mymodule_views_query_alter(&$view, &$query) {

  // Term id's to unset from result set.
  $tids = array(368,346,351,355,358,365);

  if (($view->name == 'yourviewname') && 'page' == $view->current_display) {
    $query->add_where(1,'taxonomy_term_data_node.tid', $tids, 'NOT IN');
  }
}

Did this solve your issue? Keep us posted.