27

I am using SQL Server 2008 R2 and I have an INT column where the data inserted never surpasses the max INT, but I have a query which uses the SUM function which when executed surpasses the max INT limit and throws the error mentioned in the title.

I want to be able to execute this query without changing the column type from INT to BIGINT.

Here is my query:

SELECT    UserId,
          SUM( PokemonExp )     AS TotalExp,
          MAX( PokemonLevel )   AS MaxPokeLevel

FROM      mytable

GROUP BY  UserId
ORDER BY  TotalExp DESC

Note: The PokemonExp column is of type INT.

3 Answers 3

57

Type of expression in SUM determines return type.

Try the following:

SELECT    UserId,
          SUM( CAST( PokemonExp AS BIGINT ))  AS TotalExp,
          MAX( PokemonLevel )                 AS MaxPokeLevel

FROM      mytable

GROUP BY  UserId
ORDER BY  TotalExp DESC
Sign up to request clarification or add additional context in comments.

1 Comment

For what it's worth, the same seems to happen with AVG, even if it's just the sum of your values that's overflowing.
1

You don't have to change the column type to BIGINT to get a proper sum.

Just CAST or CONVERT PokemonExp to BIGINT before you perform the SUM like follows:

SUM( CAST( PokemonExp AS BIGINT ))

Comments

0

Accepted type of expression in SUM determines return type.

Try the following:

SELECT    UserId,
          SUM( CAST( PokemonExp AS BIGINT ))  AS TotalExp,
          MAX( PokemonLevel )                 AS MaxPokeLevel

FROM      mytable

GROUP BY  UserId
ORDER BY  TotalExp DESC

1 Comment

Does CAST( PokemonExp AS BIGINT ) not explicitly cast the result to BIGINT, which was the opposite of what OP wanted?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.