I mean the definition f[x_] = Sqrt[x] should only be used when x>0. So when I enter -2 as the argument, the definition should not be used and the output will be f[-2]. But in fact mathematica evaluates the code as follows:

In spite of the fact that -2<0, Mathematica uses the definition and produces the answer $i\sqrt{2}$
What's the difference between this code and the first one that makes mathematica use the definition in spite of the negative argument passed to the function?

Update: Response to closure (Michael E2)

There must be something quite subtle going on. It is not just the usual explanation that Set evaluates the right-hand and SetDelayed does not, because the right-hand side evaluates to itself (assuming, as Mr. Wizard's answer points out, that x has no value). This can be seen because the down values are the same in each case:

$\begingroup$I disagree with the close votes. This is a subtle error not explained at all in the documentation, AFAICS. There are valid reasons for using Set instead of SetDelayed as well as reasons for putting constraints on patterns.$\endgroup$
– Michael E2Oct 21 '15 at 11:30

1

$\begingroup$@Mr.Wizard not just related, but already covered and answered there, I think.$\endgroup$
– LLlAMnYPOct 21 '15 at 11:52

Mathematica is a registered trademark of Wolfram Research, Inc. While the mark is used herein with the limited permission of Wolfram Research, Stack Exchange and this site disclaim all affiliation therewith.