I have the following T-SQL in VS2013:
CREATE TABLE [dbo].[Jugo]
(
[JugoID] INT IDENTITY (1, 1) NOT NULL,
[Jugo] NVARCHAR (50) NOT NULL,
[ColorID] INT NOT NULL,
[IngreID] INT NOT NULL,
PRIMARY KEY CLUSTERED ([JugoID] ASC),
FOREIGN KEY (ColorID) REFERENCES Color (ColorID)
ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (IngreID) REFERENCES Ingrediente (IngreID)
ON UPDATE CASCADE ON DELETE CASCADE
);
And I get the following message before updating the database:
Highlights
None
User actions
Create
Foreign Key: unnamed constraint on [dbo].[Jugo] (Foreign Key)
Foreign Key: unnamed constraint on [dbo].[Jugo] (Foreign Key)
Supporting actions
None
Can I proceed with these unnamed constraints? What would I need the constraints for?
For reference this is what I'm trying to do:
3 tables:
Jugo, Color, Ingrediente: so to create a jugo (juice) you specify name, color and ingredients, color and ingredients are on their own tables, hence the foreign keys I want to define.
Thanks.
As long as the ColorID and IngreID are both primary key in their own tables, you won't have any trouble.
But here's the catch, you didn't constrain your primary keys. It is a good practice to use constraint for every PRIMARY KEY you are using, in that way, when you foreign key it to another table. It can read that it is from another table. I don't know about SQL in VS2013 But here's my sample for SQL Server:
CREATE TABLE JUGO
(
JUGOID numeric identity (1,1) //For auto increment
CONSTRAINT PK_JUGOID PRIMARY KEY (JUGOID),
JUGO nvarchar(50) not null,
.
.
.
)
The PK_JUGOID in CONSTRAINT PK_JUGOID PRIMARY KEY (JUGOID), is user-defined, but it is a good practice to just copy the format of the primary key so you won't be confused when using foreign keys. :)
Foreign keys are for data consistency. You create the foreign keys on columns, so as not to allow invalid entries.
FOREIGN KEY (ColorID) REFERENCES Color (ColorID)
ON UPDATE CASCADE ON DELETE CASCADE,
This constraint makes sure that your jugo can only have a color that exists in the color table. Moreover you have two cascade commands:
ON UPDATE CASCADE means that if color red is ID 5, but you want to change it to 500, the change will be performed automatically for all jugo records. However, an ID should never change, so this is a clause seldom used.
ON DELETE CASCADE means that if you delete red, then you delete all red jugo records with it. I don't know if this is an appropriate case for you. It is used for instance on a users table. Remove a user, so you remove its complete data. But remove a color?
At last you should give your constraints names, so it's easier for you to deal with them.
CONSTRAINT pk_jugo PRIMARY KEY CLUSTERED ([JugoID] ASC),
CONSTRAINT fk_jugo_color FOREIGN KEY (ColorID) REFERENCES Color (ColorID),
CONSTRAINT fk_jugo_ingre FOREIGN KEY (IngreID) REFERENCES Ingrediente (IngreID)
Related
I have two tables: Ticket and TicketRelation. I am trying to relate 2 Tickets using the TicketRelation table.
I want to add a cascade constraint to both foreign keys.
I am using SQL Server Management Studio to add the constraints but I get this error:
Introducing FOREIGN KEY constraint 'FK_destiny_ticket' on table 'ticketRelation' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
I also tried to do this with a trigger, but I am not sure how to define it.
Here I provide the tables definitions:
This is the base entity TICKET
CREATE TABLE ticket
(
ticket_id BIGINT,
some_data VARCHAR (50),
CONSTRAINT PK_ticket PRIMARY KEY (ticket_id)
);
and the relational table TICKETRELATION
CREATE TABLE ticketRelation
(
origin_ticket BIGINT,
destiny_ticket BIGINT,
relation_data VARCHAR (50),
CONSTRAINT PK_ticket_relation PRIMARY KEY (origin_ticket, destiny_ticket),
CONSTRAINT FK_origin_ticket FOREIGN KEY (origin_ticket)
REFERENCES ticket(ticket_id),
CONSTRAINT FK_destiny_ticket FOREIGN KEY (destiny_ticket)
REFERENCES ticket(ticket_id),
)
I want to add an ON DELETE CASCADE constraint to both foreign keys:
CONSTRAINT FK_origin_ticket FOREIGN KEY (origin_ticket)
REFERENCES ticket(ticket_id)
ON DELETE CASCADE, -- I want to add this --
CONSTRAINT FK_destiny_ticket FOREIGN KEY (origin_ticket)
REFERENCES ticket(ticket_id)
ON DELETE CASCADE, -- and this --
I am getting Foreign key constraint while inserting the data into database as there is null data in key column. So if I disable foreign key by making Enforce Foreign Key Constraint to No, to insert that one row of data and enable it again for future transactions will it be a problem for the existing data?
You don't have to do anything special to accommodate NULLs in SQL Server foreign keys. If any of the referencing columns contain NULL then the foreign key constraint isn't checked and isn't violated:
create table T1 (
ID int not null,
constraint PK_T1 PRIMARY KEY (ID)
)
go
create table T2 (
ID int not null,
T1ID int null,
constraint PK_T2 PRIMARY KEY (ID),
constraint FK_T2_T1 FOREIGN KEY (T1ID)
references T1(ID)
)
go
insert into T1(ID) values (1),(2)
go
insert into T2(ID,T1ID) values (1,1), (2,null)
go
This runs without any errors.
In regard to disabling foreign keys, you should generally avoid doing this, especially if the goal is to insert data that violates the key. Even though you can re-enable the key in such a way that it only validates new data, the key will never be trusted (and rightfully so).
As such, the query optimizer will not be able to make use of the foreign key constraint to obtain optimal query plans.
I am trying to add foreign key to my existing column using below query
ALTER TABLE Sub_Category_Master
ADD FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
but I'm getting an error
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Sub_Categ__Categ__5812160E". The conflict occurred in database "shaadikarbefikar_new", table "shaadikarbefikar.Category_Master", column 'Category_ID'.
Well, the error clearly tells you that Category_ID in your Sub_Category_Master table contains some values that are not present in Category_Master (column Category_ID). But that's exactly the point of having a foreign key constraint - making sure your child table (Sub_Category_Master) only uses defined values from its parent table.
Therefore, you must fix those "voodoo" values first, before you're able to establish this foreign key relationship. I would also strongly recommend to explicitly name that constraint yourself, to avoid those system-generated, but not really very useful constraint names like FK__Sub_Categ__Categ__5812160E:
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FK_SubCategoryMaster_CategoryMaster
FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FKSub_Category_Master_Category_ID FOREIGN KEY (Category_ID)
REFERENCES Category_Master(Category_ID);
CREATE TABLE Orders
(
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
Is it possible to have a foreign key that references another foreign key in a different table, or can it only reference primary and unique keys?
A foreign key can reference any field defined as unique. If that unique field is itself defined as a foreign key, it makes no difference. A foreign key is just to enforce referential integrity. Making a field a foreign key doesn't change the field itself in any way. If it is a unique field, it can also be the target of another FK.
For example:
create table Table1(
PK int identity primary key,
...
);
create table Table2( -- 1-1 relationship with Table1
PKFK int primary key,
...,
constraint FK_Table2_1 foreign key( PKFK ) references Table1( PK )
);
create table Table3( -- relates to Table2
PKFKFK int primary key,
...,
constraint FK_Table3_2 foreign key( PKFKFK ) references Table2( PKFK )
);
I know of no DBMS where this is not the case. And I agree with Horse, there is nothing wrong with the practice.
Is it possible to have a foreign key that references another foreign key in a different table
Yes. In fact contrary to accepted answer, the referenced FK column doesn't even have to be unique! - at least in MySQL. see https://www.db-fiddle.com/f/6RUEP43vYVkyK2sxQQpBfj/0 for a demo of the same.
which brings up the question that if the FK is not unique in the parent table, then who is the parent row? The purpose of FKs is to establish parent-child relationship.
I am currently making a database back end system on an airport, using sql through the phpmyadmin server. The criteria is not meant to be perfect but one of the ideas behind the queries is to imagine that either a customer or flight dispatch officer might be looking at the tables. I was wondering if it was possible to reference a primary key as a foreign key across 2 or more tables. In the example below, I want to reference the model number as a foreign key in the bottom 2 tables. I have ensured that the type and character count are the same.
CREATE TABLE Aircraft_Model
(Model_Number varchar (12) NOT NULL,
seat_capacity int (3),
CONSTRAINT pk7 primary key (Model_Number));
CREATE TABLE Licence_type
(Rank varchar (25) NOT NULL,
Model_Number varchar (12),
CONSTRAINT pk9 primary key (Rank));
CREATE TABLE Aircraft
(Aircraft_ID varchar (4) NOT NULL,
Model_Number varchar(12),
airport_base text(13),
CONSTRAINT pk1 PRIMARY KEY (Aircraft_ID));
Is this possible? I only want the database to be able to perform about 12-15 simple queries.
Would the syntax of adding a foreign key be something like this?
ALTER TABLE Aircraft
ADD CONSTRAINT fk1 FOREIGN KEY(Model_Number)
REFERENCES Aircraft_Model
Does the same foreign key being referenced from a separate table such as Licence_type need a separate constraint to be added or can it be added from the same one with the same fk1 number?
I was wondering if it was possible to reference a primary key as a
foreign key across 2 or more tables.
If you mean, "Can two or more tables have foreign keys that reference the same column?", then, yes, you can do that. This seems to be what you mean, but it's not what most people mean when they talk about "a foreign key across 2 or more tables".
Declare two different, separate constraints.
ALTER TABLE Aircraft
ADD CONSTRAINT fk1 FOREIGN KEY(Model_Number)
REFERENCES Aircraft_Model (Model_Number);
ALTER TABLE License_Type
ADD CONSTRAINT fk2 FOREIGN KEY(Model_Number)
REFERENCES Aircraft_Model (Model_Number);