$dU=dQ$ and $dU=TdS$, but $dQ$ not always equal to $TdS$? Why?

In $dS = \frac{dQ}{T}$, the $dQ$ is the heat exchange on a reversible path from the initial state to the final state, irrespective of how the process is actually carried out.


Even if dW = 0 (e.g., constant volume), you can't write dQ=TdS for an irreversible process because, for irreversible heating or cooling of a body, T is not constant spatially within the body (i.e., T varies with spatial position). For transient irreversible heating, the temperatures near the boundary are hotter than in the interior, and for transient irreversible cooling, the reverse is true. So what value of T are you supposed to use? If you use the value of T at the boundary at which the heat transfer Q is occurring (i.e., $T = T_B$), you find that $dQ<T_BdS$. More precisely, $$\int{\frac{dQ}{T_B}}<\Delta S$$This is just the statement of the Clausius Inequality.


For an arbitrary process between equilibrium states of a closed system, we have $$ \Delta U = Q + W $$ which is just conservation of energy.

If the process happens quasi-statically, state variables are well-defined at each point in time and we can go to an infinitesimal description $$ dU = \delta Q + \delta W $$ where $$ \delta Q \leq TdS \qquad \delta W \geq -p dV $$ Equality holds if the process is reversible, ie when the change in entropy is given by $dS = \delta Q/T$ without additional entropy production (due to friction, chemical reactions, what have you...).

In general, work performed externally on a system can get converted into heat within the system, and an infinitesimal descriptions in terms of energy flows and state variables won't match.

Explicitly, we have $$ \delta Q = TdS - T\,\delta S_\text{irrev} \\ \delta W = -pdV + T\,\delta S_\text{irrev} $$ where $\delta S_\text{irrev}$ is the additional entropy produced compared to a reversible process.