I think you are confused by what it means to equate the coefficients. I personally think this “fact” is something that high school math usually brushes over instead of actually explaining it (at least that was the case for me and my students). Anyway, let me show you an example of when equating the coefficients actually work.
Suppose we want to find two numbers $A$ and $B$ such that
$$ Ax^2 + Bx + 2 = 3x^2 + 5x + 2 $$
for all (real) numbers $x$. Then, we may equate the coefficients and say $A = 3$ and $B = 5$. Why? Read the question again, it says that “blah blah blah … for ALL NUMBERS $x$”. That means that we are trying to find $A$ and $B$ so that NO MATTER WHAT VALUE OF $x$ we substitute, $Ax^2 + Bx + 2$ and $3x^2 + 5x + 2$ will ALWAYS be equal. So, for example, we have
$$ A(1)^2 + B(1) + 2 = 3(1)^2 + 5(1)^2 + 2, $$
$$ A(2)^2 + B(2) + 2 = 3(2)^2 + 5(2)^2 + 2, $$
$$ A(3)^2 + B(3) + 2 = 3(3)^2 + 5(3)^2 + 2, $$
$$ A(-123)^2 + B(-123) + 2 = 3(-123)^2 + 5(-123)^2 + 2, $$
etc, one equation (of $A$ and $B$) for each number(!). So, of course, $A$ and $B$ better equal $3$ and $5$ respectively. And that is indeed the case which you can see by solving the two linear equations
$$ A(1)^2 + B(1) + 2 = 3(1)^2 + 5(1)^2 + 2, $$
$$ A(2)^2 + B(2) + 2 = 3(2)^2 + 5(2)^2 + 2 $$
for $A$ and $B$. So, the sole reason why we can equate coefficients in this case, is because the equation is true for ALL values of $x$ (in fact, we only needed it to be true for two values of $x$ as we can solve for $A$ and $B$ once we get two equations). It turns out, we can do the same argument for polynomial identities. For example, if
$$ Ax^5 + Bx^3 + Cx^2 + D = 2x^5 - x^3 + 5x^2 + 1 $$
for ALL numbers $x$, then we can, with full confidence, say that $A = 2$, $B = -1$, $C = 5$ and $D = 1$ (in fact you only need four different values of $x$, check this if you’re interested). There is a deeper reason why polynomials work for us, things could go wrong with other functions. For example, suppose we have
$$ A2^{x+1} + B2^x = 2^{x+1} + 2^x $$
for ALL numbers $x$. Can we confidently say that $A = B = 1$? No, because $A = 0$ and $B = 3$ is also possible (why), and so does $A = -1$ and $B = 5$ (why). I hope this explains your confusion.