CREATE Related Tables

Relational databases allow us to connect tables using relationships, making data management more efficient. In this lesson, you’ll learn how to create tables with relationships, including one-to-many and many-to-many relationships.

One-to-Many Relationships

A one-to-many relationship exists when one record in Table A is related to multiple records in Table B. For example, consider a database tracking puppies and their owners:

Example Schema

To establish this relationship, the puppies table includes:

owners table:

CREATE TABLE owners (
  id INTEGER PRIMARY KEY,
  name VARCHAR(50) NOT NULL
);
    

puppies table:

CREATE TABLE puppies (
  id INTEGER PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  age_yrs NUMERIC(3,1),
  breed VARCHAR(100),
  weight_lbs INTEGER,
  microchipped BOOLEAN DEFAULT 0,
  owner_id INTEGER,
  FOREIGN KEY (owner_id) REFERENCES owners(id)
);
    

Enable Foreign Key Constraints

In SQLite3, you must enable foreign key constraints to enforce relationships:

PRAGMA foreign_keys = ON;

This ensures that an error is thrown if a foreign key constraint is violated. For example:

View Schema

After creating the tables, use the following command in SQLite3 to view the schema:

.schema

Many-to-Many Relationships

A many-to-many relationship exists when multiple records in Table A are associated with multiple records in Table B. For example:

Example Schema

To establish this relationship, use a join table called people_elephants. The join table includes:

people table:

CREATE TABLE people (
  id INTEGER PRIMARY KEY,
  name VARCHAR(50) NOT NULL
);
    

elephants table:

CREATE TABLE elephants (
  id INTEGER PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  gender VARCHAR(6) NOT NULL,
  age INTEGER
);
    

people_elephants join table:

CREATE TABLE people_elephants (
  person_id INTEGER NOT NULL,
  elephant_id INTEGER NOT NULL,
  FOREIGN KEY (person_id) REFERENCES people(id),
  FOREIGN KEY (elephant_id) REFERENCES elephants(id)
);
    

Note: The join table does not require a primary key because it is primarily used for queries involving person_id or elephant_id.

Enable Foreign Key Constraints

As with the one-to-many relationship, you must enable foreign key constraints:

PRAGMA foreign_keys = ON;

View Schema

Use the .schema command to verify the structure of the tables and their relationships.

What You Learned

In this lesson, you learned how to create tables with relationships in a relational database:

Real-World Applications

Relational databases with foreign key constraints are widely used in systems such as:

By understanding how to create relationships between tables, you can design efficient and normalized databases for any application.