Skip to content
Advertisement

Sorting by difference in column values

I have the following columns in my sql database table cities:

zipcode | totalPetPopulation | numCats | numDogs

My goal is to get all rows where numCats > numDogs but also I need to order them in descending order based on the difference between numCats and numDogs. That is, if I have the following table:

I need the result to be:

I have this so far for my query:

Advertisement

Answer

You can just put the difference expression in your ORDER BY clause:

Output:

Demo on dbfiddle

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement