2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DBカラムの値を0埋めにする

Posted at

0埋め = ゼロパディング

指定の桁数に合わせて、対象の値の左を0で埋める行為のこと。
SQL では lpad という関数を使って実現できる。
(なお、同様に右を埋める rpad もある)
0 以外でも埋められる。

lpad

構文

lpad(`column_name`, 8, '0')

引数

引数番号 値の意味
1 カラム名
2 桁数
3 埋める文字

実装例

既に値が入っているカラムを8桁の0埋めして更新するパターン

UPDATE `table_name` SET `column_name` = lpad(`column_name`, 8, '0');

別のカラムを参照して10桁の0埋めして更新するパターン

UPDATE `table_name` SET `column_name` = lpad(`other_column_name`, 10, '0');

SELECT時に4桁で0埋めするパターン

SELECT lpad(`column_name`, 4, '0') FROM `table_name`;

直近で利用した例

  • とあるアイテムに管理コードを追加した時、その初期値として autoincrement される primary key を 0埋めで登録
  • 元々0埋めされていなかったデータだが、帳票に出力する際に0埋めする必要が出た
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?