djs22
djs22

Reputation: 1156

MYSQL Order By Sum of Columns

Any idea on how to order the results of a MYSQL query by the sum of two columns rather than by a single column?

Select * FROM table ORDER BY (col1+col2) desc

I know that won't work., but I hope it conveys what I want to do fairly well.

Thanks!

Upvotes: 13

Views: 22230

Answers (5)

Djomla
Djomla

Reputation: 616

I can confirm this is NOT working in some cases. Check if some value is NULL

Select * FROM table ORDER BY (IFNULL(col1,0)+IFNULL(col2,0)) desc

Upvotes: 4

Rakesh Anand
Rakesh Anand

Reputation: 423

Suppose you have a table named 'Students'

enter image description here

Now you want to know the total marks scored by each student. So, type the following query

SELECT Name, S1, S2, SUM(S1+S2) AS TOTAL
FROM Students
GROUP BY Name, S1, S2
ORDER BY Total;

You will get the following result.

enter image description here

Upvotes: 8

jfoucher
jfoucher

Reputation: 2281

I think you should be able to do

SELECT *, col1+col2 as mysum ORDER BY mysum

Which is essentially the same as you already have

Upvotes: 6

Lukáš Lalinský
Lukáš Lalinský

Reputation: 41306

The query you wrote should work just fine, you can have any expression in the ORDER BY clause.

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 284836

Why not try before concluding it doesn't work? In point of fact, it does.

Upvotes: 30

Related Questions