Create a SQLite Database and Table with a UNIQUE Constraint
In this step, you will create a SQLite database and a table with a UNIQUE
constraint. This constraint will help you understand how to handle errors when inserting duplicate data.
First, open your terminal in the LabEx VM. Your default path is /home/labex/project
.
Now, let's create a SQLite database named my_database.db
. Run the following command to create the database file and open the SQLite command-line tool:
sqlite3 my_database.db
You will see a prompt indicating that you are now inside the SQLite shell:
SQLite version 3.x.x
Enter ".help" for usage hints.
sqlite>
Next, create a table named users
to store user information. This table will have three columns: id
, username
, and email
. The username
column will have a UNIQUE
constraint, meaning that each username must be unique within the table. Enter the following SQL command at the sqlite>
prompt and press Enter:
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT NOT NULL
);
This command sets up the users
table where:
id
is an integer that automatically increases for each new entry. The PRIMARY KEY
constraint ensures that each id
is unique, and AUTOINCREMENT
makes it increase automatically.
username
is a text field that cannot be left empty (NOT NULL
) and must be unique (UNIQUE
).
email
is also a text field that cannot be left empty (NOT NULL
).
You won't see any output if the command runs successfully.