Search code examples
mysqlsqlcasting

In MySQL using CAST() to CAST VARCHAR to CHAR, but end result is still VARCHAR and not CHAR


I create a table table1 with a single column column1 declared as VARCHAR(100) -

CREATE TABLE table1 (
    -> column1 VARCHAR(100)
    -> );
DESCRIBE table1;
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| column1 | varchar(100) | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+

Now I create another table table2 from table1 where I create a single column column2 and declaring it by casting column1 from table1 as CHAR(100) -

CREATE TABLE table2 AS 
    -> SELECT CAST(column1 AS CHAR(100)) AS column2
    -> FROM table1;
DESCRIBE table2;
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| column2 | varchar(100) | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+

Here, strangely enough, even after casting VARCHAR(100) AS CHAR(100), the declaration still remains as VARCHAR(100)

Now, I wanted to make sure that creating a new table with column declared by casting actually works. So I tried with casting FLOAT to DECIMAL as follows -

CREATE TABLE table3 (
    -> column3 FLOAT
    -> );
DESCRIBE table3;
+---------+-------+------+-----+---------+-------+
| Field   | Type  | Null | Key | Default | Extra |
+---------+-------+------+-----+---------+-------+
| column3 | float | YES  |     | NULL    |       |
+---------+-------+------+-----+---------+-------+
CREATE TABLE table4 AS 
    -> SELECT CAST(column3 AS DECIMAL) AS column4
    -> FROM table3;
DESCRIBE table4;
+---------+---------------+------+-----+---------+-------+
| Field   | Type          | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| column4 | decimal(10,0) | YES  |     | NULL    |       |
+---------+---------------+------+-----+---------+-------+

Here FLOAT gets correctly casted to DECIMAL. So why can't I cast VARCHAR to CHAR. Also if casting of VARCHAR to CHAR doesn't work, why am I not getting any error?


Solution

  • Here, strangely enough, even after casting VARCHAR(100) AS CHAR(100), the declaration still remains as VARCHAR(100)

    This is not strange behavior. It is clearly documented:

    • CHAR[(N)] [charset_info]

    Produces a string with the VARCHAR data type. except that when the expression expr is empty (zero length), the result type is CHAR(0).

    I'm the first to admit that it is rather counterintuitive, but it is how MySQL works. If you want a char() then either create the table with that type and insert into it or alter it afterwards.