Home > Database > Mysql Tutorial > How Can I Preserve Leading Zeros in a MySQL Numeric Column?

How Can I Preserve Leading Zeros in a MySQL Numeric Column?

Susan Sarandon
Release: 2025-01-08 13:06:42
Original
853 people have browsed it

How Can I Preserve Leading Zeros in a MySQL Numeric Column?

Maintaining Leading Zeros in MySQL Columns

Importing CSV data often leads to the loss of leading zeros in numeric fields. This article details how to restore this formatting within MySQL.

Approach 1: Leveraging ZEROFILL

The most direct solution involves altering the column's data type to include the ZEROFILL attribute:

<code class="language-sql">ALTER TABLE table_name MODIFY COLUMN interested_column numeric(8,0) ZEROFILL;</code>
Copy after login

This modification ensures all values are padded with leading zeros to reach the specified length (8 digits in this example).

Approach 2: Utilizing LPAD()

If modifying the data type isn't practical, the LPAD() function provides an alternative:

<code class="language-sql">SELECT LPAD(interested_column, 8, '0');</code>
Copy after login

LPAD() takes three arguments: the column, the target length (8), and the padding character ('0'). The query's output will display values with leading zeros to match the specified length. This method is useful for display or temporary adjustments.

The above is the detailed content of How Can I Preserve Leading Zeros in a MySQL Numeric Column?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template