Unique Column in mysql database - mysql

I m facing a probem and i don't believe that it can accept a solution so I hope if anyone knows a solution suggest it, please.
I have a column in my table that contains a certain records; some of those records are duplicated and I want to insert some new records into my table, but I wish for the new records to not be duplicated. So, basically I want to control when the data can be duplicated and when not.
I ve tried this but it does not work:
ALTER TABLE MyTable DROP PRIMARY KEY
ALTER TABLE MyTable
ADD PRIMARY KEY (`S.No`),
ADD UNIQUE KEY `PCID_uk` (`PCID`),
ADD UNIQUE KEY `USERNAME_uk` (`USERNAME`)

some of those records are duplicated and I want to insert some new records into my table, but I wish for the new records to not be duplicated
Constraints are meant to guarantee integrity over the whole table, so what you ask for is not not straight forward, but still possible.
The idea is to create a new column with a default value of 1, and then feed it using row_number() (available in MySQL 8.0). Assuming that the primary key of your table is id, and that you want to enforce partial uniqueness on column col, that would look like:
alter table mytable add col_rn int default 1;
update mytable t
inner join (
select id, row_number() over(partition by col order by id) rn
from mytable
) t1 on t1.id = t.id
set t.col_rn = t.rn;
With this set up at hand, you can create the following unique constraint
alter table mytable add constraint unique_col_rn unique (col, col_rn);
Now you can insert new records in your table, not providing values for col_rn, so it defaults to 1. If a record already exists for col, the unique constraint raises an error.
insert into mytable (col) values (...);

Related

Unique key constraint without order of columns

I have a table
drug_interaction(drug1_id ,drug2_id )
I want to know if it is possible to have unique pairs of drug1_id and drug2_id without taking into consideration the order of the values. For example if (1,2) already exists in the table
then inserting (2,1) should not be allowed.
This is hard to do in MySQL. In many databases, you can ensure that the drugs are in order using a check constraint:
check (drug1_id < drug2_Id)
However, MySQL does not actually enforce these constraints.
The only way you can enforce this is using a trigger on the table.
One way to do it would be to create two computed columns that store the smallest and greatest drug_ids on each record, and the put a unique constraint on them.
Consider:
create table drug_interaction(
drug1_id int ,
drug2_id int,
drug_least int as (least(drug1_id, drug2_id)) stored,
drug_greatest int as (greatest(drug1_id, drug2_id)) stored,
unique key unique_drugs (drug_least, drug_greatest)
)
Demo on DB Fiddle:
insert into drug_interaction(drug1_id, drug2_id) values(1, 2)
-- ok
insert into drug_interaction(drug1_id, drug2_id) values(2, 1)
-- error: Duplicate entry '1-2' for key 'unique_drugs'

Sql Statement: Insert On Key Update is not working as expected when primary key is not specified in the fields to insert

Hello I am using the "INSERT ON DUPLICATE KEY UPDATE" sql statement to update my database.
All was working fine since I always inserted an unique id like this:
INSERT INTO devices(uniqueId,name)
VALUES (4,'Printer')
ON DUPLICATE KEY UPDATE name = 'Central Printer';
But for now, I need to insert elements but I don't insert a unique id, I only insert or update the values like this:
INSERT INTO table (a,b,c,d,e,f,g)
VALUES (2,3,4,5,6,7,8)
ON DUPLICATE KEY
UPDATE a=a, b=b, c=c, d=d, e=e, f=f, g=g;
Have to say that an autoincrement primary key is generated always that I insert a row.
My problem is that now the inserted rows are duplicated since I don't insert the primary key or unique id explicitly within the sql statement.
What I am supposed to do?
For example, maybe I need to insert the primary key explicitly? I would like to work with this primary autoincremented key.
For recommendation from Gordon I am adding a sample case the you can see in the next image
Rows Output
In this case I add the first three rows, and then I try to update the three first rows again with different information.... Ok I am seeing the error... There is no key to compare to...... :$
Thanks for your answers,
If you want to prevent columns from being duplicated, then create a unique index or constraint on them. For instance:
create unique index unq_table_7 on table(a, b, c, d, e, f, g);
This will guarantee that the 7 columns -- in combination -- are unique.

