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?
A FOREIGN KEY constraint cannot reference a table in a different database.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With