Is there a built-in function to truncate values of one type to fit the range of another type? E.g casting a INTEGER
to SMALLINT
. This might fail if the INTEGER
is larger than SMALLINT
can hold. I would like the number to be truncated to the largest possible SMALLINT
in this case.
Asked
Active
Viewed 45 times
-1

Robert
- 165
- 10
-
Why do you want to do this? – Adrian Klaver Aug 19 '23 at 15:27
-
My motivation does not change the nature of my question @AdrianKlaver – Robert Aug 21 '23 at 07:55
1 Answers
1
No inbuilt function I'm aware of, you would need to use a case expression to handle the min and max values e.g:
SELECT CASE
WHEN your_integer_column > 32767 THEN 32767
WHEN your_integer_column < -32768 THEN -32768
ELSE your_integer_column
END::smallint AS truncated_smallint
FROM your_table;

Paul Maxwell
- 33,002
- 3
- 32
- 51