UNIQUE Constraint not working? (Postgresql) - sql

I altered my postgresql database table to have a unique constraint like this:
ALTER TABLE my_table
ADD CONSTRAINT unique_values UNIQUE (value_one, value_two, value_three);
I want to not be able to post duplicate values for value_one, value_two, or value_three. So there should only ever be ONE unique value in these columns in the entire database.
But I'm still able to INSERT duplicate values in the value_one, value_two, and value_three columns.
What am I doing wrong?
Edit:
I have deleted all the duplicate data in the database, but get an error whenever I try to add a unique constraint to individual columns in the table.
Another thing, if I say:
ALTER TABLE my_table
ADD CONSTRAINT unique_values UNIQUE (value_one, value_two, value_three);
I do not get an error. But if I say:
ALTER TABLE my_table
ADD CONSTRAINT unique_values UNIQUE (value_one);
Like with just one value, I get this error:
could not create unique index "unique_values"

If you define a unique constraint over three columns, that means that you cannot insert the same three values a second time. But each of these columns can contain duplicate values. For example, these three rows would satisfy the uniqueness constraint:
(1, 2, 3)
(1, 2, 4)
(1, 5, 3)
but you would get an error if you inserted one of these triples a second time.
If you want each column to be unique, you have to define three constraints, one for each column.

Related

ADD combination constraint into a dabase table

I want to make a combination of columns in a table unique which they can not have any duplicates value.
For example, I have a table of Person which contain a name, age, address and phone_number.
I want that the combination of (name, age, phone_number) must be unique.
The table person contain this data:
"Name1"|22|"adresse1"|000000
So the combination (''Name1'' and 22 and 000000) it has to be unique but if only one of them changed for example ("name2",22,000000) it will be permitted to insert data to the table.
How can I manage that with SQL please?
If you want a column or combination of columns to be unique, you can implement a unique constraint or index (they are functionally equivalent for this purpose):
create unique index unq_t_col1_col2_col3 on t(col1, col2, col3);
And for a constraint:
alter table t add constraint unq_t_col1_col2_col3
unique (col1, col2, col3);
Any attempt to insert values into the columns that already exists will result in an error, as will any attempt to update the columns with values in a different row.

How to ensure that there are no duplicates in field? MS SQL Server 2014

I have the following table:
Customer (Id, Name, employeeID)
The table is already created and is empty, I don't want to remove duplicate data, all I want is to ALTER the table to ensure that there will be no duplicate data
I want to use ALTER and ensure that there are no duplicates in employeeID.
Will
ALTER TABLE Customers
UNIQUE(employeeID)
ADD CONSTRAINT
Is there a better way?
Adding a unique constraint will ensure that no duplicate entries will be added in future:
ALTER TABLE Customers
ADD CONSTRAINT choose_a_name_for_the_constraint UNIQUE (EmployeeID);
You had it basically right, just a bit of a keyword order problem..
If you're working with SQLS, consider also that trivial operations like this can be done via the GUI in SSMS, and it will guide the process. You can also get it to turn the changes into scripts for you by right clicking the table and choosing "Script Table As..." so you can use them elsewhere
From my understanding, I create Unique Index as follows,
create table unicondtional (
i int identity (1,1)
, j int
)
insert into unicondtional values (1), (1)
select * from unicondtional
-- assume 'unicondtional' is table like what you have, so far.
CREATE UNIQUE NONCLUSTERED INDEX unique_with_condition ON unicondtional
(
j
)
WHERE (i > 2) -- max (i)
-- create unique index with condition.
-- from the 'where' clause, we say that, Index should be ensure the unique value insertion.
insert into unicondtional values (1), (2), (3) -- See the Note.
-- successful insert.
select * from unicondtional
insert into unicondtional values (2)
-- due to the Unique Index, duplicate is not allowed by the Index.
update unicondtional
set j = 3
where j = 1
-- before the Index(On the first two rows), duplicates are exist.
select * from unicondtional
So, you don't need to delete the existing duplicate records.
Note: After the Index, if you consider the 1 as duplicate, then you go with Trigger instead of Unique Index.
Since your table is empty, you can directly run
ALTER TABLE Customers
ADD CONSTRAINT UQ_EmployeeID UNIQUE(EmployeeId);
That will ensure there is no duplicate EmployeeId can be added in that table.
But if there is some data in the table and there is already a duplicate EmployeeId you will get an error message
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'Customers' and the index name 'UQ_EmployeeId'. The duplicate key value is ("DuplicateValueHere").
For your question
Is there a better way?
You already have the better way to prevent inserting duplicates.
See
Create Unique Constraints
and
ALTER TABLE (Transact-SQL)

Is there an order to how unique constraint violations occur in oracle sql?

Given that we have a table like this,
table name: my_table;
columns: id, a, b, c;
primary key: id;
unique constraints: a, (b, c);
I want to know whether there is an ordering to how the unique constraints would fail.
With this setting, I do the following insert
insert into my_table values (1,2,3,4);
And then I do the same insert once more. Can I be sure that this second insert will fail because of the primary key violation, and not because of the unique key constraints on the other columns?
And then, if I try to do this insert into my_table values (2,2,3,4);, is there a way for me to make sure which unique constraint would fail first (the one on column a or the one on columns (b,c))?

Insert new row in sql table with same foreign key value

I need to be able to insert multiple rows in a table where one of the fields, a foreign key will be included in multiple rows.
Currently when I'm trying to do insert I'm getting this error:
An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.dll but was not handled in user code
Additional information: Cannot insert duplicate key row in object
'dbo.userGroupMembership' with unique index 'IX_userId'. The duplicate
key value is (264673).
Query I'm using:
INSERT INTO userGroupMembership(userId, usergroupId, created, adultAdminAccessLevel)
SELECT [userId], 12, GETDATE(), 0
FROM [dbo].[userGroupMembership]
where usergroupId = #UserGroupId
UserId is the foreign key field.
Any idea if I need to do any configuration change in the table or how can I be able to insert multiple rows with same foreign key?
You have a unique index allowing one row per userID. If you truly want more than one row per userID just drop the unique index.
DROP INDEX dbo.userGroupMembership.IX_userID;

SQL Insert values into table

I am trying to insert a row into my database table, but I keep on getting a SQL error.
I have a table called tbl_template_log, it has 3 Forgain Keys, user_id, temp_id, savedtemp_id, at the moment I only want to Insert a row with user_id and set temp_id and savedtemp_id to 0.
Query:
INSERT INTO tbl_template_log (user_id, temp_id, savetemp_id, send_date, send_to, email_send) VALUES (user_id=77, temp_id=0, savetemp_id=0, send_date='2013-10-10', send_to='test#test.com', email_send='hello')
Error:
INSERT INTO tbl_template_log (user_id, temp_id, savetemp_id, send_date, send_to, email_send) VALUES (user_id=77, temp_id=0, savetemp_id=0, send_date='2013-10-10', send_to='test#test.com', email_send='hello')
MySQL said: Documentation
#1452 - Cannot add or update a child row: a foreign key constraint fails (`admin_boltmail`.`tbl_template_log`, CONSTRAINT `tbl_template_log_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `tbl_user` (`user_id`))
From What I understand there is some sort of issue with user_id that the ID of the user has to be existing in tbl_user and ID 77 is an existing user id.....
Could some one point out a mistake I am doing. Thx
You can't add a row to this table unless the other tables specified in your foreign key constraints already have a record with the field value you're trying to insert. That's what a foreign key constraint means.
You're trying to break the rule you defined on your table. No, the database won't let you break the rule. You'll either have to add records to the foreign key tables or disable the constraints.