A constraint is a rule we create on a database that enforces some specific behavior. For example, setting a NOT NULL constraint on a column ensures that the column will not accept NULL values.
If we try to insert a NULL value into a column with the NOT NULL constraint, the insert will fail with an error message. Constraints are extremely useful when we need to ensure that certain kinds of data exist within our database.
The NOT NULL constraint can be added directly to the CREATE TABLE statement.
CREATE TABLE employees(
id INTEGER PRIMARY KEY,
-- The PRIMARY KEY constraint uniquely identifies each row in the table
name TEXT UNIQUE,
-- The UNIQUE constraint ensures that no two rows can have the same value in the 'name' column
title TEXT NOT NULL
-- The NOT NULL constraint ensures that the 'title' column cannot have NULL values
);
In other dialects of SQL you can ADD CONSTRAINT within an ALTER TABLE statement. SQLite does not support this feature so when we create our tables we need to make sure we specify all the constraints we want! Here's a list of SQL Features SQLite does not implement in case you're curious.
Thankfully all the tables we have created for CashPal up to this point have been for testing purposes! Now that we have a better understanding of constraints, let's rebuild our database with the proper constraints and tables!
Create the users table with the following fields and constraints:
id - INTEGER, PRIMARY KEYname - TEXT, NOT NULLage - INTEGER, NOT NULLcountry_code - TEXT, NOT NULLusername - TEXT, UNIQUE, NOT NULLpassword - TEXT, NOT NULLis_admin - BOOLEAN