Sling Academy
Home/SQLite/A Complete Overview of SQLite Table Constraints

A Complete Overview of SQLite Table Constraints

Last updated: December 07, 2024

SQLite is a lightweight, high-performance, and versatile database engine used widely in embedded systems, mobile applications, and desktop software. It provides robust support for database constraints, which help maintain data integrity and provide a set of rules applied to table columns. This article offers a complete overview of SQLite table constraints, explaining each type with examples.

What are Table Constraints?

Table constraints in SQLite enforce rules at the column level whenever a new row is added, or an existing one is modified. They are essential for ensuring that the data entered into a database remains consistent and valid. SQLite supports several types of constraints, including NOT NULL, UNIQUE, PRIMARY KEY, CHECK, and FOREIGN KEY.

NOT NULL Constraint

The NOT NULL constraint ensures that a column cannot have a NULL value. If we attempt to insert or update a NULL into a NOT NULL constrained column, SQLite will emit an error.

CREATE TABLE Employees (
    ID INTEGER PRIMARY KEY,
    Name TEXT NOT NULL,
    Position TEXT
);

In the above example, the Name column can't contain NULL values, making it mandatory for each employee entry.

UNIQUE Constraint

The UNIQUE constraint guarantees the uniqueness of the data across a specified column. This constraint ensures that all values in the column or a group of columns are distinct.

CREATE TABLE Products (
    ProductID INTEGER,
    ProductName TEXT,
    SupplierID INTEGER,
    UNIQUE (ProductName, SupplierID)
);

Here, the combination of ProductName and SupplierID must be unique.

PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a table. It's a special case of the UNIQUE constraint and automatically includes a NOT NULL constraint. A table can have only one primary key, which can consist of one or multiple columns.

CREATE TABLE Orders (
    OrderID INTEGER PRIMARY KEY,
    CustomerID INTEGER,
    OrderDate TEXT
);

The OrderID column serves as the primary key, uniquely distinguishing each order.

CHECK Constraint

The CHECK constraint ensures that all values in a column satisfy specific conditions. This constraint provides a powerful way to enforce custom rules.

CREATE TABLE Departures (
    FlightID INTEGER PRIMARY KEY,
    DepartureTime TEXT NOT NULL,
    CHECK (DepartureTime > '2023-01-01')
);

Here, the CHECK constraint enforces that DepartureTime must be beyond a specified date.

FOREIGN KEY Constraint

The FOREIGN KEY constraint maintains referential integrity by ensuring that a value in one table matches a value in another table. This helps create linkage between tables, establishing relationships similar to parent-child connections.

CREATE TABLE Customers (
    CustomerID INTEGER PRIMARY KEY,
    CustomerName TEXT
);

CREATE TABLE Orders (
    OrderID INTEGER PRIMARY KEY,
    CustomerID INTEGER,
    FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

In this example, the CustomerID in the Orders table is a foreign key, referencing its counterpart in the Customers table.

Conclusion

Understanding and using SQLite table constraints effectively can greatly enhance the integrity and reliability of your database applications. By choosing and combining these constraints, you can ensure that your database not only meets business rules but also handles erroneous data efficiently.

Using sqlite3 in Python or integrating SQLite in other development frameworks gives you the flexibility to build robust applications with these constraints. Always validate how constraints affect performance, especially with unique and foreign keys, over extensive datasets.

Next Article: PRIMARY KEY and AUTOINCREMENT: How They Work Together in SQLite

Previous Article: The Impact of Type Affinities on SQLite Queries

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