Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql: how to truncate the length of a field

Alter table merry_parents change mobile mobile char(10).

When I do the above I'm getting error:

#1265 - Data truncated for column 'mobile' at row 2

How can I truncate my mobile field to char(10)? Currently it is char(12).

like image 919
vaanipala Avatar asked Mar 08 '12 00:03

vaanipala


People also ask

How do you TRUNCATE a field value in SQL?

What is the Truncate Command in SQL? We use the Truncate command to delete the data stored in the table. The working of truncate command is similar to the working of Delete command without a where clause.

How do I TRUNCATE a column in MySQL?

TRUNCATE() Function in MySQL The TRUNCATE function in MySQL is used to truncate a number to a specified number of decimal places. Parameter : TRUNCATE() function accepts two parameters as mentioned above and described below. X –The number which to be truncated.

How do I TRUNCATE the answer to 4 decimal places in SQL?

The TRUNCATE() function truncates a number to the specified number of decimal places.


3 Answers

The error is telling you that there is data 12 characters long in row 2 (and probably others) so it's stopped the alter command to avoid losing data.

Try updating your table using SUBSTRING() to shorten the column. It's unclear why you want to do this as you'll lose data, but this will truncate the data to 10 characters long:

UPDATE merry_parents SET mobile=SUBSTRING(mobile, 1, 10)

Then run your alter command:

ALTER TABLE merry_parents CHANGE mobile mobile char(10).
like image 134
Bojangles Avatar answered Oct 23 '22 12:10

Bojangles


If you are ok with truncating the data at 10 characters - you can update the column first, then resize it

UPDATE <tablename> set mobile = left(mobile, 10);

Then run your alter statement.

like image 39
Jody Avatar answered Oct 23 '22 10:10

Jody


If you are willing to just have the data truncated, you can do it in one step by using the IGNORE option on the ALTER:

ALTER IGNORE TABLE merry_parents MODIFY mobile char(10);
like image 23
Dwight Avatar answered Oct 23 '22 12:10

Dwight