How to know what kinds of substitution can we do in math? I have seen in many contexts that somebody out of the blue decides to put $x=y^2$, or $x=t/2$. 
So how do I know what kind of sustitution I'm allowed to do? 
Is there any necessary conditions or we can just put for example $x=\sqrt {sin(2y)}$ if necessary? 

You need to think in terms of functions.  If you have a function which maps from $\mathbb{A} \mapsto \mathbb{B}$, then your substitution must map from $\mathbb{C} \mapsto \mathbb{A}$ so that the range of the substitution matches the domain of the original function (this is ignoring the disctinction between the codomain and image--for instance it's perfectly fine to state that the function $f(x) = x^2$ maps $\mathbb{R} \mapsto \mathbb{R}$ where $\mathbb{R}$ is the codomain and $\mathbb{R}^+$ is the image).
An example: if you have the function $f(x) = \sqrt{x}$ such that $f: \mathbb{R}^+ \mapsto \mathbb{R}$, then it's incorrect to substitute the function $x = g(\zeta) = \zeta^3$ where $g: \mathbb{R} \mapsto \mathbb{R}$.  Here the function $g(\zeta)$ can take on a negative value--which the original domain cannot (although this would be trivial to fix by simply stating that $g : \mathbb{R}^+ \mapsto \mathbb{R}^+$).
There is another consideration, which is monotonicity.  Assuming $\mathbb{R} \mapsto \mathbb{R}$, you can consider the function: $f(x) = x$ and the substitution $x = g(\zeta) = 2\zeta^3 - 9\zeta^2 + 12\zeta$.  The original function monotonically increases, but the substitution does not (it goes back and forth).
p.s. It's worth noting that in terms of calculus and u-substitution, what really matters is whether or not your substitution is differentiable.  The fact that it may not be monotonically the same doesn't matter because the integral will properly subtract and add the parts that go back and forth.
Here is an Algebra II example where you have to be careful about substitutions:
$$
\sin^2(x) + \sin(x) - 2 = 0
$$
The substitution you make is that $y = \sin(x)$ and then we get:
\begin{align}
y^2 + y - 2 = 0 \\
(y + 2)(y - 1) = 0 \\
y = -2, y = 1
\end{align}
We must discard the $y = -2$ solution because $\sin(x) \neq 2$ for any real value (although that's not true if we allow complex values).  This leaves us with a single solution $\sin(x) = 1 \rightarrow x = \frac{\pi}{2} + 2\pi n$ where $n$ is any integer.
If we allow complex solutions, then we can use the equation that:
\begin{align}
\sin(x) = \frac{e^{ix} - e^{-ix}}{2} = 2 \\
\frac{e^{ix} - e^{-ix} - 4}{2} = 0
\end{align}
Now we can use a substitution: $e^{ix} = y$:
$$
y - \frac{1}{y} - 4 = 0 \rightarrow \frac{y^2 - 4y - 1}{y} = 0
$$
We can solve: $y = \frac{4 \pm \sqrt{16 + 4}}{2} = \frac{4 \pm 4\sqrt{5}}{2} =  2 \pm 2\sqrt{5}$ which gives:
\begin{align}
e^{ix} = 2 \pm 2\sqrt{5} = e^{i(2\pi n - i\ln(2 \pm 2\sqrt{5})} \\
x = 2\pi n - i\ln(2 \pm 2\sqrt{5})
\end{align}
