i dont understand why we can use WHERE clause with date functions. For instance lets take
SELECT name FROM table1
WHERE DATEDIFF(year1,year2) < 10;
And its working. I thought that we cant use WHERE with functions. To do this we should use HAVING clause. So how it is for real? Are date functions not the same as MAX,MIN,AVG and so on;
It's not correct that you can't use functions in the
WHEREclause. You can put almost anything in it (except aggregates) as long as it evaluates to a logical true/false condition based on the columns of the involved tables, or just constant expressions.HAVINGon the other hand does support aggregates in addition to everything else.The difference between the two is when it's executed, it's relevant when you use
GROUP BY.WHEREcomes first, it imposes conditions on which rows from all involved tables can be used to form the groups, and those that don't fulfill it won't be taken into account for aggregations. You can think ofWHEREworking on the raw table data before grouping takes place.HAVINGis evaluated afterwards, when the groups are already formed and aggregations are computed (that's why you can use them here) and decided which final groups are allowed to show up in the final query result.They both operate at different times and on different sets of data. Note that when there is no
GROUP BY,WHEREandHAVINGare equivalent.