Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Oracle's to_char() function adding spaces?

Tags:

oracle

Why is Oracle's to_char() function adding spaces?

select length('012'),         length(to_char('012')),         length(to_char('12', '000'))    from dual; 

3, 3, 4

like image 965
Igor Drincic Avatar asked Oct 27 '08 14:10

Igor Drincic


People also ask

What is TO_CHAR function in Oracle SQL?

TO_CHAR (datetime) converts a datetime or interval value of DATE , TIMESTAMP , TIMESTAMP WITH TIME ZONE , or TIMESTAMP WITH LOCAL TIME ZONE datatype to a value of VARCHAR2 datatype in the format specified by the date format fmt .

What can we use instead of TO_CHAR in SQL?

SQL Server has separate functions for YEAR() , MONTH() , and DAY() . Oracle uses TO_CHAR() ; SQL Server uses CONVERT() . One option is to define the functions YEAR() , MONTH() , and DAY() in Oracle and then use string concatenation (via the CONCAT() ) function to combine the data.

How do I format in Oracle?

In SQL statements, you can use a format model as an argument of the TO_CHAR and TO_DATE functions to specify: The format for Oracle to use to return a value from the database. The format for a value you have specified for Oracle to store in the database.

What is FM in TO_CHAR in Oracle?

1 FM: Suppressing Blanks and Zeros. PL/SQL offers the FM element as a modifier to a format mask. FM (fill mode) controls the suppression of padded blanks and leading zeros in values returned by the TO_CHAR function.


2 Answers

The extra leading space is for the potential minus sign. To remove the space you can use FM in the format:

SQL> select to_char(12,'FM000') from dual;  TO_C ---- 012 

By the way, note that to_char takes a NUMBER argument; to_char('012') is implicitly converted to to_char(to_number('012')) = to_char(12)

like image 150
Tony Andrews Avatar answered Nov 10 '22 03:11

Tony Andrews


To make the answers given more clear:

select '['||to_char(12, '000')||']',         '['||to_char(-12, '000')||']',         '['||to_char(12,'FM000')||']'  from dual   [ 012]                      [-012]                       [012]   
like image 36
James Curran Avatar answered Nov 10 '22 03:11

James Curran