Fixing "Msg 402" in SQL Server: Understanding Modulo and Data Types
If you've been working with SQL Server and ran into this error:
Don't worry — you're not alone. This is a common issue and it's actually quite easy to fix once you understand what's going on.
Let’s break it down in simple terms.
What Does This Error Mean?
This error is telling you that SQL Server doesn’t allow you to use the modulo operator (%) with FLOAT and INT data types together.
Wait… What’s a Modulo?
The modulo operator (%) gives you the remainder after dividing one number by another.
For example:
That means:
The %
operator works perfectly with integers (whole numbers).
The Problem: Mixing Float with Int
Let’s say you write something like:
SQL Server throws the error:
"The data types float and int are incompatible in the modulo operator."
Why?
Because SQL Server is very strict about the %
operator. It only works with integers.
-
INT % INT
➡️ ✅ Works -
FLOAT % INT
➡️ ❌ Error -
FLOAT % FLOAT
➡️ ❌ Error
The Fix: Convert to Integers
If you only care about the remainder of the whole number part, you can cast your float to an integer using CAST()
or CONVERT()
.
Example:
What’s Happening Here?
-
CAST(@num1 AS INT)
converts 10.5 → 10 -
Then
10 % 3
gives1
Note: Casting a float to an int truncates the decimal part. It does not round. So:
-
10.9 → 10
-
10.1 → 10
If you need to do math on the decimal part, the modulo operator might not be the right tool — consider other math functions.
Summary
Here’s what you need to remember:
-
SQL Server doesn't support
%
on FLOATs -
Always use integers with the
%
operator -
If you have FLOATs, use
CAST()
to convert them
Simple Rule:
Always use integers with
%
— cast if needed!
Final Example
Wrapping Up
This is one of those SQL quirks that can be confusing at first, but once you get the hang of it, it’s pretty straightforward. Understanding how SQL Server handles data types — especially with operators — is a great step toward writing better and more reliable queries.