2

how to ensure mysql column has 4 character ?

Due to using the MATCH function with minimum 4 char, i want my primary key which is a INT to be at least 4 char.

How can i do it ?

eg. 1 will be 0001 in sql table

Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
Fxster
  • 189
  • 1
  • 4
  • 13

3 Answers3

1

Use ZEROFILL attribute of column. Alter your Primary key column to have zerofill enabled.

Try this:

ALTER TABLE `tablename` CHANGE
COLUMN `id` `id` INT(4) ZEROFILL NOT NULL AUTO_INCREMENT ;
luiges90
  • 4,493
  • 2
  • 28
  • 43
Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
0

You can use MySQL's LPAD function:

SELECT LPAD('1',4,'0');
    -> '0001'

Docs here.

Madbreaks
  • 19,094
  • 7
  • 58
  • 72
0

Assuming your primary key is an auto-incremented id.

  1. Temporarily take the auto-increment off.
  2. Add 999 to every id. (Of course if other tables use this id as a foreign key, you are going to have to adjust them, too).
  3. Re-add the auto-increment, but make sure that it starts at at least 1000. See: How to set initial value and auto increment in MySQL?
Community
  • 1
  • 1
DWright
  • 9,258
  • 4
  • 36
  • 53
  • 1
    For any production, established relational database this probably isn't feasible. – Madbreaks Jan 09 '13 at 18:03
  • @Madbreaks. You're absolutely right. I'm inferring from the question that it probably is not production stuff. But if it is, forget what I said. – DWright Jan 09 '13 at 18:07
  • That sounds fine. If it's production data, you don't want to mess with the already existing keys. – DWright Jan 11 '13 at 18:07