Vous êtes sur la page 1sur 2

Tutorial#4 (Jan 29-Feb 3)

Multiple Table creation in SQLite

Each contact has the following information: first name, last name, email, and phone.
Both email and phone must be unique. In addition, each contact belongs to one or many
groups, and each group has zero or multiple contacts.

With these requirements, you come up with three tables:

 The contacts table stores contact information.


 The groups table stores group information.
 The contact_groups table stores the relationship between contacts and groups.

The following database diagram illustrates tables: contacts groups , and


contact_groups.

The following statement creates the contacts table.


CREATE TABLE contacts (
contact_id integer PRI
first_name text NOT N
last_name text NOT N
email text NOT NULL U

1 CREATE TABLE contacts (


2 contact_id integer PRIMARY KEY,
3 first_name text NOT NULL,
4 last_name text NOT NULL,
5 email text NOT NULL UNIQUE,
6 phone text NOT NULL UNIQUE
7 );
Try It

The contact_id is the primary key of the contacts table.

Because the primary key consists of one column, you can use column constraint to
make the contact_id column as the primary key.
The first_name and last_name columns have TEXT storage class and those columns
are NOT NULL . It means you must provide values when you insert or update rows in the
contacts table.
The email and phone are unique therefore you use the UNIQUE constraint for each
column.
The following statement creates groups table:
CREATE TABLE groups (
group_id integer PRIM
name text NOT NULL
);

Try It

1 CREATE TABLE contact_groups (


2 contact_id integer,
3 group_id integer,
4 PRIMARY KEY (contact_id, group_id),
5 );
6
7
8
9
Try It

The contact_groups table has a primary key that consists of two columns: contact_id,
group_id .
To add the primary key constraint you use PRIMARY KEY table constraint.
PRIMARY KEY (contact_id, grou

1 PRIMARY KEY (contact_id, group_id)

Vous aimerez peut-être aussi