![]() The following query creates a table with the name CUSTOMERS −įollowing is the output of the above SQL statement − Let’s create two tables with the names CUSTOMERS and ORDERS. We can have more than one Foreign Key per table.įollowing is the syntax to add Foreign key constraints on a column of a table −ĬREATE TABLE TABLE_2(COLUMN_NAME FOREIGN KEY REFERENCES TABLE_1(COLUMN_NAME)) Primary keyĪ table can contain only one Primary Key. ![]() The table that has the primary key is known as the parent table and the key with the foreign key is known as the child table.Įven though both the primary key and foreign key refer to the same column, there are many differences to be observed in the way they work. ![]() It helps to normalize (or organize the data in a database) the data in multiple tables. Here are some key points of the Foreign Key −Ī Foreign Key is used to reduce the redundancy (or duplicates) in the table. Following is the diagram to identify the Foreign key and Primary key in the above tables − Then, the column Roll_no of the STU_ADD table is the Primary key, whereas the column Roll_no of the STD_MARKS is a Foreign key. STU_MARKS contains the columns Roll_no, Subject, Marks and, Date. STU_ADD contains the columns/attributes Roll_no, Name, Age, Address, and Pin. Let’s consider an example scenario for a better understanding, suppose we have two tables namely, STD_ADD & STD_MARKS such that − In addition to avoiding redundant records, SQL keys are used to establish a relationship between multiple tables. ![]() A KEY is an attribute that allows us to uniquely identify a row in a table. i.e, a Foreign key prevents operations, like “dropping the table”, that would eliminate the connection between two tables. In addition to linking to tables, The Foreign key constraint ensures referential integrity by preventing changes to data in the primary key table from invalidating the link to data in the foreign key table. Using the Foreign key, we can link two tables together.Ī Foreign Key is also known as a Referencing key of a table because it can reference any field defined as unique. In SQL, a Foreign Key is a column (or combination of columns) in a table whose values match the values of a Primary Key column in another table. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |