Deductions & credits

Does the gain of $250k or $500k include the sale total amount only? Or is it what you bank after you pay off the mortgage? 

Does it change anything if you put it right into a new mortgage?