Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Foreign Key constraints get checked on an SQL update statement that doesn't update the columns with the Constraint?

Do Foreign Key constraints get checked on an SQL update statement that doesn't update the columns with the Constraint? (In MS SQL Server)

Say I have a couple of tables with the following columns:

OrderItems

    - OrderItemID
    - OrderItemTypeID (FK to a OrderItemTypeID column on another table called OrderItemTypes) 
    - ItemName

If I just update

update [dbo].[OrderItems]
set    [ItemName] = 'Product 3'
where  [OrderItemID] = 2508 

Will the FK constraint do it's lookup/check with the update statement above? (even thought the update is not change the value of that column?)

like image 270
John Egbert Avatar asked Sep 27 '11 18:09

John Egbert


People also ask

Do foreign keys get automatically update?

No the foreign key is not updated automatically.

Which of the following is not true about a foreign key constraint?

Q 26 - Which of the following is not true about a FOREIGN KEY constraint? A - It is a referential integrity constraint.

How can check foreign key constraint in SQL query?

Using SQL Server Management Studio Open the Table Designer for the table containing the foreign key you want to view, right-click in the Table Designer, and choose Relationships from the shortcut menu. In the Foreign Key Relationships dialog box, select the relationship with properties you want to view.

Can you update a foreign key in SQL?

To modify a foreign key. In Object Explorer, expand the table with the foreign key and then expand Keys. Right-click the foreign key to be modified and select Modify.


2 Answers

No, the foreign key is not checked. This is pretty easy to see by examining the execution plans of two different updates.

create table a (
    id int primary key
)

create table b (
    id int, 
    fkid int
)

alter table b add foreign key (fkid) references a(id)

insert into a values (1)
insert into a values (2)

insert into b values (5,1) -- Seek on table a's PK

enter image description here

update b set id = 6 where id = 5 -- No seek on table a's PK

enter image description here

update b set fkid = 2 where id = 6 -- Seek on table a's PK

enter image description here

drop table b
drop table a
like image 154
Joe Stefanelli Avatar answered Oct 06 '22 20:10

Joe Stefanelli


No. Since the SQL update isn't updating a column containing a constraint, what exactly would SQL Server be checking in this case? This is similar to asking, "does an insert trigger get fired if I only do an update?" Answer is no.

like image 21
Randy Minder Avatar answered Oct 06 '22 19:10

Randy Minder