A magnetic field sensor comprises: a magnetic field detecting element that
detects magnitude of an external magnetic field based on electric
resistance of the magnetic field detecting element to sense current, the
electric resistance being varied in accordance with the external magnetic
field; an upper shield layer that is formed to cover the magnetic field
detecting element; and a protective layer that is formed above the upper
shield layer with respect to a direction of stacking. The upper shield
layer includes a first portion at least part of which covers a top
surface of the magnetic field detecting element, and a second portion
that covers the first portion, and, the first portion has a larger
absolute value of magnetostriction than the second portion.