Unexpected results while using HAVING without GROUP BY
This is not valid SQL - even though MariaDB and MySQL (until version 5.6) allow it:

having budget &gt; avg(budget)


So, if you get unexpected results, don't worry much. Just do not use invalid SQL syntax ;) If you are not sure what syntax is valid and what not, you can add ONLY_FULL_GROUP_BY to the SQL mode setting and you'll get errors instead of unexpected / inconsistent results.

What is actually happening in the query:

select * 
from department 
having budget &gt; avg(budget);


Whenever there is an aggregate function (SUM(), COUNT(), AVG()) either in the SELECT list or in HAVING condition, a GROUP BY the whole set is implied. So the query is equivalent to:

select dept_name, building, budget
from department 
group by ()
having budget &gt; avg(budget);


This means the whole set has to be collapsed in a single row and only aggregate expressions should be allowed, not columns. So the whole SELECT list is invalid (all 3 columns) and the budget in the HAVING condition. However, MySQL and MariaDB have allowed this since very early versions, for some efficiency optimization (in certain cases where it would not create inconsistent results).

In the specific case (or similar ones), that a dept_name, a building and a budget have to de displayed in the SELECT result, an arbitrary row is chosen and displayed. In more complicated cases, you can even see results from different rows, showing a department A with the budget from department B !

The same (arbitrary) budget value is used in the HAVING filter, giving the weird results you noticed.

A few more details can be found in MySQL's documentation: 


5.6 (old behaviour): MySQL Handling of GROUP BY
8.0 (current behaviour): MySQL Handling of GROUP BY




You first query is the right way to do it:

select * 
from department 
where budget &gt; (select avg(budget) from department);


Another way is to use window functions (available in both MariaDB and latest MySQL):

select *
from
  (
    select *,
           avg(budget) over () as avg_budget
    from department 
  ) as a
where budget &gt; avg_budget ;