I'm looking for the equivalent of Select LEN(1234) from x
Return 4
for FlameRobin for my Char
field.
All I can find is char_length
which returns the fields max length not the contents of the field.
I'm looking for the equivalent of Select LEN(1234) from x
Return 4
for FlameRobin for my Char
field.
All I can find is char_length
which returns the fields max length not the contents of the field.
Because that is the difference between SQL datatypes CHAR
(fixed length, always right-padded with spaces, like in DBF and other tabular formats of that age) and VARCHAR
(variable-length, may be shorter than max length).
And your query is NOT a query you are really using!
The query you suggest DOES return exactly 4 in Firebird.
db<>fiddle here
select rdb$get_context('SYSTEM', 'ENGINE_VERSION') as version , rdb$character_set_name from rdb$database;
VERSION | RDB$CHARACTER_SET_NAME :------ | :--------------------------------------------------------------------------------------------------------------------------- 3.0.5 | UTF8
Select char_LENgth(1234) from rdb$database
| CHAR_LENGTH | | ----------: | | 4 |
create table T ( i integer, c char(20), v varchar(20) )
✓
insert into T values (1234, 1234, 1234)
1 rows affected
select * from T
I | C | V ---: | :------------------------------------------------------------------------------- | :--- 1234 | 1234 | 1234
Select char_length(1234) as const , char_length(i) as int_to_char , char_length(c) as fixed_char , char_length(v) as var_char , char_length(trim(c)) as char_t , char_length(cast(trim(c) as varchar(20))) as char_t_v , char_length(trim(cast(c as varchar(20)))) as char_v_t from T
CONST | INT_TO_CHAR | FIXED_CHAR | VAR_CHAR | CHAR_T | CHAR_T_V | CHAR_V_T ----: | ----------: | ---------: | -------: | -----: | -------: | -------: 4 | 4 | 20 | 4 | 4 | 4 | 4
This is exactly what should happen. If you store "HELLO" in a CHAR(20) field, you will get a 20 character string on output (it might be trimmed somewhere along the path, so you don't realize that the initial size is always padded to, or truncated to, 20).
Either use VARCHAR
type, or you'll have to do something like CHAR_LENGTH(TRIM(FieldName))
to get the "perceived length" of the string.