Change the ids in my SQL Server table so they would be a sequence

I have a table with a unique auto-incremental primary key. Some entries have been deleted from the table, so there are gaps in the ids, it is not a sequence.
I need a query that will make it a sequence. the table is not connected with any other table, so I can temporarily remove the pk and auto-increment from the id column (until the ids will be a sequence).
I use SQL server
If possible, I want to run the query starting from specific id
You cannot update identity column values, nor you can remove the identity from the column, update the values and set it back. You must create a new table with the same schema, copy the data from the old table, but for ID generate a new value, drop the old table and rename the new one to keep the same name.
use [tempdb]
go
if OBJECT_ID('TestTable') is not null
drop table TestTable
go
create table TestTable (
ID int not null primary key clustered identity(1,1)
, Name varchar(50)
)
insert into TestTable(Name) values
('Row #1'),('Row #2'),('Row #3'),
('Row #4'),('Row #5'),('Row #6'),
('Row #7'),('Row #8'),('Row #9')
delete from TestTable where ID in (3, 4, 8) -- Make some gaps
create table TestTable_NEW (
ID int not null primary key clustered identity(1,1)
, Name varchar(50)
)
insert into TestTable_NEW(Name)
select Name
from TestTable
order by ID -- Preserve the rows order
drop table TestTable
exec sp_rename N'TestTable_NEW', N'TestTable'
However, I will not recommend doing this at all. Identity values are supposed to be immutable. They should never change. If you have problems with gaps, then do not allow deletion of existing records. Also, identity do not guarantee that there will be no gaps in the sequence. Only that the values will be unique and increasing. So you should definitely reconsider your database and/or application design, because it is flawed.

check if data exists before insert and return true/false?

Solution:
Place unique constraint on multiple columns
ALTER TABLE rating ADD UNIQUE KEY ( id , id );
I want to insert a score in my rating system. I want to be able to insert data if it doesn't exist. I also want the same query to return true/false if it does exist.
I looked into INSERT IGNORE but that silently fails so I don't know how to check against that.
I know I could attempt a SELECT ... WHERE id = 1 and THAN do the insert, but I want to move this down to a single insert, is this possible?
If you use a unique key constraint on the column or columns you want to check against, then a normal insert will succeed if there is no data already, or fail noisily due to unique key constraint if there is already something matching.
INSERT INTO `rating` (value1)
SELECT 'your rate for value1' FROM `rating`
WHERE NOT EXISTS (SELECT * FROM `rating`
WHERE value1='your rate for value1' ) LIMIT 1;

MySQL on duplicate key on a non-unique field

I have a table containing all sort of parameters.
The structure of the table is : id, object_id, param_name, param_value
The following code works, but it appends results instead of updating them.
The fact is that I can't use ON DUPLICATE KEY because my fields are non-uniques (except for id of course)
INSERT INTO `params_table` (`object_id`, `param_name`, `param_value`)
SELECT
A.id AS my_object_id,
'XYZ' AS my_param_name,
IF(TMP.abc IS NULL,0,1) AS my_param_value
FROM
ref_table AS A
LEFT JOIN tmp_table AS TMP ON TMP.abc = A.abc
ON DUPLICATE KEY
UPDATE `param_value` = IF(TMP.abc IS NULL,0,1);
The ON DUPLICATE KEY clause does not only work on the primary key:
If you specify ON DUPLICATE KEY
UPDATE, and a row is inserted that
would cause a duplicate value in a
UNIQUE index or PRIMARY KEY, an UPDATE
of the old row is performed
So unless I'm missing something obvious you simply need to create a unique index on the column combination you want to make unique:
ALTER TABLE params_table
ADD UNIQUE unique_object_param(object_id,param_name);