INSERT statement conflicted with COLUMN FOREIGN KEY - sql

I have a FK in my table that looks like this:
Clearly, I should be able to insert NULL into this column as well as any value that exists in the parent table.
But when I try to insert NULL, I get the following error:
The INSERT statement conflicted with the FOREIGN KEY constraint
"users_fk". The conflict occurred in database "mydatabase", table
"dbo.country", column 'country_id'.

You are absolutely right - you should be able to insert NULL into this column.
Are you 500% sure that you are? The error message says something else - it appears as if you're inserting an invalid value.
Could it be that you have
(a) another line in your script that inserts additional (invalid) values?
Or
(b) do you happen to have a trigger on this table that does something invalid?
Update: (based on your comment)
If you're not specifying the column in the INSERT statement - then maybe an invalid default value is defined on that column? Something like a default of 0 or something.
If you do have a default value - that default value will be inserted (and not NULL, as you seem to be expecting)

Related

How can I INSERT into this table?

I have set a trigger up which I need to test. To do this I need to carry out an insert into the tblSOLine table however when I do this I am getting an error which I assume relates to the way the PK/FKs are set up. Is there any way I could do an insert into this table without messing with the table relationships?
Here is what I tried:
INSERT INTO tblSOLine (SOHeaderID, ProductID, Quantity, NetSale, VAT)
VALUES (5364, 6, 6, NULL, NULL)
Here is the error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tblSOLine_tblSOHeader".
The conflict occured in database "VintageSounds", table "dbo.tblSOHeader", column 'SOHeaderID'.
The error is saying that SOHeaderID = 5364 does not exist in SOHeader. You need to be sure that this value is what you intend.
You should not be getting an error if you attempt to insert this a headerid with this number, if the foreign key does not work. However, such ids are usually IDENTITY columns, so they are automatically generated. If you don't have a typo in the number, then perhaps you are confusing the number with something else, such as the customer number.

INSERT statement conflicted with foreign key constraint?

I'm having issue with an assignment I'm working on right now. The question is:
Write an INSERT statement that adds this row to the Products table:
ProductID: The next automatically generated ID
CategoryID: 4
ProductCode: dgx_640
ProductName: Yamaha DGX 640 88-Key Digital Piano
Description: Long description to come.
ListPrice: 799.99
DiscountPercent: 0
DateAdded: Today’s date/time.
Use a column list for this statement.
And the answer I came up with is:
INSERT INTO Products(CategoryID, ProductCode, ProductName, Description, ListPrice, DiscountPercent, DateAdded)
VALUES (4, 'dgx_640', 'Yamaha DGX 640 88-Key Digital Piano', 'Long description to come.', 799.99, 0, SYSDATETIME())
But when I try to execute it, an error comes up saying
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Products__Catego__3B75D760". The conflict occurred in database "MyGuitarShop", table "dbo.Categories", column 'CategoryID'.
The statement has been terminated.
Any help would be appreciated
The error is very clear - you're trying to insert a value into the CategoryID column of Products which causes a violation of the foreign key constraint to the category table.
This means: you're trying to insert a value (4) into Products.CategoryID which does not exist in the Category table. The foreign key constraint's job is to prevent exactly this case - it will not allow you to do this - for good reason.
So basically: you need to ensure that the values you're inserting into foreign key columns do exist in the referenced table (Category) before you do the INSERT.
The reference may not need to be enforced.
Make a new Database Diagram and add your two tables. Right click the connection line going between them, choose properties.
Where it says 'Enforce Foreign Key Constraint' change it to No.
This fixed the issue for me.
It is also possible that the number you're trying to insert and reference is an auto number row as a primary key in the connected table. I can only assume this can cause as issue, vs having the column be it's own editable column value.
you are trying to insert a value in the foreign key that doesn't exist in the table it reference, in you'r case it's the CategoryID.
to solve this you need to insert number 4 in the CategoryID column in the table catego first

Check constraint last_name capitalized

