I am working from this database, its one of the first I have tried building:
http://sqlfiddle.com/#!2/38ef8
When I try to add this line:
Insert Into country (name) values ('US');
It says Field 'id' doesn't have a default value. Am I doing my primary key correctly? I have seen people using "auto_incrment" on their primary key like this example:
http://sqlfiddle.com/#!2/c807a/2
Is that what I should be using?
If you didn't specify PRIMARY KEY column as AUTO_INCREMENT then you have to give values manually, for example:
INSERT INTO Country(id, name) values(1, 'US');
It's up to you wheter use AUTO_INCREMENT or not. There are many reasons to do it and many not to do it:
Pros and Cons of autoincrement keys on "every table"
Should each and every table have a primary key?
there are the properties of PRIMARY key
1 : cant be NULL
2 : cant be duplicate
now when you select AUTO_INCREMENT , every time you use the query
Insert Into country (name) values ('US');
it automatically generates a number incrementing the highest value existing in the table for the primary key column
but when you do not set the primary key as AUTO_INCREMENT ,
Insert Into country (name) values ('US');
this query will enter NULL values in every column for the row except the given column
in that case your PRIMARY_KEY also gets a null value
which clearly contradicts with the definition of PRIMARY_KEY .
that is why you get the error
I hope the explanation serves
If you have not set your primary key as auto increment, you will have to insert that manually in your queries.
The primary key should be set to AUTO_INCREMENT, if it is not so, you will have to set that manually.
Although you can still insert with specific values after setting the primary key to AUTO_INCREMENT provided the key is not already existing :D
Related
I've been trying to insert 3 Values in my varchar column K_Name but when I try to insert them with the INSERT INTO command it gives me the following error:
Well, you clearly have another column that is a primary key with a default value of 0 or '0'.
Your table should probably look like:
create table tblkunden (
kunden_id int auto_increment primary key,
k_name varchar(<whatever>)
);
Then your insert should work.
A primary key should not have a default value. Simply declaring it as a primary key means that it cannot be null and that duplicates cannot be inserted. Declaring it as auto_increment ensures that the value is assigned in an insert.
If you already have a primary key column and need only an autoincrement the you could try
ALTER TABLE tblkunden MODIFY COLUMN K_Nr INT NOT NULL AUTO_INCREMENT;
otherwise you should add the autoincrement clause at you table creation's script
Try -
INSERT INTO tblkunden (K_Nr, k_name)
VALUES(1,'Hans'),
(2,'Franz'),
(3, 'Peter');
This is because you can not have a NULL within a primary key which is the k_Nr column and because it is a primary key, it needs to be a unique value.
You can also use the primary key as an auto_increment which is mentioned in an answer above, this will increment each value by 1, you can change this to have a different increment if needed.
I hope this makes sense.
I´m creating a database addrees and I want to know what I need to set in Mysql to don´t store repeat values?
Like
Addrees 1 ("teste",1,new york,eua);
Addrees 2 ("teste",1,new york,eua);
If this happen my database will not store.
So what I need to do?
To alter an already existing table, run this MySQL command:
alter table yourtablename add unique index(firstcolumn, secondcolumn, thirdcolumn, fourthcolumn);
That'll add the unique constraint to the specified columns. Here's how to specify such a constraint in the CREATE TABLE.
CREATE TABLE buyers (
buyer_id INT UNSIGNED NOT NULL,
first_name CHAR(19) NOT NULL,
last_name CHAR(19) NOT NULL,
age SMALLINT NOT NULL,
post_code SMALLINT NOT NULL,
UNIQUE idx_flname_age (first_name,last_name,age)
);
The primary key constraint will do this too, as mentioned by #Ajeesh
EDIT:
As per the suggestion in the comment, if you want to avoid errors generated by this unique constraint, you have three good options:
INSERT IGNORE
and
INSERT...ON DUPLICATE KEY UPDATE
and
REPLACE
INSERT IGNORE will not do anything if the insert violates the unique constraint, except log a harmless warning. The table will be left as is, and no error would be reported. This may be desireable in some cases.
More commonly is the second option, ON DUPLICATE KEY UPDATE, which says "Well, if the key already exists, then update that key's row like this instead."
And lastly is REPLACE, which will, if the key already exists, delete the row, then do an INSERT as normal. If the key did not exist previously, it will simply act as an INSERT.
This stack overflow answer has some examples.
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
You need to call these fields a UNIQUE_KEY
To make a column to be distinct you need to have Primary Key constraint/Unique Key. Primary key is used for relating one table with another and it's values should not be NULL. But in your case you can have Unique constraint to store only unique/distinct values.
I've heard Primary Key means to be unique. Correct me please if I'm wrong.
Assume we have a table of users. It has 3 columns of id, username and password. We usually set the id to be AUTO_INCREMENT. So it would technically make a new unique id each time we add a row to the table. Then, why we also set the id column to be Primary Key or Unique?
Having a column as a key offers other aspects. First, if it is primary or unique, this would enforce that no query could enter a duplicate value for that key. Also keys can allow you do things like
INSERT ... ON DUPLICATE KEY UPDATE...
Of course you also want an index on the column for quick lookups.
AUTO_INCREMENT behavior only manifests when the column is not specified during an insert. Consider:
CREATE TABLE ai (
ai int unsigned not null auto_increment,
oi int unsigned,
key (ai),
primary key (oi)
);
INSERT INTO ai VALUES (1,2);
INSERT INTO ai VALUES (1,3);
INSERT INTO ai VALUES (null,5);
This will yield (1,2), (1,3), (2,5). Note how the AUTO_INCREMENT column has a duplicate.
A primary key does two things:
enforce database integrity (uniqueness and not-null of the column)
create an index to implement that, which also makes for fast look-up by the primary key column as a "side-effect".
You may not strictly need (1) if you can ensure that in your application code (for example by only using the auto-increment value), but it does not hurt.
You almost certainly want (2), though.
So it would technically make a new unique id each time we add a row to the table
Well, that is up to you. The unique id only gets inserted if you don't specify an explicit value. And technically, it is not guaranteed to be unique, it is just an auto-increment that does not take into consideration any existing values in the table (that may have somehow ended up in there).
i want to change the ids of a table to some other unique value.
This is a simplified example:
CREATE TABLE IF NOT EXISTS test (
id int(11) NOT NULL,
reverse_id int(11) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY reverse_id (reverse_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO test (id, reverse_id) VALUES ('1', '2'), ('2', '1');
UPDATE test SET id = reverse_id;
# Duplicate entry '2' for key 'PRIMARY'
I am looking for a command that checks only at the end of the UPDATE for the uniqueness of the id elements.
[I know that I can create a second row and change the status of this row to primary, then i can update the ids and reset the primary status, but i want to have one command, without adding or changing other rows, tables]
This is not possible with MySQL as far as I know.
It neither evaluates constraint on statement level (it does that on row level while processing) nor does it allow you to define them to be deferred (so the constraint would be evaluated at commit time).
The only option I can see if you want to "renumber" your primary key: drop the primary key, renumber the ids then re-create the primary key.
What if you create the table having reverse_id as its primary key? - that is unique in your definition so it is a valid candidate for primary key.
Primary keys are unique by definition - this constraint is stopping you from achieving what you want
I have a table with a unique key for two columns:
CREATE TABLE `xpo`.`user_permanent_gift` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`fb_user_id` INT UNSIGNED NOT NULL ,
`gift_id` INT UNSIGNED NOT NULL ,
`purchase_timestamp` TIMESTAMP NULL DEFAULT now() ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `user_gift_UNIQUE` (`fb_user_id` ASC, `gift_id` ASC) );
I want to insert a row into that table, but if the key exists, to do nothing! I don't want an error to be generated because the keys exist.
I know that there is the following syntax:
INSERT ... ON DUPLICATE KEY UPDATE ...
but is there something like:
INSERT ... ON DUPLICATE KEY DO NOTHING
?
Yes, use INSERT ... ON DUPLICATE KEY UPDATE id=id (it won't trigger row update even though id is assigned to itself).
If you don't care about errors (conversion errors, foreign key errors) and autoincrement field exhaustion (it's incremented even if the row is not inserted due to duplicate key), then use INSERT IGNORE like this:
INSERT IGNORE INTO <table_name> (...) VALUES (...)
HOW TO IMPLEMENT 'insert if not exist'?
1. REPLACE INTO
pros:
simple.
cons:
too slow.
auto-increment key will CHANGE(increase by 1) if there is entry matches unique key or primary key, because it deletes the old entry then insert new one.
2. INSERT IGNORE
pros:
simple.
cons:
auto-increment key will not change if there is entry matches unique key or primary key but auto-increment index will increase by 1
some other errors/warnings will be ignored such as data conversion error.
3. INSERT ... ON DUPLICATE KEY UPDATE
pros:
you can easily implement 'save or update' function with this
cons:
looks relatively complex if you just want to insert not update.
auto-increment key will not change if there is entry matches unique key or primary key but auto-increment index will increase by 1
4. Any way to stop auto-increment key increasing if there is entry matches unique key or primary key?
As mentioned in the comment below by #toien: "auto-increment column will be effected depends on innodb_autoinc_lock_mode config after version 5.1" if you are using innodb as your engine, but this also effects concurrency, so it needs to be well considered before used. So far I'm not seeing any better solution.
Use ON DUPLICATE KEY UPDATE ...,
Negative : because the UPDATE uses resources for the second action.
Use INSERT IGNORE ...,
Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.