Module Development

Alter the Query Used for a View for Drupal 8, 9, 10, and 11

At its core, Views is a query generator. It provides a way for site builders and developers to construct queries for Drupal content using an intuitive user interface. The UI allows you to configure the fields, filters, sorting, and relationships in the generated query using common conditions. In most cases, this is sufficient. However, there are situations where you need to dynamically alter the constructed query using hook_views_query_alter() prior to its execution.

One example use case is adding sort parameters to a search view if no search terms have been entered. You can use hook_views_query_alter() to check if a search term was entered. If so, sort the result by relevance; and if there are no search terms, sort the results by date. Or maybe you need to dynamically set the value of a filter condition based on a calculation performed by your custom code.

Using hook_views_query_alter() in a custom module, you can alter the query that is generated by a view before the query is performed. In most cases this alters the SQL query used. This same technique will work regardless of the storage system Views is querying.

In this tutorial we'll:

  • Learn how to alter a view's query using the hook_views_query_alter() hook in Drupal
  • Use hook_views_query_alter() to dynamically add a new sort condition that could not be achieved using the UI

By the end of this tutorial you should know how to alter the database query used to retrieve the results for a view.