How do I add leading 0's to a string in mysql? - mysql

I have a column in my table of zip codes. Some of the zip codes got truncated since they started with 0. For instance, 00123 appears as 123 and 04567 appears as 04567.
Is there a function that I can use to update all entries of the column so that if the length of the string is 3, there will be 0's place in front of the number to make it length of 5? (i.e. 123 --> 00123 & 4567 --> 04567)

If your column already is in a string type, you can use LPAD to add leading strings:
update table set zipcode = LPAD(zipCode, 5, '0');
If it's a numeric datatype, change the column to use ZEROFILL, then do the same as above. Please note that this will automatically make your column unsigned.
See the manual

Make your zipcode field one of the text type fields. Problem solved. This makes sense when you think about it as it is unlikely that you are going to do any mathematical computations on this data. Also, this is more flexible if and when you need to accommodate countries with non-numeric postal code values.

Create or ALTER the field to zerofill and set the length to that
CREATE TABLE `abc` (
`zip` int(5) unsigned zerofill DEFAULT NULL,
`b` int(11)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Try UPDATE Table SET zipCode = LPAD(zipCode, 5, '0');
This will fill your data with leading zeros. Hope that helps !

Related

MySQL and phMyAdmin

I'm new to this website and using Mysql and phpMyAdmin. I need help with one of my table and I would really appreciate it. So, I created a table that has an Integer column I want to be able to limit it to only 7(Seven) digits I'm not quiet sure if this is possible using Mysql or phpMyAdmin.
I haven't tried any query on it. I want to limit the Integer type to only 7(Seven) digits.
This might not be the best possible solution but I think that if you were to store the integer as string in the format char(7) to limit the number of characters able to be entered it would get the job done.
I'm not familiar with Mysql in particular but here's some documentation on it : https://dev.mysql.com/doc/refman/8.0/en/char.html
I hope this helped.
In MySQL <8.0.16 You can't restrict the number of digits for an Integer. That has no meaning.
You can, however, use a DECIMAL type that allows you to specify the number of digits and the number of decimal places.
For example, DECIMAL(7,0) will define what you want.
Your CREATE statement becomes something like
CREATE TABLE IF NOT EXISTS myTable (
id INT AUTO_INCREMENT PRIMARY KEY,
someText VARCHAR(255) NOT NULL,
decimalValue DECIMAL(7,0)
) ;
If you're using MySQL 8.0.16 or later you can use a CHECK constraint to limit the value (as distinct from limiting the number of digits).
The example above becomes
CREATE TABLE IF NOT EXISTS myTable (
id INT AUTO_INCREMENT PRIMARY KEY,
someText VARCHAR(255) NOT NULL,
decimalValue INT,
CONSTRAINT `decValue_chk` CHECK (`decimalValue` <= 9999999))
) ;

Is using Alter here wrong as opposed to Cast?

So I created a table with all varchar (255) then decided to use CAST to change to UNSIGNED (since all +ve values). When I checked, it has been changed to unsigned. However, I noticed when I check the whole table again the columns are still considered as varchar.
Is my understanding correct that CAST only works for the specific code and will not permanently change and if I wish to change the column type permanently, will require me to use ALTER as shown below?
If so why do people use cast instead of Alter?
CREATE table project.worldcup_players (
MatchID varchar (255),
Team_Initials varchar (255),
Coach_Name varchar (255),
Player_Name varchar (255)
);
SELECT * FROM project.worldcup_players;
SELECT CAST(MatchID AS UNSIGNED) AS MatchID FROM project.worldcup_players;
ALTER TABLE project.worldcup_players
CHANGE COLUMN `MatchID` `MatchID` INT NULL DEFAULT NULL ;
CAST only changes the result of an expression in the query. You could use CAST if you only want to change to an unsigned integer sometimes, without changing the way the data are stored.
ALTER TABLE is required if you want to change the way the data are stored.
Suppose your MatchID was represented by a number only for some matches. In other matches, the match is identified by an alpha string. In that case, the column must be a varchar, because the column must be stored as the same data type on all rows in a given table. Don't alter the table, because it would cause all the non-numeric strings to be changed to their numeric equivalent, 0.

What is difference between char and varchar

CREATE TABLE IF NOT EXISTS `test` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`country` varchar(5) NOT NULL,
`state` char(5) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
I tried following query to insert data
INSERT INTO `test`.`test` (`id` ,`country` ,`state`)
VALUES (NULL , 'south-india', 'Gujarat');
When I execute above query It will shows following warning
Warning: #1265 Data truncated for column 'country' at row 1
Warning: #1265 Data truncated for column 'state' at row 1
I found Reference that VARCHAR is variable-length.CHAR is fixed length.
Then what you mean by
VARCHAR is variable-length.
CHAR is fixed length.
VARCHAR(5) will use at most 5 characters of storage, while CHAR(5) will always use exactly 5.
For a field holding a person's name, for example, you'd want to use a VARCHAR, because while on average someone's name is usually short, you still want to cope with the few people with very long names, without having to have that space wasted for the majority of your database rows.
As you said varchar is variable-length and char is fixed. But the main difference is the byte it uses.
Example.
column: username
type: char(10)
if you have data on column username which is 'test', it will use 10 bytes. and it will have space.
'test______'
Hence the varchar column will only uses the byte you use. for 'test' it will only use 4 bytes. and your data will be
'test'
THanks.
As you mentioned VARCHAR is variable-length. CHAR is fixed length.
when you say
Varchar(5) and if the data you store in it is of length 1, The
remaining 4 byte memory space will be used by others. example: "t"
on the other hand
Char(5) and if the data you store in it is of length 1, The remaining
4 byte memory space cant be used. The 4 byte will end up not used by
any other data. example: "t____" here ____ is the unused space.

How to add a not null constraint to an already existing column with null values?

I've seen a similar question on stackexchange, but it's answer did not give me the correct results.
For demonstration purposes, I have a simple table PURCHASES with columns PURCHASE_NUM, PURCHASE_DATE, CUSTOMER_ID. I want to enforce a not null constraint on the CUSTOMER_ID table. I tried the following:
ALTER TABLE PURCHASES MODIFY CUSTOMER_ID char NOT NULL;
That syntax is fine, but then I insert with the following: INSERT INTO PURCHASES VALUES (333, NULL, NULL); and the tuple is added without issue. Why is the constraint not being enforced? Would having NULL values already in that column before adding the constraint affect things?
Thanks
edit DESCRIBE PURCHASES; says the following for the column of interest:
Field, Type, Null, Key, Default, Extra
CUSTOMER_ID, char(5), YES, , NULL,
Your ALTER command didn't work, the Null column still says YES. Your ALTER command syntax looks just fine, it should have worked. Check your typing and try again.
Is your customer ID really just a char?
Maybe you have to change to
ALTER TABLE PURCHASES MODIFY CUSTOMER_ID char NOT NULL;
According to the manual, data entry into a NOT NULL column that has no explicit DEFAULT clause will set the column to NULL. Thus, you should ALTER your column to contain a DEFAULT. From 4.0 documentation:
Implicit defaults are defined as follows:
For numeric types, the default is 0, with the exception that for integer or floating-point types declared with the AUTO_INCREMENT attribute, the default is the next value in the sequence.
For date and time types other than TIMESTAMP, the default is the appropriate “zero” value for the type. For the first TIMESTAMP column in a table, the default value is the current date and time. See Section 10.3, “Date and Time Types”.
For string types other than ENUM, the default value is the empty string. For ENUM, the default is the first enumeration value.

updating Primary key value with value '02' not saving

When i update primary column with value '02' its saving to only 2. But it should be saved as 02.
When i run the following sql am not getting any error and saving successfully. But the value is not updating. Its not accepting any values that starts with '0'.
UPDATE `table_name` SET `id` = '02' WHERE `id` =2 ;
Declare your id column as Zerofill. The column declared with zerofill can be used to display values with leading zeros But this means not that it actually store the leading zeros. It does not store the leading zeros but used to display values with leading zeros
You can modify existing column.
ALTER TABLE table_name MODIFY `id` INT(11) ZEROFILL NOT NULL AUTO_INCREMENT
You have to change the data type of the id column from a numeric data type to VARCHAR or similar to save the leading zero. Otherwise, 02 is the same number as 2 , 002, 0002, 00002 .. etc.