I need to put in a script an id with zero value - mysql

CREATE TABLE IF NOT EXISTS home (
id int(11) NOT NULL AUTO_INCREMENT,
description(200) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 COLLATE=latin1_bin;
I need to insert a default value with id=0 but, I can't in this way. Anyone can help me?

You cannot have a DEFAULT value on an AUTOINCREMENT column. Also, as ID is your primary key, it would not really make sense to have a DEFAULT.
If you are just trying to insert an ID with a « 0 » value : mysql by default does not allow this on an AUTOINCREMENT field, but this can be tweaked with :
SET [GLOBAL|SESSION] sql_mode='NO_AUTO_VALUE_ON_ZERO'
However this is not recommended. See the mysql docs

I would be very cautious about trying to do such a thing. MySQL is so adamant about keeping zeros out that it changes the values of 0 to 1 when a column becomes an auto-increment column. Consider what happens with this code:
CREATE TABLE IF NOT EXISTS home (
id int(11) NOT NULL,
description varchar(200) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1;
insert into home (id, description)
values (0, 'my home');
select *
from home;
alter table home modify column id int auto_increment;
select *
from home;
The table no longer has 0 after the alter table.
Presumably, this is because long ago MySQL decided that 0 is a signal for using the default value, so the value is baked in.
You can use any other value that you want. So you might consider -1 if you want a "default" values for your tables that use auto_increment.

Related

Field 'category_id' doesn't have a default value MySQL

I'm learning SQL.
I'm trying to insert data. My MySQL database looks like this.
CREATE TABLE category (
category_id CHAR(100),
category_name VARCHAR(120) NOT NULL,
PRIMARY KEY (category_id)
)
I ran this command
INSERT INTO category (category_name) VALUES ("test");
But I got this error
ERROR 1364 (HY000): Field 'category_id' doesn't have a default value
Thank you in advance.
If you want to have an incrementing ID it would need to be an int. You Generally want to make ID's integers not chars to speed up lookup regardless.
CREATE TABLE IF NOT EXISTS category (
`category_id` INT NOT NULL AUTO_INCREMENT,
`category_name` VARCHAR(120) NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET = utf8mb4 COLLATE utf8mb4_unicode_ci;
That will let you insert without adding your own ID, and automatically generate unique ID's for the records.
Issue was you set your category_id field to not have a default value and also not allow null, which means you -have- to set a value for it in the insert. If you wanted to use your existing table you would need to do this:
INSERT INTO category (category_id, category_name) VALUES ("someid", "test");

mysql Field 'col1' doesn't have a default value

I had db schema defined as below
CREATE TABLE `ATestTable` (
id bigint(20) NOT NULL AUTO_INCREMENT,
refId varchar(32) NOT NULL,
col1 text COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_keyy_refId` (`refId`)
) ENGINE=InnoDB AUTO_INCREMENT=123 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
when I have something like this
Insert into ATestTable (refId, col1) Values ('abc', 'def');
I got error Field 'col1' doesn't have a default value. I searched online this error should happens when there is no value specified for this NOT NULL column. But I do specified the value. I even tried the same insert script on my local db and it works. So is it a db server configuration thing?
I run show variables like '%sql_mode%' and the one which doesn't work is NO_ENGINE_SUBSTITUTION. My local db (which works) is giving me ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
There are two things you can try, in other to fix your issue
1) You can change the sql mode to match your local db mode by running this query
SET GLOBAL sql_mode = 'modes';
modes separated by comma's. Note that this will work if only you have administrative rights. If not use
SET SESSION sql_mode = 'modes';
which will affect only the current client.
2) Set a default value for Col1 (eg: empty text) and the trigger will update the value anyways
CREATE TABLE `ATestTable` (
id bigint(20) NOT NULL AUTO_INCREMENT,
refId varchar(32) NOT NULL,
col1 text COLLATE utf8_unicode_ci DEFAULT ' ' not.
NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_keyy_refId` (`refId`)
) ENGINE=InnoDB AUTO_INCREMENT=123 DEFAULT.
CHARSET=utf8 COLLATE=utf8_unicode_ci;

Unable to add Column to table in mysql

I am trying to add a column to a table.To do so I am trying
ALTER TABLE requirements Modify COLUMN parent_id int(11);
but when I try to execute this query mysql does not respond for long.So each time I have to kill the query.
I have created the table using
CREATE TABLE requirements (requirement_id smallint(6) NOT NULL AUTO_INCREMENT,
product_id smallint(6) NOT NULL,
name varchar(255) CHARACTERSET latin1 NOT NULL DEFAULT '',
PRIMARY KEY (requirement_id),
UNIQUE KEY requirement_product_id_name_idx (product_id,name),
UNIQUE KEY requirement_product_idx (requirement_id,product_id),
KEY requirement_name_idx_v2 (name) )
ENGINE=InnoDB
AUTO_INCREMENT=7365
DEFAULT CHARSET=utf8;
Please help me know why I am not able to execute the Alter table query.I am new to database is there something wrong with my alter table query.
According to your table defintion parent_id seems to be a new column which you want to add so your query should be to add the column not modify.
Try this:
alter table requirements add column parent_id int(11);
SQL FIDDLE DEMO
On a side note:
There needs to be a space between CHARACTERSET here
name varchar(255) CHARACTERSET latin1 NOT NULL DEFAULT '',
should be
name varchar(255) CHARACTER SET latin1 NOT NULL DEFAULT '',

Best way to add column to a big table with longblob

I have the following table:
CREATE TABLE IF NOT EXISTS PDF_STORAGE (
ID_PDF_STORAGE bigint(20) NOT NULL AUTO_INCREMENT,
DESC_FILE varchar(255) DEFAULT NULL,
PDF_FILE longblob,
LINK_FILE varchar(255) DEFAULT NULL,
VERSION int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (ID_PDF_STORAGE)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Where PDF_FILE is a file of 10 MB on average. Today it has about 50.000 rows. I need to add a new column to this table but it is taking a long time, more than 10 min, some times giving a 401 error in PhpMyAdmin, so I'd like to know what is the proper way to achieve this...
I already tried:
ALTER TABLE PDF_STORAGE ADD VERSION INT NOT NULL DEFAULT '0' AFTER LINK_FILE ;
and
SET FOREIGN_KEY_CHECKS=0;
CREATE TABLE PDF_STORAGE_new LIKE PDF_STORAGE;
ALTER TABLE PDF_STORAGE_new ADD VERSION INT NOT NULL DEFAULT '0' AFTER LINK_FILE ;
INSERT INTO PDF_STORAGE_new (PDF_STORAGE, DESC_FILE, ID_PDF_STORAGE, LINK_FILE) SELECT * FROM PDF_STORAGE;
RENAME TABLE PDF_STORAGE TO PDF_STORAGE_old, PDF_STORAGE_new TO PDF_STORAGE;
DROP TABLE PDF_STORAGE_old;
SET FOREIGN_KEY_CHECKS = 1;
but they are also slow.. is there a better way?
Thanks
What you are doing now ALTER TABLE is the best approach to my knowledge. You can try making this change when there is not much transaction (or) DB operation going on. I mean say, do the changes in idle time.
ALTER TABLE PDF_STORAGE ADD VERSION INT NOT NULL DEFAULT '0' AFTER LINK_FILE ;
You can as well create a new table same as this table schema along with the new column.
Insert all the records from this table to the newly created table.
Rename the new table to the old table name.
delete the old table.

Mysql - duplicate entry error for key with auto increment

Why do I get an error of the form:
Error in query: Duplicate entry '10' for key 1
...when doing an INSERT statement like:
INSERT INTO wp_abk_period (pricing_id, apartment_id) VALUES (13, 27)
...with 13 and 27 being valid id-s for existing pricing and apartment rows, and the table is defined as:
CREATE TABLE `wp_abk_period` (
`id` int(11) NOT NULL auto_increment,
`apartment_id` int(11) NOT NULL,
`pricing_id` int(11) NOT NULL,
`type` enum('available','booked','unavailable') collate utf8_unicode_ci default NULL,
`starts` datetime default NULL,
`ends` datetime default NULL,
`recur_type` enum('daily','weekly','monthly','yearly') collate utf8_unicode_ci default NULL,
`recur_every` char(3) collate utf8_unicode_ci default NULL,
`timedate_significance` char(4) collate utf8_unicode_ci default NULL,
`check_in_times` varchar(255) collate utf8_unicode_ci default NULL,
`check_out_times` varchar(255) collate utf8_unicode_ci default NULL,
PRIMARY KEY (`id`),
KEY `fk_period_apartment1_idx` (`apartment_id`),
KEY `fk_period_pricing1_idx` (`pricing_id`),
CONSTRAINT `fk_period_apartment1` FOREIGN KEY (`apartment_id`) REFERENCES `wp_abk_apartment` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_period_pricing1` FOREIGN KEY (`pricing_id`) REFERENCES `wp_abk_pricing` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Isn't key 1 id in this case and having it on auto_increment sufficient for being able to not specify it?
Note: If I just provide an unused value for id, like INSERT INTO wp_abk_period (id, pricing_id, apartment_id) VALUES (3333333, 13, 27) it works fine, but then again, it is set as auto_increment so I shouldn't need to do this!
Note 2: OK, this is a complete "twilight zone" moment: so after running the query above with the huge number for id, things started working normally, no more duplicate entry errors. Can someone explain me WTF was MySQL doing to produce this weird behavior?
It could be that your AUTO_INCREMENT value for the table and the actual values in id column have got out of whack.
This might help:
Step 1 - Get Max id from table
select max(id) from wp_abk_period
Step 2 - Align the AUTO_INCREMENT counter on table
ALTER TABLE wp_abk_period AUTO_INCREMENT = <value from step 1 + 100>;
Step 3 - Retry the insert
As for why the AUTO_INCREMENT has got out of whack I don't know. Added auto_increment after data was in the table? Altered the auto_increment value after data was inserted into the table?
Hope it helps.
I had the same problem and here is my solution :
My ID column had a bad parameter. It was Tinyint, and MySql want to write a 128th line.
Sometimes, your problem you think the bigger you have is only a tiny parameter...
Late to the party, but I just ran into this tonight - duplicate key '472817' and the provided answers didn't help.
On a whim I ran:
repair table wp_abk_period
which output
Number of rows changed from 472816 to 472817
Seems like mysql had the row count wrong, and the issue went away.
My environment:
mysql Ver 14.14 Distrib 5.1.73, for Win64 (unknown)
Create table syntax:
CREATE TABLE `env_events` (
`tableId` int(11) NOT NULL AUTO_INCREMENT,
`deviceId` varchar(50) DEFAULT NULL,
`timestamp` int(11) DEFAULT NULL,
`temperature` float DEFAULT NULL,
`humidity` float DEFAULT NULL,
`pressure` float DEFAULT NULL,
`motion` int(11) DEFAULT NULL,
PRIMARY KEY (`tableId`)
) ENGINE=MyISAM AUTO_INCREMENT=528521 DEFAULT CHARSET=latin1
You can check the current value of the auto_increment with the following command:
show table status
Then check the max value of the id and see if it looks right. If not change the auto_increment value of your table.
When debugging this problem check the table name case sensitivity (especially if you run MySql not on Windows).
E.g. if one script uses upper case to 'CREATE TABLE my_table' and another script tries to 'INSERT INTO MY_TABLE'. These 2 tables might have different contents and different file system locations which might lead to the described problem.