A Good Bad Example
I learnt something new today (thanks to Steven) about TRIM – in the past I’ve used RTRIM and LTRIM if I only want to trim from the left or right ends of a string, but I was not aware (or had forgotten) that SQL’s TRIM function allows this to be specified.
Oracle’s documentation of TRIM, however, has a somewhat confusing example:
“This example trims leading zeros from the hire date of the employees in the hr schema:
TO_CHAR(TRIM(LEADING 0 FROM hire_date))
WHERE department_id = 60
ORDER BY employee_id;
As an example of using the TRIM function the above code is adequate; however, why does it call the TO_CHAR function at that point? After all, TO_CHAR is only useful if the datatype of its argument is not a character string – but in this case, it’s a string already – TRIM always returns a string.
Not only does the example perform a useless datatype conversion, it involves an implicit conversion – from date to string. The expression would be much better like this:
TRIM(LEADING 0 FROM TO_CHAR(hire_date))
Better – but still not perfect. Sure, we should probably specify the date format so the code is a bit more robust (what if the session has a default format of ‘MM/DD/YY’?), but we can see yet another implicit data type conversion: “LEADING 0“. The only purpose for TRIM is to remove characters. Sure, you can put in zero if you want, but it’s only going to be converted to a character, ’0′ anyway – so why not make it obvious to the next coder who comes along:
TRIM(LEADING '0' FROM TO_CHAR(hire_date,'DD/MM/YY'))
There, much better! I think the above expression is much clearer about what it will actually do – i.e. it converts a date to a string of characters, and then removes any leading ’0′ characters.