1

Table:

id | c1  | c2
-------------    
1  | 10 | 20
2  | 55 | 20
3  | 30 | 30
4  | 11 | 80
5  | 12 | 20

and query

select (sum(c1)+sum(c2))as sum from mytable where sum > 100 ??

the above generates an error as sum not part of the table. any work around to limit / where condition to restrict result returned to be only upon this condition of two columns sum ? (with out the need to add a third column to the table)

Thank you

Ahmed ElGamil
  • 179
  • 1
  • 13
  • 1
    Use `HAVING` instead of `WHERE` also `sum` is probably reserved, try another field name. – Orbling Jun 24 '13 at 17:05
  • @Orbling (surprisingly?!) sum is not a reserved word. – Sylvain Leroux Jun 24 '13 at 17:07
  • 1
    @SylvainLeroux: It is surprising! It's not in the [reserved word list](http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html) - but I would still not use it, could become reserved in future and confusing in any event. – Orbling Jun 24 '13 at 17:09

3 Answers3

4

I believe you are looking for the HAVING clause.

So,

SELECT (SUM(c1)+SUM(C2)) AS sum FROM mytable HAVING sum > 100;
2

You can either wrap your existing query in another select:

select total
from
(
  select sum(c1 + c2) as total 
  from mytable 
) d
where total > 100;

Or you can use a HAVING cluase:

select sum(c1 + c2) as total 
from mytable 
having sum(c1 + c2) > 100;  -- you can also use the total alias in the having

See SQL Fiddle with Demo.

Taryn
  • 224,125
  • 52
  • 341
  • 389
1

This answer is related to Ahmed's comment:

SELECT (c1+c2) AS sum FROM mytable WHERE ID > 5  GROUP BY ID HAVING sum > 100;
gustavohenke
  • 38,209
  • 13
  • 113
  • 120
jospratik
  • 1,286
  • 10
  • 18