updating Primary key value with value '02' not saving - mysql

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.

Related

Why can I not change mysql int value?

It seems like a bug because when I set the integer value on a column it says it has been changed successfully but nothing happens and the integer value remains blank.
I can't use the database because I get the error that all my integer columns have incorrect integer values, but when I try to change them to int(11) e.g. nothing is happening.
Does anyone know how to fix this?
I can set columns with varchar datatypes to have values and they work fine.
Fatal error: Uncaught mysqli_sql_exception: Incorrect integer value: '' for column 'topic_id' at row 1 in C:\wamp64\www\mycode\upload2.php on line 32
mysqli_sql_exception: Incorrect integer value: '' for column 'topic_id' at row 1 in C:\wamp64\www\mycode\upload2.php on line 32
Code:
ALTER TABLE `topics` CHANGE `topic_id` `topic_id` INT(11) NOT NULL
AUTO_INCREMENT;
// This isn't changing the int value at all!
You have multiple errors in what you are attempting to do.
First, there is the problem that the values in the table are not integers.
Second, you cannot set a column to auto-increment unless it is the primary key.
One option is to drop the primary key and auto-increment idea. Then you can update the values to NULL and change the column to an int:
update topics
set topic_id = null
where topic_id regexp '[^0-9]';
ALTER TABLE `topics` CHANGE `topic_id` `topic_id` INT(11) ;
Here is a db<>fiddle.
If you really want topic_id to be an auto-increment primary key, then I would suggest recreating the table. Something like this:
create table temp_topics as
select *
from topics;
drop table topics; -- be very careful here!
create table topics (
topic_id int auto_increment primary key,
. . . -- the rest of the columns
);
insert into topics (<list of columns here>)
select <list of columns here>
from temp_topics;
if you wanna change a value you have to update that row.
what you are trying to do is wrong , int data type has fixed length (4 bytes), so when you give it a length , it actually doesn't mean anything and its been ignored by the sql engine
see MySql Ref: https://dev.mysql.com/doc/refman/8.0/en/integer-types.html
numeric data types are divided into 3 categoies :
Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT
Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC
Floating-Point Types (Approximate Value) - FLOAT, DOUBLE

How do I add leading 0's to a string in 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 !

Not null confusion

In phpMyAdmin, as we create table there is not null constraints by default for all fields...and as per my knowledge when we set the constraint to not null...it doesn't allow user to remain field empty which are not null as per this link.....
http://www.techopedia.com/definition/27370/not-null-constraint
now my question is..according to this link, not null means every row of data must contain a value - it cannot be left blank during insert or update operations.....but when i insert data programatically like insert into, i am able to insert data in just two fields and other remains blank although there is not null constraints on that fields ...and still not generates any error....so i don't understand how not null works???
for example, i create table with lets say 5 fields...
create table myTable
(
Column1 int not null,
Column2 int not null,
Column3 int not null,
Column4 int not null,
Column5 int not null,
)
and insert values in just two fields like
"INSERT INTO myTable (column1,column2) VALUES(10,20)";
but other fields i don't give any '' so it takes 0 as value....and still i am able to insert data with no error...how is that possible??
Everything that has the NOT NULL constraint set needs to contain data. If you insert data programmatically and you do not insert data for a NOT NULL cell, then you will get an SQL Error.
e.g. you have this table:
CREATE TABLE test (
id INTEGER PRIMARY_KEY AUTO_INCREMENT,
some_value INTEGER NOT NULL,
some_other_value INTEGER);
Then some_value will contain data in every data set returned, some_other_value may or may not contain data in every data set returned. The only thing to work around this would be this:
CREATE TABLE test (
id INTEGER PRIMARY_KEY AUTO_INCREMENT,
some_value INTEGER NOT NULL DEFAULT 0,
some_other_value INTEGER);
If you now set data programatically and do not set data for some_value, some_value will default to 0 (or to whatever data you set the default to on table creation).
Maybe you can refer to this link:
For multiple-row INSERT statements or INSERT INTO ... SELECT
statements, the column is set to the implicit default value for the
column data type. This is 0 for numeric types, the empty string ('')
for string types, and the “zero” value for date and time types. INSERT
INTO ... SELECT statements are handled the same way as multiple-row
inserts because the server does not examine the result set from the
SELECT to see whether it returns a single row. (For a single-row
INSERT, no warning occurs when NULL is inserted into a NOT NULL
column. Instead, the statement fails with an error.)
If a column definition includes no explicit DEFAULT value and it is defined as "Not Null" then Mysql will automatically assign default value to the column based on datatype. e.g. 0 for integer and "" for varchar
If you create a unique index on a column, the default value will be accepted with the first row but will give an error with subsequent inserts.

