Drupal 7 – How to Modify a Views Query in a Custom Module
To modify or alter a drupal view query, follow the below steps. Views are brilliant piece of functionality that can be added to drupal via a module.
Navigate to sites/all/modules/yourmodule and create your module.info file, to inform our module is ready to install on the system.
Declare hook_views_api, as this is required for your module to have its include files loaded.
Write your alter hook, hook_views_query_alter as a next function. This is your main area as here you have to work a bit. Make sure that you are using correct machine name for the view. There is a trick for this, just examine the URL of the view will something like this admin/structure/views/view/oa_fullcalendar/edit. So oa_fullcalendar is my view name.
In this example, I’ve tried to change the order by clause i n the view query. You can use Devel module to debug further in Drupal