On the surface, it's simple math as was said. Typically, the dealer buys your car, the loan gets paid off and the net (plus or minus) goes into the new car purchase. This is called an asymmetric negotiation where the dealer has vastly more information, training and leverage.
They will squeeze you one way or another: get a good price on your trade in and they get you on the financing, etc. Some folks are really good at negotiating with dealers. I'm one of the others who will never buy from a new or used car dealer ever again. Politicians will always get my vote if they say they will repeal the crooked franchise laws.
Here's one of many references with advice on how to not get ripped off too much.
https://www.consumerreports.org/consumerist/dealerships-rip-you-off-with-the-four-square-heres-how-to-beat-it/