2

Is it legal in ANSI SQL (or important implementations) to join on floating point columns?

I'm sure that it is generally not a good idea, but I'm working on an API and looking to SQL for guidance as to whether it should be prevented, or left to the developer to choose.

If it is legal, do you have the option to specify a precision to use in the comparison?

5
  • 2
    Underlying problem: does it make sense for a floating point value to be part of a (primary, natural, candidate, foreign, ...) KEY ? Answer: probably only as part of a {min,max} range. (the floating-point representation of date[time] values in SAS (and in Postgres <= pg8.3) can be painfull) Next question: how often do you need to join on non-Key fields?
    – joop
    Sep 6, 2018 at 16:34
  • 1
    It is valid and can work, but rounding can cause unexpected records if not anticipated. You shouldn't prevent a developer from doing things the language is capable of doing. Sep 6, 2018 at 16:41
  • floating-point-gui.de
    – user330315
    Sep 6, 2018 at 17:52
  • 1
    Remember, juggling chainsaws is legal. Sep 7, 2018 at 6:09
  • I see this in data that has been migrated from another DBMS. If you can change the way the data type maps, this would be the best solution. If not I've had some success with changing the joins to look like "ON str(FloatField) = str(OtherFloatField)". This is less efficient since its got to convert all the values from both fields before comparing.
    – John
    Mar 19, 2021 at 15:14

1 Answer 1

5

SQL allows joining on any columns and any conditions.

However, you should not allow joining on floating point columns, if you can prevent using equality conditions on such columns. The simple replacement is to allow joins on decimal/numeric columns.

What is the problem? WYSIWIG (what-you-see-is-what-you-get) is the problem. Two floating point values can look the same, and yet be different. This causes joins to fail.

You can specify the conditions as essentially:

on abs(a - b) < 0.00001 -- your favorite threshold

but this prevents the use of an index. Some databases may have "fuzzy" match for floating point numbers.

There are cases where you might want inequality joins using floating point values. This would be when doing ranges:

limit       val
1.4142     'a'
2.7182     'b'
3.1415     'c'

But this is a rare condition -- particularly when the limits should be floating point rather than counts or monetary limits.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.