Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign key reference to table in another schema

I tried to create a foreign key on one of my tables, referencing a column of a table in a different schema.

Something like that:

ALTER TABLE my_schema.my_table ADD (   CONSTRAINT my_fk     FOREIGN KEY (my_id)     REFERENCES other_schema.other_table(other_id) ) 

Since I had the necessary grants, this worked fine.

Now I wonder if there are reasons for not referencing tables in a different schema, or anything to be careful about?

like image 701
Peter Lang Avatar asked Jan 19 '10 16:01

Peter Lang


People also ask

Can a foreign key reference a table in another database?

A FOREIGN KEY constraint cannot reference a table in a different database.

Can we relate tables from different schemas?

yes you can go for it. Need to write the schema name before the table. select Grant premission on it. Source qualifier can join tables from same db with different schemas.

Does foreign key have to reference primary key in another table?

In a foreign key reference, a link is created between two tables when the column or columns that hold the primary key value for one table are referenced by the column or columns in another table. This column becomes a foreign key in the second table.

How do you reference a foreign key to multiple tables?

Learn Python + JavaScript + Microsoft SQL for Data scienceA foreign key is a key used to link two tables together. This is sometimes also called as a referencing key. A Foreign Key is a column or a combination of columns whose values match a Primary Key in a different table.


2 Answers

No problem doing this. Schemas really have no impact when establishing foreign key relationships between tables. Just make sure the appropriate people have the permissions necessary for the schemas you intend to use.

like image 187
Randy Minder Avatar answered Sep 20 '22 11:09

Randy Minder


If you're in an organization where different people have authority over different schemas, I think it's good practice to give the other schema the ability to disable, or even drop and recreate, your constraint.

For example, they could need to drop or truncate their table and then reload it to handle some (very weird) support issue. Unless you want to get called in the middle of the night, I recommend giving them the ability to temporarily remove your constraint. (I also recommend setting your own alerts so that you'll know if any of your external constraints get disabled or dropped). When you're crossing organizational/schema lines, you want to play well with others. The index that Vincent mentioned is another part of that.

like image 22
Jim Hudson Avatar answered Sep 20 '22 11:09

Jim Hudson