HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Reducing column size and data type in mysql

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
columnsizereducingtypemysqlanddata

Problem

I have a mysql table adv(id(TEXT),index(TEXT) ) which I need to change it as follows

ALTER TABLE adv
  MODIFY COLUMN id VARCHAR(80),
  MODIFY COLUMN index INT(11);


will this preserve all the data in the above columns assuming that they are less then 80 chars for id and a number for index?

Solution

Yes, it will. When there's no load on the table, I would suggest following procedure though. Not only can you double-check if everything is okay, it probably is also faster.

CREATE TABLE new_adv LIKE adv;

ALTER TABLE new_adv
  MODIFY COLUMN id VARCHAR(80),
  MODIFY COLUMN index INT(11);

INSERT INTO new_adv SELECT * FROM adv;

RENAME adv TO old_adv, new_adv TO adv;
/*when everything is okay...*/
DROP TABLE old_adv;


And by the way, it's a good idea not to use keywords like index for column names. You might want to change that, too. And if it's just for the benefit of not having to use backticks all the time when you use this column.

Code Snippets

CREATE TABLE new_adv LIKE adv;

ALTER TABLE new_adv
  MODIFY COLUMN id VARCHAR(80),
  MODIFY COLUMN index INT(11);

INSERT INTO new_adv SELECT * FROM adv;

RENAME adv TO old_adv, new_adv TO adv;
/*when everything is okay...*/
DROP TABLE old_adv;

Context

StackExchange Database Administrators Q#143685, answer score: 5

Revisions (0)

No revisions yet.