Relationships Between Tables
Establishing Relationships Between Tables in SQL
Once you’ve created tables, the next step is connecting them to create a meaningful database structure. Relationships between tables allow you to link data, enabling complex queries and efficient data management. In this article, we’ll discuss relationships between tables with examples and syntax for SQL Server, MySQL, and Oracle PL/SQL.
What Are Table Relationships?
A relationship is a connection between two tables based on a common column. For example, a Customers table might relate to an Orders table through a column like customer_id
.
Types of Relationships
- One-to-One: Each row in one table corresponds to exactly one row in another.
- One-to-Many: One row in one table corresponds to multiple rows in another.
- Many-to-Many: Rows in one table can correspond to multiple rows in another, often handled using a join table.
Defining Relationships Using Foreign Keys
A foreign key is a column in one table that references a primary key in another table. This establishes the link between the tables.
Querying Data Across Tables
Once relationships are defined, you can write queries to fetch data from multiple tables using joins.
Fetch the names of customers along with their order dates:
One-to-Many Relationship Example
In our example, one customer can have many orders. The customer_id
column in the Orders table references the primary key in the Customers table.
Insert Sample Data
Query Result
CustomerName | OrderDate |
---|---|
Raja | 2025-01-01 |
Raja | 2025-01-02 |
Understanding Referential Integrity
Foreign keys help maintain referential integrity, ensuring that:
- You can’t insert a
customer_id
in orders that doesn’t exist in customers. - You can’t delete a row in customers if related rows exist in orders unless cascading actions are defined.
Summary
Defining relationships between tables is a cornerstone of database design. By using foreign keys, you create a structure that enforces data integrity and enables powerful queries. In the next article, we’ll dive into constraints, exploring how to enforce rules and validate data within your tables.