Sling Academy
Home/SQLite/Using FOREIGN KEYs in SQLite to Model Relationships

Using FOREIGN KEYs in SQLite to Model Relationships

Last updated: December 07, 2024

In SQLite, the use of FOREIGN KEYs is essential for modeling relationships between tables, providing the capability to enforce referential integrity within the database. This functionality ensures that relationships between tables remain consistent and errors such as orphaned records are minimized.

Understanding Foreign Keys

A foreign key is a field (or collection of fields) in one table, that uniquely identifies a row of another table. The table containing the foreign key is called the child table, and the table with the primary key is called the parent table. By establishing a foreign key relationship, you can enforce that the child table only includes values that exist in the parent table.

Enabling Foreign Key Support in SQLite

SQLite does not enable foreign key constraints by default. Before executing any SQL statements that involve foreign keys, it's necessary to enable this feature. Here’s how you can enable it:

PRAGMA foreign_keys = ON;

Once enabled, SQLite will enforce all foreign key constraints until the feature is turned off.

Creating Tables with Foreign Keys

Let's look into how you can create tables with foreign key constraints. Consider the following SQL command for creating two tables, users and orders.


CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL
);

CREATE TABLE orders (
    id INTEGER PRIMARY KEY,
    user_id INTEGER,
    order_date TEXT,
    FOREIGN KEY(user_id) REFERENCES users(id)
);

In the example above:

  • The users table has a primary key id.
  • The orders table includes a column user_id which acts as a foreign key referencing the id column of the users table.

Benefits of Using Foreign Keys

Foreign key constraints in SQLite offer several benefits:

  • Data Integrity: They ensure that orphaned rows do not exist in a child table, thus preserving data integrity.
  • Simplification of Data Relationships: They offer a clear and explicit definition of how data maps across different entities.
  • Automatic Cascading: Operations can be cascaded to child tables automatically using ON DELETE and ON UPDATE rules.

Using ON DELETE and ON UPDATE

SQLite allows the specification of actions to be taken in the case of changes to the parent table. You can specify these actions by extending your foreign key constraint:


CREATE TABLE orders (
    id INTEGER PRIMARY KEY,
    user_id INTEGER,
    order_date TEXT,
    FOREIGN KEY(user_id) REFERENCES users(id)
    ON DELETE CASCADE
    ON UPDATE NO ACTION
);

Here we added:

  • ON DELETE CASCADE: Delete the child records from the orders table when the parent users record is deleted.
  • ON UPDATE NO ACTION: Prevent updates on rows, when a foreign key in a child table would be affected by a change in the parent table.

Checking if Foreign Key Constraints Are On

To programmatically check if foreign key constraints are enabled, execute the following:

PRAGMA foreign_keys;

If the response is 1, they're enabled. If 0, they are not.

Conclusion

By using FOREIGN KEY constraints in SQLite, you create robust relationships among tables that maintain referential integrity and ensure consistent data across your application. Remember to enable foreign key support and carefully specify any cascading rules that fit the expected behavior of your application's data model.

Next Article: SQLite UNIQUE Constraint: Preventing Duplicate Data

Previous Article: Designing a Database with SQLite PRIMARY KEY Constraints

Series: SQLite Data Types and Constraints

SQLite

You May Also Like

  • How to use regular expressions (regex) in SQLite
  • SQLite UPSERT tutorial (insert if not exist, update if exist)
  • What is the max size allowed for an SQLite database?
  • SQLite Error: Invalid Value for PRAGMA Configuration
  • SQLite Error: Failed to Load Extension Module
  • SQLite Error: Data Type Mismatch in INSERT Statement
  • SQLite Warning: Query Execution Took Longer Than Expected
  • SQLite Error: Cannot Execute VACUUM on Corrupted Database
  • SQLite Error: Missing Required Index for Query Execution
  • SQLite Error: FTS5 Extension Malfunction Detected
  • SQLite Error: R-Tree Node Size Exceeds Limit
  • SQLite Error: Session Extension: Invalid Changeset Detected
  • SQLite Error: Invalid Use of EXPLAIN Statement
  • SQLite Warning: Database Connection Not Closed Properly
  • SQLite Error: Cannot Attach a Database in Encrypted Mode
  • SQLite Error: Insufficient Privileges for Operation
  • SQLite Error: Cannot Bind Value to Parameter
  • SQLite Error: Maximum String or Blob Size Exceeded
  • SQLite Error: Circular Reference in Foreign Key Constraints