Can a database query be written inside a template.php file? I am writing a query inside the following function of template.php file

        function theme_name_process_views_view_field(&amp;$vars) { 
 if ($vars['view']-&gt;name == 'view_name') { 
// query is written here
      foreach( $vars['view']-&gt;result as $key =&gt; $value ) {
          $nid = $value-&gt;nid;
          $query = db_select('abc_in', 'abc')
            -&gt;fields('abc', array('study_abc'))
            -&gt;condition('abc_nid', $nid , '=');
          $result =   $query-&gt;execute()-&gt;fetchField();
        $vars['view']-&gt;result[$key]-&gt;field_field_abc_in[0]['rendered']['#markup'] = "&lt;div class='abc_code'&gt;" .  $result . "&lt;/div&gt;" ;

    } }


Is it ok to write a db_query inside template.php file ?
I an taking a data from custom table and inserting value into field of a view ?
You can definitely do it, however you really shouldn't.

The theme layer is for presenting the data.
The actual functionality and the data itself should come from modules.

If you mention what you are trying to do I can give some more information on where it should go instead

Edit

Based on your code example, if you are dealing with a custom data table the best thing would be to use hook_views_data() to let views know about your database table and fields. Then you would just use your new fields via the UI.

If you didn't want to go to that much trouble though you could use basically the same solution as you are using now in a custom module in one of the views hooks, like hook_views_post_execute(), where you can loop through the results in a similar fashion as you are doing now.

You generally wouldn't be dealing with markup here though (like your abc_code div). You're really only changing data here and then changing markup in the theme. Although your field should already have classes that let you specifically style it so adding that class probably shouldn't be necessary.