[Drupal Views] How to view the SQL query executed by a View?

| | 2 min read

While working on Drupal Views, we might want to examine the query executed by the View to get its data. Analyzing the query may help us to identify why the view does not produce expected result. Read on to know how to view the SQL query executed by a View.

You need a patch that can be applied temporarily to views_plugin_query_default.inc file of the view module.

--- a/sites/all/modules/views/plugins/views_plugin_query_default.inc
+++ b/sites/all/modules/views/plugins/views_plugin_query_default.inc
@@ -1393,6 +1393,19 @@ class views_plugin_query_default extends views_plugin_query {
           $query->range($offset, $limit);
         }

+        $query_string = (string)$query;
+        $query_string = str_replace('{', '', $query_string);
+        $query_string = str_replace('}', '', $query_string);
+        $query_params = $query->getArguments();
+        foreach($query_params as $placeholder => $value) {
+          if(!is_numeric($value)) {
+            $query_string = str_replace($placeholder, "'$value'", $query_string);
+          }
+          else {
+            $query_string = str_replace($placeholder, $value, $query_string);
+          }
+        }
+        drupal_set_message($query_string);
         $result = $query->execute();

         $view->result = array();

Now if you run your view page you will get the query as a message. The advantage with this custom logic is that it does not require you to install any other module. Moreover you can copy and paste the output directly to the MySQL terminal or phpMyAdmin box and execute the query.

Sure, we can use dpq() here instead of this custom logic. But dpq() does not remove the curly braces in the query. We will have to remove the curly braces before we execute the query within our favorite SQL terminal.

Hope this article was helpful. We would love to hear your feedback regarding the comments form below.