In my database there is a field last_id
of type integer
. The table contains several rows. Let's say the maximum value of last_id
is 104050. Now I want to know the length of this integer.
As this is not possible I am trying to convert it into a string.
SELECT to_char(MAX(last_id),'99') FROM xxxx
I would expect this to yield 10 with type = text, but instead it returns ## type = text.
Afterwards I would use SELECT char_length(to_char(MAX(last_id),'99')) FROM xxx
which should return 2 ...
What is going wrong here?
Cast the integer
value to text
:
SELECT length(max(last_id)::text) FROM xxx;
Since you are dealing with integers you can actually find the length of the number (or number of digits in the number) directly. Mathematically, the number of digits in an integer is one more than the floor of the log base 10 of the number.
You could use the following to find the length directly:
SELECT FLOOR(LOG(MAX(last_id))) + 1 FROM xxxx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With