Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic overflow error converting expression to data type int for basic statistics

I am trying to do a basic query that calculates average, min, max, and count.

SELECT
 MIN(column) as min,
 MAX(column) as max,
 AVG(column) as avg,
 count(*) as count
FROM database.dbo.table;

Where column is of type int, and the database is azure sql standard.

and in return, i get an error: "Arithmetic overflow error converting expression to data type int"

Why is int getting a casting-to-int problem in the first place? and is there something I can add that will make this work on all numerical types?

like image 248
Kristian Avatar asked Apr 30 '26 01:04

Kristian


2 Answers

Try to use count_big like this:

SELECT
 MIN(column) as min,
 MAX(column) as max,
 AVG(column) as avg,
 count_big(*) as count
FROM database.dbo.table;

Also you try to CAST your column as BIGINT like this:

 SELECT
 MIN(CAST(column as BIGINT)) as min,
 MAX(CAST(column as BIGINT)) as max,
 AVG(CAST(column as BIGINT)) as avg,
 count_big(*) as count
FROM database.dbo.table;
like image 104
Rahul Tripathi Avatar answered May 02 '26 14:05

Rahul Tripathi


The issue is either with the average aggregation or the count(*).

If the sum of the values in column is greater than 2,147,483,647 you will need to cast the column as a bigint before averaging because SQL first sums all of the values in column then divides by the count.

If the count of the rows is more than 2,147,483,647, then you need to use count_big.

The code below includes both fixes so it should work.

SELECT 
 MIN(column) as min,
 MAX(column) as max,
 AVG(Cast(Column AS BIGINT)) as avg,
 count_big(*) as count
 FROM database.dbo.table;

You don't need to cast min or max to bigint because these values exist in the table already without overflowing the int data type.

like image 45
ckarst Avatar answered May 02 '26 15:05

ckarst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!