// math reference

SQL float equality

Why = is unreliable on float columns and the portable fixes: ABS(a - b) < epsilon, or storing exact decimals for values that must compare equal.

Категория
Math
Returns
boolean
In this category
67 of 82

Синтаксис

ABS(a - b) < 1e-9
a = b  -- exact types only

Each block is a separate form. The support table and the examples show which engine takes which.

Поддержка движка

ДвижокSupportЗаметки
SQL Server Да Same rule; DECIMAL columns compare exactly, FLOAT does not
PostgreSQL Да = on double precision compares exact binary values; a real (float4) column never equals the literal 0.1, which is read as float8
MySQL Да Same; DECIMAL compares exactly
SQLite Да REAL compares by value; INTEGER cents sidestep the problem
Oracle Да NUMBER compares exactly; BINARY_FLOAT/BINARY_DOUBLE do not

Примеры

PostgreSQL

SELECT ABS((0.1::float8 + 0.2::float8) - 0.3::float8) < 1e-9 AS close_enough;  -- true

MySQL

SELECT * FROM measurements
WHERE ABS(reading - 0.1) < 0.000001;

PostgreSQL

SELECT 0.1::float4 = 0.1 AS f4, 0.1::float8 = 0.1 AS f8;  -- false, true

Полезно знать

  • The failure is representational, not engine-specific: 0.1 and 0.2 have no exact binary form, so their float sum is the neighbour of 0.3 rather than 0.3.
  • Pick the tolerance relative to the magnitude: ABS(a - b) < 1e-9 suits values near 1, but near 1e12 adjacent doubles are about 1e-4 apart, so use ABS(a - b) <= 1e-9 * ABS(b).
  • Single-precision columns are the worst case: on PostgreSQL WHERE real_col = 0.1 matches nothing, because the stored float4 0.1 differs from the float8 0.1 the literal becomes. MySQL FLOAT columns behave the same way.

Questions about float equality

Why does my WHERE x = 0.1 not match?

Either the column is single precision (REAL/float4, MySQL FLOAT), whose 0.1 differs from the double the literal becomes, or the value was computed and carries rounding error. Compare with a tolerance: ABS(x - 0.1) < 1e-6 for single precision.

How should I compare floats in SQL?

Within a tolerance scaled to your data: ABS(a - b) < epsilon. For currency and counts, avoid the problem entirely by using NUMERIC/DECIMAL columns, which compare exactly.

Do joins on float keys work?

They match only bitwise-equal values, so computed floats routinely fail to join. Join on rounded keys (CAST to a fixed scale) or exact integer keys instead.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.