Create a Relationship in SQL

In SQL, you create a relationship by creating a foreign key constraint.

More specifically, you have a parent table and a child table. The parent contains the primary key, and the child table contains a foreign key that references the primary key of the parent table.

When you use SQL to create a relationship, you can create the relationship at the time you create the table, or you can create it later (by altering the table). This article covers both scenarios.

Continue reading

How to Add a Foreign Key Constraint to an Existing Table in SQL Server (T-SQL)

In database terms, a foreign key is a column that is linked to another table‘s primary key field in a relationship between two tables.

A foreign key is a type of constraint, and so if you want to create a foreign key in SQL Server, you’ll need to create a foreign key constraint.

This article demonstrates how to create a foreign key constraint in SQL Server, using Transact-SQL.

Continue reading

How to Create a Relationship in MySQL Workbench

To create a relationship in MySQL Workbench:

  1. Create a database model (either create a new model or reverse engineer an existing database)
  2. Viewing the database model, double click on the first table of the relationship
  3. The bottom pane will open with the table details. Click on the Foreign Keys tab
  4. In the left pane, select the foreign key field and referenced table
  5. In the middle pane, select the foreign column and referenced (primary key) column
  6. In the right pane, set any Update/Delete actions you’d like to occur when a primary key record is updated or deleted

The relationship is now established. Repeat steps 4 to 6 for any other foreign key columns in that table.

Continue reading

How to Create a Relationship in Access

To create a relationship in Access 2013 or 2016:

  1. While viewing a table in Design view, and ensuring that the DESIGN tab is selected, click Relationships from the Ribbon
  2. A Show Table dialog will appear with a list of tables and queries. Select the tables (and/or queries) that you wish to create a relationship between, and close the dialog
  3. The Relationships tab will appear with the selected tables. Click and drag a field on top of a field in another table to initiate a relationship.
  4. The Edit Relationships dialog will pop up containing both fields. Make any adjustments and click OK

This will create the relationship. You will see the tables in the Relationship tab with lines depicting the relationship between the tables.

Continue reading