Constraints are rules that enforce data integrity in a table. Let's add NOT NULL
and UNIQUE
constraints to a new table called users
.
-
Create a table named users
with constraints. Run this command at the sqlite>
prompt:
CREATE TABLE users (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL,
age INTEGER
);
This command creates a table named users
with the following constraints:
username
cannot be NULL
and must be UNIQUE
.
email
cannot be NULL
.
Let's break down the command:
CREATE TABLE users
: This tells SQLite to create a new table named users
.
id INTEGER PRIMARY KEY
: This defines a column named id
with the data type INTEGER
. The PRIMARY KEY
constraint ensures that each value in this column is unique and serves as the primary identifier for each row.
username TEXT NOT NULL UNIQUE
: This defines a column named username
with the data type TEXT
. The NOT NULL
constraint ensures that this column cannot be empty, and the UNIQUE
constraint ensures that all values in this column are distinct.
email TEXT NOT NULL
: This defines a column named email
with the data type TEXT
. The NOT NULL
constraint ensures that this column cannot be empty.
age INTEGER
: This defines a column named age
with the data type INTEGER
.
-
Now, let's try to insert some data that violates these constraints to see how they work. First, attempt to insert a user without a username:
INSERT INTO users (email, age) VALUES ('[email protected]', 25);
You'll see an error because the username
column is defined as NOT NULL
.
Expected Output:
Error: NOT NULL constraint failed: users.username
This error shows that SQLite enforces the NOT NULL
constraint on username
, preventing the insertion.
-
Next, attempt to insert a user with a duplicate username. First, insert a valid user:
INSERT INTO users (username, email, age) VALUES ('johndoe', '[email protected]', 30);
Then, try to insert another user with the same username:
INSERT INTO users (username, email, age) VALUES ('johndoe', '[email protected]', 25);
You'll see an error because the username
column is defined as UNIQUE
.
Expected Output:
Error: UNIQUE constraint failed: users.username
This error demonstrates that SQLite enforces the UNIQUE
constraint on username
, preventing duplicate values.