I don't understand why I'm getting this error when trying to populate this table. There is nothing in the table at the moment so I don't understand why there would be a duplicate...
This is the code I'm using:
INSERT INTO Suppliers
(supp_id,company_name,town,phone)
Values
("ADT217","AdTec","Birmingham","0121-368-1597"),
("CPS533","CPS","Maidenhead","01382-893715"),
("FCL162","ForComp Ltd","Nottingham","01489-133722"),
("KBC355","KBC Computers","Glasgow","0141-321-1497");
suppliers table...
CREATE TABLE suppliers(
supp_id int NOT NULL,
company_name character(15) NOT NULL,
town character(15)
phone character(15)
primary key(supp_id)
);
This occurs when you have a primary key but do not give it an initialization value. The insert itself is causing the duplication.
In your case, two possibilities come to mind:
supp_id is the primary key and declared as a number. In older versions of MySQL, I think the string values get silently converted to numbers. Because the leading characters are letters, the value is 0.
You have another id field that is the primary key, but given no value and not declared auto_increment.
EDIT:
I suspect you want the following code:
CREATE TABLE suppliers (
supplierId int NOT NULL auto_increment primary key,
supp_name varchar(255) unique,
company_name varchar(15) NOT NULL,
town varchar(15),
phone varchar(15)
);
INSERT INTO Suppliers(supp_name, company_name, town, phone)
Values ('ADT217', 'AdTec', 'Birmingham', '0121-368-1597'),
('CPS533', 'CPS', 'Maidenhead', '01382-893715'),
('FCL162', 'ForComp Ltd', 'Nottingham', '01489-133722'),
('KBC355', 'KBC Computers', 'Glasgow', '0141-321-1497');
Some notes:
Usually you want varchar() rather than char(), unless you really like lots of spaces at the end of strings.
I added a unique supplier name to the table and declared the id to be a auto_increment.
Single quotes are ANSI standard for string constants. MySQL (and some other databases) allow double quotes, but there is no reason to not use the standard.
With your table you can get the error like "Incorrect Integer Value", but depending on MySQL server configuration it can do conversion(string->int) automatically for your query string must become "0" as result of this it makes 2 rows with 0 as supp_id and get error Duplicate entry '0' for key 'PRIMARY'. I guess you are using InnoDB as table type, in this case query will run as transaction and it will rollback after first error(for this example it will be second row).
DROP TABLE suppliers; -- Will drop your old table
CREATE TABLE suppliers(
supp_id varchar(30) NULL, -- You can set length as you wish
company_name character(15) NOT NULL,
town character(15),
phone character(15),
primary key(supp_id)
);
INSERT INTO Suppliers
(supp_id,company_name,town,phone)
Values
("ADT217","AdTec","Birmingham","0121-368-1597"),
("CPS533","CPS","Maidenhead","01382-893715"),
("FCL162","ForComp Ltd","Nottingham","01489-133722"),
("KBC355","KBC Computers","Glasgow","0141-321-1497");
After changing type insert will work without problems.
In Wordpress, when we clone the website, the media and user roles are not working. The error is as below:
WordPress database error Duplicate entry '0' for key 'PRIMARY' for query
INSERT INTO `wp_334_actionscheduler_logs`
(`action_id`, `message`, `log_date_gmt`, `log_date_local`)
VALUES (0, 'action complete via WP Cron', '2021-02-17 05:29:40',
'2021-02-17 05:29:40')
made by
do_action_ref_array('action_scheduler_run_queue'),
WP_Hook->do_action,
WP_Hook->apply_filters,
ActionScheduler_QueueRunner->run,
ActionScheduler_QueueRunner->do_batch,
ActionScheduler_Abstract_QueueRunner->process_action,
do_action('action_scheduler_after_execute'),
WP_Hook->do_action,
WP_Hook->apply_filters,
ActionScheduler_Logger->log_completed_action,
ActionScheduler_DBLogger->log
Related
USE Airline;
CREATE TABLE Responsible_for(
Time_work TIME NOT NULL,
date_work DATE NOT NULL,
Staff_ID INT NOT NULL,
Passenger_ID VARCHAR(45) NOT NULL,
CONSTRAINT FOREIGN KEY(Passenger_ID) REFERENCES Passenger(Passenger_ID),
CONSTRAINT FOREIGN KEY(Staff_ID) REFERENCES Staff(Staff_ID));
SELECT * FROM airline.Responsible_for;
INSERT INTO Responsible_for VALUES(
('04:00:00','2019-04-01',1235,'1102546778'));
why there is error?
thank you
You have an additional pair of parentheses around the list of values that should not be there.
That should be:
INSERT INTO Responsible_for(time_work, date_work, staff_id, passenger_id)
VALUES ('04:00:00','2019-04-01',1235,'1102546778');
Notes:
it is a good practice to always enumerate the columns to insert; this prevents hard-to-debug issues, and can make the code resilient to changes in the structure of the target table
you use airline at the beginning of the script, so there is no need to prefix the table name with the schema name in the insert statement
I would recommend against storing the date and time components in separate columns; this makes things unnecessarily complicated (and less efficient) when you need to compare it against a datetime; MySQL has the datetime datatype, that is meant to store both together
i have created a table in mysql named as student with 2 columns named as "S-id int not null auto_increment 14012040" and "S-name varchar(45) not null unique" "primary key(S-id)"....
the table was successfully created..but after inserting one record into db ,on the next insertion it shows error like "dupliction of primary key is not allowed"...plz hlp me whta should i do..
in th below i am posting the screen shots....
creating table.
[1st insertion successfully addesd][2]
getting error
Your primary key S-id has a default value (14012040).
You only inserts values for S-name and studentcol columns therefore it will use the S-ids default value again and again.
When it runs first it can use the default value because it is not exists in the table. But second time it will throw an error.
You should use auto increment for S-id as Álvaro Touzón said.
UPDATE:
According to your comment, here is the working create script:
CREATE TABLE student (
S_id INT NOT NULL AUTO_INCREMENT
,S_name VARCHAR(45) NOT NULL
,PRIMARY KEY (S_id)
,UNIQUE INDEX S_name_UNIQUE(S_name ASC)
) AUTO_INCREMENT=14012040;
Working SQL fiddle here.
Need help how to solve this problem...
I have created a users table which has following columns
Create table users
(
uid int(10) PRIMARY KEY AUTO_INCREMENT,
uname varchar(50),
password varchar(50),
email varchar(50)
);
when i insert values with uid it executes successfully :
Insert into users values(1,'ABC','Helloworld','ABC#gmail.com');
but when i try without uid
Insert into users values('SDC','Helloworld','SDC#gmail.com');
it does not execute successfully and gives an error
ERROR 1136 (21S01): Column count doesn't match value count at row 1
my uid has AUTO_INCREMENT so it should automatically increase..
Of course auto_increment is working correctly. You just need to learn best practices about using insert. Always list all the columns (unless you really, really know what you are doing):
Insert into users (uname, password, email)
values('SDC', 'Helloworld', 'SDC#gmail.com');
The id column will be auto-incremented. If you don't list the columns, then MySQL expects values for all columns, including the auto-incremented one.
I'm currently having issues with inserting values into a database table that uses a foreign key from another table to align the is together. The tables are pretty simple. One holds information about a project, and the other hold values for the project images. Here they are in detail.
The projects table
project_id int(50) PRIMARY KEY NOT NULL AUTO_INCREMENT,
project_name varchar(50) NOT NULL,
project_permitted timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT "The date that the project took place.",
project_in varchar(50) NOT NULL COMMENT 'The place where the project took place (ie the city and state).',
project_type varchar(50) NOT NULL COMMENT 'The project type (ie residentual, commercial, etc).',
project_description longtext,
project_published timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
Here is the second table called project_images
image_id int(50) PRIMARY KEY NOT NULL AUTO_INCREMENT,
project_id int(50),
image_url varchar(50) NOT NULL,
CONSTRAINT fk_projects FOREIGN KEY (project_id) REFERENCES projects(project_id)
What I am trying to do is insert values into the second table using the project_id from the projects table using a subquery. That query looks like this:
insert into project_images (project_id, project_url, project_description)
values (
(select project_id from projects where project_name = 'The Venue'),
"images/theVenue.png",
"The Venue: an appartment complex in Austin, Texas."
)
With this query I keep getting an error that says
something to the effect of "You are missing a comma or closing bracket
near project_id.
Can anyone help or point out the best way to handle this situation.
Modify your query to be like
insert into project_images (project_id, project_url, project_description)
select project_id ,
"images/theVenue.png",
"The Venue: an appartment complex in Austin, Texas."
from projects where project_name = 'The Venue';
After looking into this question a bit more, it seems that you cannot use a subquery the way I am using it to get the value of a column, However, the column can be inserted directly so long as the foreign key points to a primary key from another table that has already be inserted. The whole point to using this query was for a PHP project, so I guess I'll just do a select query in a project to get its ID then add that to the sql that queries the project_images table. This seems to be the only way to do that.
I have created a table empInfo as follow
CREATE TABLE empInfo (
empid INT(11) PRIMARY KEY AUTO_INCREMENT ,
firstname VARCHAR(255) DEFAULT NULL,
lastname VARCHAR(255) DEFAULT NULL
)
Then I run below Insert statements :-
INSERT INTO empInfo VALUES(NULL , 'SHREE','PATIL');
INSERT INTO empInfo(firstname,lastname) VALUES( 'VIKAS','PATIL');
INSERT INTO empInfo VALUES(NULL , 'SHREEKANT','JOHN');
I thought first or Third SQL will fail as empid is PRIMARY KEY and We are trying to insert NULL for empid .
But MYSQL proved me wrong and all 3 queries ran successfully .
I wanted to know Why it is not failing when trying to insert NULL in empid column ?
Final Data available in table is as below
empid firstname lastname
1 SHREE PATIL
2 VIKAS PATIL
3 SHREEKANT JOHN
I can figure out that it has something releted to AUTO_INCREMENT But I am not able to figure out reason for it . Any pointers on this .
This behaviour is by design, viz inserting 0, NULL, or DEFAULT into an AUTO_INCREMENT column will all trigger the AUTO_INCREMENT behaviour.
INSERT INTO empInfo VALUES(DEFAULT, 'SHREEKANT','JOHN');
INSERT INTO empInfo VALUES(NULL, 'SHREEKANT','JOHN');
INSERT INTO empInfo VALUES(0, 'SHREEKANT','JOHN');
and is commonplace practice
Note however that this wasn't however always the case in versions prior to 4.1.6
Edit
Does that mean AUTO_INCREMENT is taking precedance over PRIMARY KEY?
Yes, since the primary key is dependent on the AUTO_INCREMENT delivering a new sequence prior to constraint checking and record insertion, the AUTO_INCREMENT process (including the above re-purposing of NULL / 0 / DEFAULT) would need to be resolved prior to checking PRIMARY KEY constraint in any case.
If you remove the AUTO_INCREMENT and define the emp_id PK as INT(11) NULL (which is nonsensical, but MySql will create the column this way), as soon as you insert a NULL into the PK you will get the familiar
Error Code: 1048. Column 'emp_id' cannot be null
So it is clear that the AUTO_INCREMENT resolution precedes the primary key constraint checks.
It is exactly because of the auto increment. As you can see, no empid values are null in the db. That is the purpose of auto increment. Usually you would just not include that column in the insert, which is same as assigning null
As per the documentation page:
No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign 0 to the column to generate sequence numbers. If the column is declared NOT NULL, it is also possible to assign NULL to the column to generate sequence numbers.
So, because you have an auto increment null-allowed field, it ignores the fact that you're trying to place a NULL in there, and instead gives you a sequenced number.
You could just leave it as is since, even without the not null constraint, you can't get a NULL in there, because it will auto-magically convert that to a sequenced number.
Or you can change the column to be empid INT(11) PRIMARY KEY AUTO_INCREMENT NOT NULL if you wish, but I still think the insert will allow you to specify NULLs, converting them into sequenced numbers in spite of what the documentation states (tested on sqlfiddle in MySQL 5.6.6 m9 and 5.5.32).
In both cases, you can still force the column to a specific (non-zero) number, constraints permitting of course.
CREATE TABLE empInfo (
empid INT(11) PRIMARY KEY AUTO_INCREMENT NOT NULL,
firstname VARCHAR(255) DEFAULT NULL,
lastname VARCHAR(255) DEFAULT NULL
)
Not sure but i think it will work :)