INSERT query for unique records-Mysql - mysql

I have a table like this
id | name | zip
1 | abc | 1234
2 | xyz | 4321
3 | asd | 1234
I want to insert records such that the id and name when inserted may have the same value but if the value of zip is also same for that particular record it is not inserted. If not it should be inserted.
eg: I can insert another row with value for id=1 and value for name= abc but if that record also has zip=1234 it should not be inserted.
How can I achieve this.

Create two unique indexes:
create unique index idx_table_name_zip on table(name, zip)
create unique index idx_table_id_zip on table(id, zip)
The database will then guarantee the uniqueness you want to enforce.

Make a Primary Key from id, name and zip combined
ALTER TABLE table ADD PRIMARY KEY(id, name, zip)
With this a row/record is marked duplicate if all the three columns are same otherwise it is a perfectly fine non-duplicate record.
check this for more here

you need to make a check before inserting the row, for exmpale
select * from table where zip = #zip and name = #name and id = #id
if no rows return you can do the insert...

Related

How to make unique combination of columns values?

I have a table with data like this:
id | link | name | date
1 aa bob 1
1 aa tom 2
1 bb tom 3
2 cc lora 4
It means I can have not unique values in any column but I CAN'T have the same row with identical id link name (date doesn't matter). This is the example what I can't have:
id | link | name | date
1 aa bob 1
1 aa bob 2
I tried to:
ALTER TABLE table ADD UNIQUE KEY `uk_id_link_name` (id, link, name);
also:
ALTER TABLE `table` ADD UNIQUE `unique_index`(`id`, `link`, `name`);
But it gives me an error:
Duplicate entry
How to make unique rows (combination of columns values which is not unique)?
EDIT: I don't want to delete duplicates from table.
Your table already violates the unique constraint. So you need to get rid of the offending values.
You can delete all but the earliest date:
delete t
from t join
(select id, link, name, min(date) as mindate
from t
group by id, link, name
) tt
using (id, link, name)
where date > mindate;
When the data is compatible, you can add the unique constraint.
Note: back up/make a copy of the table before doing this, so you don't lose data that you might really need.
The correct syntax for SQL Server should be the next:
ALTER TABLE TableName ADD CONSTRAINT ConstraintName UNIQUE (id, link, name)
But before create the constraint, of course you should ensure that there are not existing rows braking the constraint, for example using this query:
SELECT id, link, name, COUNT(*)
FROM TableName
GROUP BY id, link, name
HAVING COUNT(*) >= 2
This query returns the duplicates grouping by the three fields: id, link, name
If the query returns rows, you have to solve these duplicates before create the unique constraint.

Mysql : insert into select && where not exists

I need to insert some data in a table named ‘queue’ which is a patient queue in a particular date . Two fields data will be inserted .Two fields name are ‘PatientID’ and ‘Visiting Date’. Table ‘queue' like
QueueID | PatientID | Visiting_date |
-------------|-------------------|-------------------------|
1 | 4 | Current date |
table:queue
But while inserting the record there are two conditions :
Condition 1 : patitentID comes from patient table (given below)
Condition 2 : one record will be inserted to ‘queue’ table if it does not exist to prevent repeatation.ie PatientID=4 will not be inserted if already inserted.
-------------|-----------------|------------------|
patitentID | Patient Name | Contact no |
-------------|-----------------|------------------|
4 | David | 01245785874 |
table:patient
My SQL is: (it does not work)
INSERT INTO `queue`(`patientID`, `Visiting_date`)
SELECT patient.`patientID`,’CURDATE()’ FROM `patient`
WHERE NOT EXISTS (
SELECT `patientID`, `visiting_date`FROM `queue`
WHERE `patientID` = '4' AND `visting_date`=CURDATE()
) LIMIT 1;
You could set a foreign key to make sure the patients id exists.
In the Queue table you can set patientID as unique, this makes sure you can insert only unique id's in the queue table.
Also if you would like to be able to insert the same userID but with different dates you could specify unique constraint for multiple columns in MySQL.
If you want to solve it with a mysql query only you can use this question.
I would use a separate query to check if there is a user with that ID in that table.
SELECT * FROM queue WHERE PatientID = 4;
and then check the result of that query, if it returns a row, that means that there is a user in there and you don't do anything.
If the query doesn't return a row, that means you can now use a query to inert a user. Like this
INSERT INTO queue (PatientID, VisitingDate);

MySQL: INSERT ON DUPLICATE KEY UPDATE not all the fields

I have a users table as below:
id --- name --- email --- gender
id column is both primary key and unique key. Here I'd like to update the rows with new name and email information but I don't have to change their gender. I tried to update table using query:
INSERT INTO USERS VALUES(id, name, email) ON DUPLICATE KEY UPDATE name=VALUES(name), email=VALUES(email);
It did not work and alerted as:
Column count doesn't match value count at row 1
For example, assume we have one row as follows:
id=1 | name='Mike' | email='mike#mike.com' | gender='male'
How to use on-duplicate-key update to change name to 'Michael'?
id=1 | name='Michael' | email='mike#mike.com' | gender='male'
Thanks.
[UPDATE: adapted to question update]
Your problem is in the insert field already, you give only three values. For that you need
INSERT INTO users (id, name, email)
VALUES (42, "patrick","patrick#home")
ON DUPLICATE KEY UPDATE name="patrick", email="patrick#home";
But still think twice if your program really does what you want, especially if it is possible that two incoming requests get the same new id.

Select MySQL records that conflict with a proposed unique index

I have a set of records that I want to add a unique index to, however some existing records conflict with that index, so I want to identify them and remove them in order that the constraint can be placed on the data.
Is there a way I can write a SELECT query based around any record that contradicts the unique index?
Example:
Table has columns
id | user | question_id | response | is_current
I want a unique index such that
user | question_id | response |is_current
is not duplicated.
Is it possible to SELECT all records where that set of values is not unique?
Show non-unique:
select user,question_id,response,is_current,count(*) as theCount
from tablename
group by user,question_id,response,is_current
having theCount>1

Update Records in TargetTable from Source Table with Identical Name Records

I'm trying to update TableA with records from TableB but only where there are no records in TableA already existing with the same Name Column value. I have queries that will do that however what I'd like to do is in the cases where a 'matched' record exists but does not have values in Fieldx/y/z the existing record will update. For instance:
Target Table | Bob | NULL | NULL|
Source Table | Bob | New York | Doctor
The Target table would not have a new record created since 'Bob' exists but that existing record would have New York and Doctor added since those fields are NULL or empty/
You can do this with the on duplicate key update option to insert. First create a unique index on name, so duplicates are not allowed:
create unique index TargetTable_name on TargetTable(name);
Then:
insert into TargetTable(name, col1, col2)
select name, col1, col2
from SourceTable
on duplicate key update col1 = coalesce(TargetTable.col1, values(col1)),
col2 = coalesce(TargetTable.col2, values(col2));