How do I return an SQL query result as custom variable in a template?
You can add variables using a hook_preprocess_THEME() function. For example, if you are trying to add a variable to the page.html.twig template, the theme hook is page. So you would use the following:

function hook_preprocess_page(&amp;$vars)
{
  // Add your result to the $vars array:
  $vars['some_variable'] = db_query('SELECT something FROM {some_table} WHERE some_column = :some_value', [':some_value' =&gt; 'some value'])-&gt;fetchField();
}


Because you've added some_variable to the $vars array, some_variable will be available in your template.