generated from microverseinc/curriculum-template-databases
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema.sql
56 lines (48 loc) · 1.47 KB
/
schema.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* Database schema to keep the structure of entire database. */
CREATE TABLE animals(
id SERIAL NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
date_of_birth DATE NOT NULL,
escape_attempts integer NOT NULL,
neutered BOOLEAN NOT NULL,
weight_kg FLOAT NOT NULL
);
ALTER TABLE animals
ADD COLUMN species VARCHAR(255);
-- create new tables
CREATE TABLE owners(
id SERIAL NOT NULL PRIMARY KEY,
full_name VARCHAR(255) NOT NULL,
age INT NOT NULL
)
-- create species table
CREATE TABLE species(
id SERIAL NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL
)
-- delete species column in animals table
ALTER TABLE animals DROP COLUMN species;
-- one-to-many relationship: add new columns to animals table
ALTER TABLE animals
ADD COLUMN species_id INT CONSTRAINT animals_fk
REFERENCES species(id) ON DELETE CASCADE;
ALTER TABLE animals
ADD COLUMN owner_id INT CONSTRAINT fk_animals
REFERENCES owners(id) ON DELETE CASCADE;
-- create vets table
CREATE TABLE vets(
id SERIAL NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INTEGER NOT NULL,
date_of_graduation DATE
);
-- many-many relationship: create table to connects two table together
CREATE TABLE specializations(
species_id INT REFERENCES species(id) ON DELETE CASCADE,
vets_id INT REFERENCES vets(id) ON DELETE CASCADE
);
CREATE TABLE visits(
animals_id INT REFERENCES animals(id) ON DELETE CASCADE,
vets_id INT REFERENCES vets(id) ON DELETE CASCADE,
visit_date DATE
);