So I made a basic database with a table named "logs". In logs, I made a column (let's say "ID").
Next, I coded some PHP (INSERT INTO logs (ID) VALUES ('$ID');) and went to test it. I used the same value 2 times, and I got an error: Duplicate entry.
I knew this would happen, but is it possible to allow 2 or more rows to be the same in a CHAR( 255 ) column?
Any help will be appreciated.
If you don't make a field as primary key, or unique you can place duplicates there. The same applies for your Char(255) column.
Fields are by default not primary keys, and not unique. So, unless you change it yourself, duplicates are allowed.
Related
everyday i add almost 5000 new records in mysql and i want to prevent insert duplicate row in table,i think i should check all of the bank befor any insert operation,is it suitable?
Or there is any better way to do that??
thanks in advance
It's a good choice to prevent the data model beeing corrupted by software by applying a unique index to the field attributes which must not be duplicatable.
It's even better to ask the database for duplicate candidates before inserting data.
The best is, to have both combined. The security on the database model and the question for duplicates in the software layer because a) error handling is much more expensive than querying and b) the constraint protects the data from human failure.
mysql supports unique indexes with the CREATE UNIQUE INDEX statement.
e.g: CREATE UNIQUE INDEX IDX_FOO ON BAR(X,Y,Z);
creates a unique index on table BAR. This index will also be used when running the query for duplicates - speeds up the processing very much.
See MySQL Documentation for more details.
When you have a data integrity issue, you want the database to enforce the rules (if possible). In your case, you do this with a unique index or unique constraint, which are two names for the same thing. Here is sample syntax:
create unique index idx_table_col1_col2 on table(col1, col2)
You want to do this in the database, for three reasons:
You want the database to know that that column is unique.
You do not want a multi-threaded application to "accidentally" insert duplicate values.
You do not want to put such important checks into the application, where they might "accidentally" be removed.
MySQL then has very useful constructs to deal with duplicates, in particular, insert . . . on duplicate key update, insert ignore, and replace.
When you run SQL queries from your application, you should be checking for errors anyway, so catching duplicate key errors should be no additional burden on the application.
Firstly, any column that needs to be unique you can use the UNIQUE constraint:
CREATE TABLE IF NOT EXISTS tableName
(id SERIAL, someUniqueColumnName VARCHAR(255) NOT NULL UNIQUE);
See the MySQL Documentation for adding uniqueness to existing columns.
You need to decide what constitutes a duplicate in your table, because uniqueness is not always restricted to a single column. For instance, in a table where you store users with a corresponding id for something else, then it may be both combined which have to be unique. For that you can have PRIMARY KEY which uses two columns:
CREATE TABLE IF NOT EXISTS tableName (
id BIGINT(20) UNSIGNED NOT NULL,
pictureId BIGINT(20) UNSIGNED NOT NULL,
someOtherColumn VARCHAR(12),
PRIMARY KEY(id, pictureId));
I have a 'code_number' column with varchar(25) field type, and I make it into Unique field type. I try to insert 2 number to the number column with different number. First number is '112225577' and for the second number is '112228899'. Now I'm trying to update the first number, and only change 3 last digit number '577' with '433', became '112225433'. But I got error Duplicate entry '112225433' for key 'code_number'.
How can it be duplicate? I only have 2 data and the data is not same. Can anybody explain to me why this happening?
UPDATE
here is my code.
Product
id INT(11)
product VARCHAR(250)
code_number VARCHAR(25) UNIQUE
...
Account
id INT(11)
name VARCHAR(250)
email VARCHAR(100) UNIQUE
...
And my query is like this:
$this->db->set('code_number','112225433');
$this->db->where('code_number','112225577');
$this->db->update('product');
Same problem goes to email column when i try to update account record.
here is the code sample:
$this->db->set('email','andy123#yahoo.com');
$this->db->where('name','Andy');
$this->db->update('account');
the email data in email column where name='Andy' is 'andy123#hotmail.com'.
You can definitely do this without a problem (see the SQL Fiddle here).
I imagine that you are doing something where both rows are getting updated to the same value, the equivalent of:
update t
set code_number = '112225433';
This will generate exactly the error you report. There are, no doubt, many SQL queries that would have this effect. But, this would generate such an error.
It could be a problem with your SQL editor. For instance, it could show you the previous value but it could have update it already, so that you you believe that it has not been changed yet. I ever had such problem like this before: the value was updated in the DB but the editor had no updated yet.
I am working with an old MySQL table, which serves as a log of sorts. It looks like
CREATE TABLE `queries` (
`Email` char(32) NOT NULL DEFAULT '',
`Query` blob,
`NumRecords` int(5) unsigned DEFAULT NULL,
`Date` date DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Now, I need to be able to UPDATE the records in this table (don't ask why, I don't know). Normally, I would just do
UPDATE table SET ... WHERE unique_column = value
But in this case, I don't have a unique column to work from.
Is there a workaround for this, or am I just going to have to push to put in a nice, standard INT NOT NULL AUTO_INCREMENT?
UPDATE queries
SET ...
WHERE Email = value1
AND Query = value2
AND NumRecords = value3
AND Date = value4
LIMIT 1;
A unique identifier is the only reliable way of doing this. Just add an auto_increment column and be done with it.
For exhaustive info including some workaround approaches (none of them perfect though!) check this question, where the OP had a table without a unique identifier and no way to change it.
Update: As Doug Currie points out, this is not entirely true: A unique ID is not necessary as such here. I still strongly recommend the practice of always using one. If two users decide to update two different rows that are exact duplicates of each other at the exact same time (e.g. by selecting a row in a GUI), there could be collisions because it's not possible to define which row is targeted by which operation. It's a microscopic possibility and in the case at hand probably totally negligeable, but it's not good design.
There are two different issues here. First, is de-duping the table. That is an entirely different question and solution which might involve adding a auto_increment column. However, if you are not going to de-dup the table, then by definition, two rows with the same data represent the same instance of information and both ought to be updated if they match the filtering criteria. So, either add a unique key, de-dup the table (in which case uniqueness is based on the combination of all columns) or update all matching rows.
In case you didn't know this, it will affect performance, but you don't need to use a primary key in your WHERE clause when updating a record. You can single out a row by specifying the existing values:
UPDATE queries
SET Query = 'whatever'
WHERE Email = 'whatever#whatever.com' AND
Query = 'whatever' AND
NumRecords = 42 AND
Date = '1969-01-01'
If there are duplicate rows, why not update them all, since you can't differentiate anyway?
You just can't do it with a GUI interface in MySQL Query Browser.
If you need to start differentiating the rows, then add an autoincrement integer field, and you'll be able to edit them in MySQL Query Browser too.
Delete the duplicates first. What's the point of having duplicate rows in the table (or any table for that matter)?
Once you've deleted the duplicates you can implement the key and they your problem is solved.
I'm planning to make a very simple program using php and mySQL. The main page will take information and make a new row in the database with that information. However, I need a number to put in for the primary key. Unfortunately, I have no idea about the normal way to determine what umber to use. Preferably, if I delete a row, that row's key won't ever be reused.
A preliminary search has turned up the AUTOINCREMENT keyword in mySQL. However, I'd still like to know if that will work for what I want and what the common solution to this issue is.
In MySQL that's the standard solution.
CREATE TABLE animals (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
);
Unless you have an overriding reason to generate your own PK then using the autoincrement would be good enough. That way the database manages the keys. When you are inserting a row you have to leave out the primary key column.
Say you have a table table = (a, b, c) where a is the primary key then the insert statement would be
insert into table (b, c) values ('bbb', 'ccc')
and the primary key will be auto inserted by the databse.
AUTOINCREMENT is what you want. As long as you don't change the table's settings, AUTOINCREMENT will continue to grow.
AUTOINCREMENT is the standard way to automatically create a unique key. It will start at 1 (or 0, I can't remember and it doesn't matter) then increment with each new record added to the table. If a record is deleted, its key will not be reused.
Auto increment primary keys are relatively standard depending on which DBA you're talking to which week.
I believe the basic identity integer will hit about 2 billion rows(is this right for mySQL?) before running out of room so you don't have to worry about hitting the cap.
AUTO_INCREMENT is the common choice, it sets a number starting from 1 to every new row you insert. All the work of figuring out which number to use is done by the db, you just ask it back after inserting if you need to ( in php you get it by callin mysql_last_insertid I think )
For something simple auto increment is best. For something more complicated that will ultimately have a lot of entries I generate a GUID and insert that as the key.
I'm working on a script that sadly I inherited - with no commenting or anything. Argh!
For testing purposes I duplicated one of the tables in the database which had an auto-incrementing ID. When the data is saved to the database, though, the ID number just reads "0" -- which is the default for that column. I'm not sure why it's not auto increasing anymore... any thoughts? Thank you!
Are you sure you set the field in the duplicate table to auto-increment? Try running:
ALTER TABLE `duplicate_table` CHANGE `ai_key` `ai_key` INT( key_length ) NOT NULL AUTO_INCREMENT
And see if it is set or not.
Did you create the new table from scratch or as a real copy? If the column is supposed to auto increment it should be a primary (or at least a unique) key, with no default value.
Just to double check use the sql statement to show the show create table syntax for both tables and compare.
show create table <table>
It sounds like your column isn't actually auto_increment any more. This has happened to me a couple of times because there was a bug (?) in phpMyAdmin which I used to create backups: it wouldn't add the auto_increment keyword into the CREATE TABLE statements. That was a massive pain in the butt...