#### Schemas and Relationships ![](https://i.redd.it/vk7q0diwh4m21.jpg) --- #### What is a database relationship? :sparkles: A relationship is established between two database tables when one table uses a foreign key that references the primary key of another table. :key: ---> :key: --- #### Why is it important :question: Establishing consistent relationships between database tables helps ensure data integrity, contributing to database normalization. --- #### What kinds of database relationships are there? - one to one. - one to many. - many to many. --- #### How does a schema describe a relational database? - A database schema is a design that represents the storage of your data in a database. - It describes both the organization of data and the relationships between tables in a given database. --- - A database schema is a blueprint of how our data will look. It doesn’t hold data itself, but instead describes the shape of the data and how it might relate to other tables or models. - Logical Vs Physical. --- ![](https://i.imgur.com/BxeNp8L.png) --- #### Keys :key: Databases have a few different types of keys --- #### Candidate key - Uniquely identifies a database entry without referring to any other data - Does not describe any relationships to other tables - Each table may have one or more candidate keys --- For example, a company might use Social Security numbers as a candidate key to uniquely identify employees ![](https://i.imgur.com/rI9Q044.png) --- Some people share the same first names, last names, and position, but no two people use the same Social Security number --- Among the candidate keys, one is selected as the table primary key. A table can contain several candidate keys, but only one primary key. ![](https://media.giphy.com/media/Z6E5EzRex9S4hAlsUt/giphy.gif) --- #### Primary key Usually the first column in a table and can be automatically generated by the database ![](https://i.imgur.com/7gIvBUI.png) --- #### Foreign key A foreign key is another candidate key (not the primary key) used to link an entry to data in another table --- Here, the Courses table primary key is Course_ID. The foreign key is Teacher_ID ![](https://i.imgur.com/DwE8NW1.png) --- The foreign key establishes a relationship between the Teachers and Courses tables :handshake: ![](https://i.imgur.com/4mqkNKx.png) --- ...and they live happily ever after in a well organised database! ![](https://media.giphy.com/media/UEGwYCVTBFa9tJEf66/giphy.gif)
{"metaMigratedAt":"2023-06-16T18:07:21.650Z","metaMigratedFrom":"Content","title":"Untitled","breaks":true,"contributors":"[{\"id\":\"3934dd6c-8588-4d47-a23b-ba8c96da8ea7\",\"add\":3003,\"del\":621},{\"id\":\"5fc58879-82a7-42a5-adb7-d717c9b3063b\",\"add\":1152,\"del\":1010}]"}
    389 views