What is automatically populating this column?

I am using MySQL 5.6.1 on a Win 7 64Bit.
I have a standard audit column I add to all my tables called CRT_TS (create timestamp), along with a UPD_TS (update timestamp) column. I had planned on populating these via a before insert trigger and a before update trigger using utc_timestamp().
The UPD_TS column behaves as I expect it to. However, the CRT_TS column seems to be getting automatically populated without my defining a default or trigger for that column.
I was able to reproduce this behavior by running the following script.
create schema `test` default character set utf8 collate utf8_general_ci;
drop table test.TEST_TABLE;
create table test.TEST_TABLE(
TEST_ID int not null auto_increment ,
CRT_TS timestamp not null ,
UPD_TS timestamp not null ,
TEST_ALIAS varchar(64) not null ,
primary key PK_PERM (TEST_ID) ,
unique index UI_PERM_01 (TEST_ALIAS) )
auto_increment = 1001;
insert into test.TEST_TABLE
(TEST_ID
,TEST_ALIAS)
values
(1
,'testing');
select *
from test.TEST_TABLE;
In the above example, the CRT_TS column isn't being supplied a value, and yet it is being populated with the same value what would have been provided by the now() function. The UPD_TS column is populated with all zeros, yet both columns have been defined identically.
My questions is, what is populating the CRT_TS column? I am attempting to set both the UPD_TS and CRT_TS columns to utc_timestamp() value. Even setting the value in a trigger for CRT_TS, the value is overridden.
Thanks for any clarity you can provide.

How to reinstate auto increment during importation of CSV file into MySql while retaining pervious numbering?

ID,CREATED,FILENUMBER,ADDRESS,CITY,STATE,ZIP
1008,"02/27/2014, 10:28",142840,124 North St,Anycity,NY,91111
1007,"02/12/2014, 21:06",142839,424 Maple Ave,Anycity,NY,91111
1006,"02/12/2014, 21:06",142839,143 Great Pl,Anycity,NY,91111
I have "like above" records in the comma separated value file format. I would like to import this table into MySQL and while doing so to:
retain existing records with same ID numbers
to make ID to continue increment with each record added
if one of the records is is deleted I don't want records to update their number (for example, if record with ID 1007 is deleted the remaining record numbers would 1006 and 1008)
And the last, but not least I would like "FILENUMBER" to Auto increment on each new record
with first two numbers being the year date (e.g. 14 stands for 2014) and the remaining
four numbers are just incrementing with each record (e.g 142841, 142842, 142843, etc). Another example, if record is added December 31, 2014, the file number should auto increment with like 142844 and any next record addition on January 1, 2015 it would be 152845.
and I also want retain each existing records same FILENUMBER numbers and then with new records continue to auto increment.
Is there a way to import this into MySQL and to make columns ID and FILENUMBER to do the above?
I am thinking of something like this:
CREATE TABLE `records` (
`ID` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`CREATED` TIMESTAMP DEFAULT NOW(),
`FILENUMBER` int(6) zerofill not null auto_increment,
`ADDRESS` varchar(50) NOT NULL,
`CITY` varchar(12) NOT NULL,
`STATE` varchar(2) NOT NULL,
`ZIP` INT(10) NOT NULL);
load data local infile 'c:\\records.csv'
into table records
fields terminated by ','
lines terminated by '\n'
(ID, CREATED, FILENUMBER, ADDRESS, CITY, STATE, ZIP);
Some corrections:
You can't define multiple fields to have auto increment.
If you want to keep id with auto..., then filenumber int ... auto... is wrong.
Possible options (for enabling):
You better not define auto increment for filenumber field but for
id field only.
For the latest inserted filenumber value to hold current year as
prefix, then you need a trigger to set the 2 digit year as
prefix.
You can use primary key value as suffix with year to form the
filenumber.
And, to retain the former auto_increment value in the new table into which you are importing data, you need to use alter table command.
alter table table_name
auto_increment = new_number_from_where_to_start_with;