Flatness of the restriction morphism of an affine scheme to an affine subscheme Let $X= \operatorname{Spec}(A)$ be an affine scheme, and $Y= \operatorname{Spec}(B)$ be an open affine subscheme of $X$. The inclusion morphism $Y \rightarrow X$ induces a structure of $A$-algebra on $B$. I would like to prove that $B$ is then flat over $A$.  
When $Y$ is a principal open subset of $X$, the result is known because $B$ is then a localization of $A$. In the general case, I suspect that $B$ is not always a localization (or is it ?). How could I then prove flatness of $B$ ?
 A: Recall the relevant definitions:
Definition Let $f : X \to Y$ be a morphism of schemes. $f$ is said to be flat if the map of stalks $\mathcal{O}_{Y,f(x)} \to \mathcal{O}_{X,x}$ is a flat morphism of rings for all $x \in X$.
Definition Let $f : X \to Y$  be a morphism of schemes. $f$ is said to be an open immersion if the map on topological spaces $X \to Y$ is open, is a homeomorphism onto its image, and the morphism of sheaves $f^* \mathcal{O}_Y \to \mathcal{O}_X$ is an isomorphism.
Now it should be clear that every open immersion of schemes is flat! No need to assume that the schemes are affine.
Proposition Every open immersion of schemes is flat.
Proof. Let $f : X \to Y$ be an open immersion of schemes. Since $f^* \mathcal{O}_Y \to \mathcal{O}_X$ is an isomorphism, it induces an isomorphism on all stalks, so the map $\mathcal{O}_{Y,f(x)} = (f^* \mathcal{O}_Y)_x \to \mathcal{O}_{X,x}$ is an isomorphism (hence flat) for all $x \in X$. Therefore, $f$ is flat. $\square$
To be extra precise, the relevant open immersion in your question is the inclusion $\operatorname{Spec}(B) \to \operatorname{Spec}(A)$.
In general, an open affine subscheme of an affine scheme need not be a localization; see for example this question.
