How to Remove Duplicate Items in Drupal Views with Random Sort

If you are building a Drupal site and using Views to display content, you may have noticed a problem: when you use random sorting, sometimes the same content appears multiple times.

In this guide, we will explain in simple language how to eliminate duplicate items in Views when using random sort. Even if you are a fresher or a student, you can follow these steps easily.

What is the Problem?

When you create a View and choose Random as the sort option:

  • The database randomly selects rows.
  • If your content has multiple fields or relationships (like taxonomy terms, users), it can return the same content multiple times.
  • This leads to duplicates in the view result.

Why Do Duplicates Happen?

  1. Database Joins: If your view joins multiple tables, a single content item may appear more than once in the query.
  2. Random Sort: ORDER BY RAND() (MySQL) or ORDER BY RANDOM() (Postgres) may pick duplicate rows because the database doesn’t automatically enforce uniqueness.

How to Fix Duplicate Items

Here are easy solutions that work for beginners:

1. Enable Distinct in Views

  1. Go to your View → Advanced section.
  2. Find Query settings → Click Distinct.
  3. Save the View.

Result:
This ensures only unique rows are returned. Most duplicates are fixed with this option.

2. Use Aggregation

If Distinct does not work (sometimes with complex relationships):

  1. Go to View → Advanced → Enable Use aggregation.
  2. Group by Content: Nid (Node ID).

Result:
Database collapses duplicate rows into a single item.

3. Add a Unique Sort Identifier

Sometimes random sorting still causes duplicates:

  1. Add Content: Nid (or unique field) as a Sort criteria → ascending.
  2. Keep Global: Random as primary sort.

Result:
Random items are still selected, but duplicates are prevented.

4. Custom Query Alter (Advanced)

If none of the above works, you can use hook_views_query_alter() to force uniqueness:

function mymodule_views_query_alter(&$view, \Drupal\views\Query\QueryPluginBase $query) {
  if ($view->id() == 'my_random_view' && $view->current_display == 'page_1') {
    $query->addDistinct(TRUE);
  }
}

Only use this if you are comfortable with PHP. Beginners should try Distinct and Aggregation first.

Example: Show 5 Unique Random Articles

  1. Create a new view → Show Content → Filter Published content.
  2. Sort criteria → Global: Random.
  3. Advanced → Check Distinct.
  4. Pager → Display 5 items.

Now you will always get 5 unique random articles without duplicates.

Eliminating duplicates in Views with random sort is simple once you know the steps:

  • Enable Distinct.
  • Use Aggregation if needed.
  • Optionally, add unique sort criteria.
  • As a last resort, use custom query alter.

With these techniques, your Drupal site will show clean, unique content even when sorted randomly.