How can I make a check constraint that checks if last_name has the last 2 letters capitalized?
alter table clienti modify (nume_client constraint che_d check(nume_client=upper(substr(nume_client, -2, 1))));
I did like this, but I am getting the following error:
00000 - "cannot validate (%s.%s) - check constraint violated"
Your constraint is comparing the whole name to the upper-cased second-to-last character. It's only looking at one character, because you're supplying the third argument substring_length as 1. You need to check the last two characters; so you need to compare only those with the same two characters in upper-case:
substr(nume_client, -2) = upper(substr(nume_client, -2))
The error you are getting is because you have existing data which does not satisfy the constraint you are trying to add. That may be because your constraint isn't doing what you intended, as it will always return false in your original version.
If you get the same error with the modified check then you either need to remove or correct that data before you add the constraint, or use the novalidate clause:
check (substr(nume_client, -2) = upper(substr(nume_client, -2))) novalidate
Any existing constraint-violating rows will remain untouched, but you won't be able to add new rows that violate the constraint, or update existing rows to still-invalid values.
You can use your alter table modify (column...) syntax, or the simpler syntax Gordon Linoff showed; they do the same thing ultimately.
You might already have records there in table, that do not pass the check constraint. If it's OK to have the check only for future transactions you can use NOVALIDATE clause to constraint. E.g.
CREATE TABLE names (last_name VARCHAR2(100));
--Table created
INSERT INTO names VALUES ('Rambo');
--1 row inserted
INSERT INTO names VALUES ('GatES');
--1 row inserted
alter table names add constraint chk_che_d
check (SUBSTR(last_name,-2,1) = upper(substr(last_name, -2, 1))) NOVALIDATE;
--Table altered
INSERT INTO names VALUES ('Travolta');
--ORA-02290: check constraint (RO.CHK_CHE_D) violated
INSERT INTO names VALUES ('SkywalkER');
--1 row inserted
This is the syntax for adding a check constraint:
alter table clienti add constraint chk_che_d
check (nume_client = upper(substr(nume_client, -2, 1)));
I'm pretty sure the logic doesn't do anything useful (I'm pretty sure this will always return false). But the right syntax will get you on the right path.

Oracle Constraints error

I have a table x, and added a new column abc of number data type. New column successfully loaded with null values into table x.
When I was trying to add the same column with not null constraint, its giving an error : "table must be empty to add mandatory (not null) column"
I expected an error because as there is no data in it, I can't use not null constraint. But, what was not expecting this error. Why must the table be empty to add that constraint ? Could some one explain ?
It is because the null constraint is immediately violated as soon as you create the column. You could perhaps supply a default value.
An empty table would not have this problem due to lack of rows.
If you don't have data in the table, NOT NULL constraint is not violated. But if you have at least a single row, the constraint is violated because database have to create a column value for each row as NULL.
You can use a default value to overcome this issue:
ALTER TABLE tablename
ADD column_name NUMBER NOT NULL
DEFAULT '*';

add CHECK constraint to already populated table

I created a table called test with column called code:
create table test(
code char(3) not null);
I then populated the table with the following data:
insert into test values ('A12');
insert into test values ('B23');
insert into test values ('C45');
I then altered the column to make it char(4):
alter table test
alter column code char(4) not null;
I then added a 'X' to all existing data so that it becomes 4 characters long:
update test
set code='X'+code
where LEN(code)=3;
So far so good but then when I tried to add a check constraint:
alter table test
add constraint codeCheck check (code like 'A-Z''A-Z''0-9''0-9');
I got this error:
The ALTER TABLE statement conflicted with the CHECK constraint "codeCheck".
I understand that the error implies that the existing data violates the check constraint that I am trying to add into the table, but why?
and how do I do it such that the existing data and check constraint do not violate each other?
Your pattern syntax is wrong. It should be
alter table test
add constraint codeCheck check (code like '[A-Z][A-Z][0-9][0-9]');
Because your data doesn't match the like constraint.
Try
alter table test
add constraint codeCheck check (code like '[A-Z][A-Z][0-9][0-9]' );
I don´t know how it works with SQL Server but your like clause looks odd.
Try using
'[A-Z]{2}\d{2}'