27

This is my table data Student

enter image description here

And this is my query --

SELECT id, SUM( maths + chemistry + physics ) AS total, maths, chemistry, physics
FROM `student`

but it is throwing a single row --

id  total   maths   chemistry   physics
118     760     55  67  55

although i want to apply sum for all ids ....let me know how can i achieve this?

Trialcoder
  • 5,816
  • 9
  • 44
  • 66

7 Answers7

72

Sum is a aggregate function. You dont need to use it. This is the simple query -

select *,(maths + chemistry + physics ) AS total FROM `student`
Piyu
  • 736
  • 5
  • 4
19

Tip: If one of the fields has the possibility to be NULL, then use COALESCE to default these to 0, otherwise total will result in NULL.

SELECT *, (
    COALESCE(maths, 0) +
    COALESCE(chemistry, 0) +
    COALESCE(physics, 0)
) AS total 
FROM `student`
digout
  • 4,041
  • 1
  • 31
  • 38
  • is there an easier way if you have lots of columns you want to add than this? Maybe a database setting? – dasLort Jul 28 '21 at 12:58
  • @dasLort consider changing your table schema to be INT NOT NULL for example and a default of 0? – digout Mar 17 '22 at 14:25
11

If you're requiring to get total marks of each student, then SUM is not what you'd be needing.

SELECT id,
    (maths+chemistry+physics) AS total,
    maths,
    chemistry,
    physics
FROM `student`

Will do the job just fine.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
9

You don't need use SUM for this operation. Try this query:

SELECT id, ( maths + chemistry + physics ) AS total, maths, chemistry, physics
FROM `student`
khomyakoshka
  • 1,259
  • 8
  • 18
1

The sum function in MySQL works in the sense that it gives you the sum of values in a column from your select statement. If you need to sum values from a row in your query, then just use plus (+) What you need is this query :

SELECT id, (`maths` +`chemistry`+`physics`) AS `total`, `maths`, `chemistry`, `physics`
FROM `student`;

This will give you the results you need.

Benson Kiprono
  • 129
  • 1
  • 1
  • 12
0

All aggregate function works on rows specified by rowname and group by operation. You need operation on individual rows which is not an option for any aggregate function.

Saikat Biswas
  • 114
  • 1
  • 9
0

Try this

SELECT id, ( maths + chemistry + physics ) AS total, maths, chemistry, physics
FROM `student`

You are done. Thanks

Y. Joy Ch. Singha
  • 3,056
  • 24
  • 26