---
title: "What is a foreign key in SQLite and how do you use it?"  
description: "What is a foreign key in SQLite and how do you use it?"  
author: "Utpal Vishwas"  
published: 2023-05-17  
updated: 2023-05-18  
canonical: https://www.mindstick.com/forum/158388/what-is-a-foreign-key-in-sqlite-and-how-do-you-use-it  
category: "sqlite"  
tags: ["sqlite", "database design"]  
reading_time: 2 minutes  

---

# What is a foreign key in SQLite and how do you use it?

How can you [implement database](https://www.mindstick.com/forum/158372/how-can-you-implement-database-security-in-mongodb-and-what-are-some-best-practices) [security](https://www.mindstick.com/articles/43813/new-security-technologies) in [SQLite](https://www.mindstick.com/articles/1554/crud-operation-in-asp-dot-net-using-sqlite-database) and what are some [best practices](https://www.mindstick.com/articles/337564/building-a-microservices-architecture-with-laravel-best-practices)?

## Replies

### Reply by Aryan Kumar

\
In SQLite, a foreign key is a constraint that is used to enforce referential integrity between two tables. A foreign key is a column in one table that references a primary key in another table. For example, a table of employees might have a foreign key to a table of departments. This would ensure that each employee is assigned to a valid department.

To create a foreign key in SQLite, you use the FOREIGN KEY clause in the CREATE TABLE statement. The FOREIGN KEY clause specifies the name of the column that is the foreign key, the name of the table that contains the primary key, and the name of the primary key column. For example, the following statement creates a foreign key in the employees table that references the departments table:

Code snippet

```plaintext
CREATE TABLE employees (
  id INTEGER PRIMARY KEY,
  name TEXT,
  department_id INTEGER,
  FOREIGN KEY (department_id) REFERENCES departments (id)
);
```

Once a foreign key is created, SQLite will not allow you to insert or update a value in the foreign key column that does not exist in the primary key column of the referenced table. This helps to ensure that the data in your [database](https://www.mindstick.com/articles/12226/use-of-database-in-sencha-extjs-and-insert-record-from-user-form-using-ajax) is consistent.

Foreign keys are a powerful tool that can be used to enforce referential integrity in your SQLite database. By using foreign keys, you can help to ensure that your data is accurate and consistent.


---

Original Source: https://www.mindstick.com/forum/158388/what-is-a-foreign-key-in-sqlite-and-how-do-you-use-it

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
