0% found this document useful (0 votes)
74 views70 pages

CS2102: Database Systems - Adi Yoga Sidi Prabawa 1 / 73

The document discusses an upcoming database systems course. It provides information about group formation deadlines, material preparation, and an upcoming question and answer session on Friday, January 27th at 6pm that will be recorded.

Uploaded by

Sheryl Kong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views70 pages

CS2102: Database Systems - Adi Yoga Sidi Prabawa 1 / 73

The document discusses an upcoming database systems course. It provides information about group formation deadlines, material preparation, and an upcoming question and answer session on Friday, January 27th at 6pm that will be recorded.

Uploaded by

Sheryl Kong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 1 / 73

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 2 / 73


Deadline for group formation is this Saturday, 28 January 2023 by 12:00 Noon
Groups with fewer than 4 members may be merged or allocated a random member

Starts this Wednesday


Please prepare the material before hand
Solutions will be released on Friday evening (18:00)

Session I: Friday, 27 January 2023 at 18:00


Q&A Session
Will be recorded

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 3 / 73


CS2102: Database Systems -- Adi Yoga Sidi Prabawa 4 / 73
CS2102: Database Systems -- Adi Yoga Sidi Prabawa 5 / 73
Operation Operator Visualization Description

Union R∪S A relation containing all tuples that are in R or S

Intersection R ∩ S A relation containing all tuples that are in R and S

A relation containing all tuples that are in R but not in


Difference R−S
S

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 6 / 73


L Operator R Visualization

Keep
dangling

Keep
dangling

Keep Keep
dangling dangling

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 7 / 73


CS2102: Database Systems -- Adi Yoga Sidi Prabawa 8 / 73
History and Usages Unique and Keys
General

Basic DDL
Basic DML Alter and Drop

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 9 / 73


CS2102: Database Systems -- Adi Yoga Sidi Prabawa 10 / 73
De-facto standard language to "talk" to RDBMS
Developed by Donald D. Chamberlin and Raymond F. Boyce (IBM Research, 1974)
Originally called SEQUEL (Structured English Query Language)

SQL is a domain-speci c language (i.e., not a general-purpose like Python)


SQL is a declarative language
Focus on what to compute, instead of how to compute
Somewhat opposite to relational algebra expression (which is imperative)
Based on multi-set/bag (may contain duplicate rows) instead of set

First standard is SQL-86; the most recent standard is SQL-2019 (new standard every ~3-5 years)
New standards introduce new language concepts (e.g., support new features of RDBMS)
Many RDBMS add their own " avor" to SQL

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 11 / 73


Included in application written in a host language

Application is a mixture of host language (e.g., C, Java, Python) and SQL statements
Example: Embedded SQL, Dynamic SQL

Application is entirely written in the host language (e.g., C, Java, Python)


Example: ODBC (Open DataBase Connectivity), JDBC (Java DataBase Connectivity)

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 12 / 73


Directly writing SQL statements to an interface

psql pgAdmin

This will be our preferred mode

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 13 / 73


Data De nition Data Data Data Transaction
Manipulation Query Control Control
CREATE
ALTER INSERT SELECT GRANT BEGIN
DROP UPDATE REVOKE COMMIT
RENAME DELETE ROLLBACK
TRUNCATE MERGE SAVEPOINT

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 14 / 73


CS2102: Database Systems -- Adi Yoga Sidi Prabawa 15 / 73
SQL is case-insensitive
CREATE TABLE <table_name> ( You can use uppercase or
<attr1> <type1> [<column_constraint>], lowercase
<attr2> <type2> [<column_constraint>], Convention:
Keywords should be in
⁝ uppercase
<attrn> <typen> [<column_constraint>], Try to align elements
[<table_constraint>], -- comment
[<table_constraint>], /* comment */

[<table_constraint>] -- no comma
);

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 16 / 73


attr1 attr2 ... attrn
CREATE TABLE <table_name> (
 
<attr1> <type1> [<column_constraint>],
<attr2> <type2> [<column_constraint>],

<attrn> <typen> [<column_constraint>], <table_name>(
[<table_constraint>], -- comment <attr1> : <type1>,
[<table_constraint>], /* comment */ <attr2> : <type2>,
    ⁝

<attrn> : <typen>
[<table_constraint>] -- no comma
); )

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 17 / 73


Create the relation Employees(id: INT, name: TEXT, age: INT, role: TEXT).

Table "Employees"
CREATE TABLE Employees (
id INTEGER, id name age role
name VARCHAR(50),
 
age INTEGER,
role VARCHAR(50)
);

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 18 / 73


Type Description Kinds Types
BOOLEAN Logical Boolean (true/false) XML
Document
JSON
INTEGER (INT) Signed 4-bytes integer
Point
Double precision 8-bytes oating-
FLOAT8 Line
point
Polygon
Spatial
Exact numeric of selectable Circle
NUMERIC[(p,s)] Box
precision
Path
CHAR(n) Fixed-length character string
Money/Currency
VARCHAR(n) Variable-length character string Special
MAC/IP Address
TEXT Variable-length character string
DATE Calendar date (year, month, day)
TIMESTAMP Date and time
CREATE TYPE

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 19 / 73


INSERT INTO <table_name> [(attr_1, attr_2, ..., attr_n)]
VALUES
(<val_1_1>, <val_2_1>, ..., <val_n_1>),
(<val_1_2>, <val_2_2>, ..., <val_n_2>),

(<val_1_m>, <val_2_m>, ..., <val_n_m>);

Either all inserted or none inserted


Attributes can be speci ed out-of-order (optionally)
Missing values are replaced with NULL (if allowed) or default values (if speci ed)

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 20 / 73


Table "Employees"

id name age role

INSERT INTO Employees id name age role

VALUES (101, 'Sarah', 25, 'dev'); 101 'Sarah' 25 'dev'

INSERT INTO Employees (name, id) id name age role

VALUES ('Judy', 102), ('Max', 103); 101 'Sarah' 25 'dev'


102 'Judy' NULL NULL
103 'Max' NULL NULL

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 21 / 73


Table "Employees"
CREATE TABLE Employees (
id INTEGER, id name age role
name VARCHAR(50),
age INTEGER,
role VARCHAR(50) DEFAULT 'sales'
);

INSERT INTO Employees id name age role

VALUES (101, 'Sarah', 25, 'dev'); 101 'Sarah' 25 'dev'


INSERT INTO Employees (name, id) 102 'Judy' NULL 'sales'
VALUES ('Judy', 102), ('Max', 103); 103 'Max' NULL 'sales'

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 22 / 73


Condition is optional
DELETE FROM <table_name> If unspeci ed, equivalent to
[ WHERE <condition> ]; always true
If speci ed, condition can be
arbitrarily complex

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 23 / 73


Table "Employees"

id name age role


101 'Sarah' 25 'dev'
Perform the operation if the condition evaluates to True✱. 102 'Judy' NULL 'sales'
Used in WHERE clause (and relational algebra)
103 'Max' NULL NULL

DELETE FROM Employees; DELETE FROM Employees


-- delete all! WHERE role <> 'dev';

id name age role id name age role


101 'Sarah' 25 'dev'
103 'Max' NULL NULL


Remember, we have three-valued logic!
CS2102: Database Systems -- Adi Yoga Sidi Prabawa 24 / 73
CS2102: Database Systems -- Adi Yoga Sidi Prabawa 25 / 73
Reject the insertion if the condition evaluates to False.
Used in integrity constraints

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 26 / 73


x x IS NULL x IS NOT NULL
not-NULL False True
NULL True False

x y x IS DISTINCT FROM y x IS NOT DISTINCT FROM y


not-NULL not-NULL x <> y x = y
not-NULL NULL True False
NULL not-NULL True False
NULL NULL False True

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 27 / 73


. Not-NULL Constraints
. Unique Constraints
. Primary Key Constraints
. Foreign Key Constraints
. General Constraints

Column Constraint: Named Constraint:


Applies to a single column✱ Name is speci ed by user
Speci ed at column de nition Unnamed Constraint:
Table Constraint: Name is automatically assigned by DBMS
Applies to one or more column
Speci ed after column de nition

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 28 / 73


CREATE TABLE Employees ( CREATE TABLE Employees (
id INT NOT NULL, id INT CONSTRAINT nn_id NOT NULL,
name TEXT NOT NULL, name TEXT CONSTRAINT nn_name NOT NULL,
age INT, age INT,
role TEXT role TEXT
); );

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 29 / 73


id name age role Row
101 'Sarah' 25 'dev' Row 1
NULL 'Judy' 32 'sales' Row 2
102 '' 27 'hr' Row 3
103 'Max' NULL NULL Row 4

CREATE TABLE Employees (


id INT NOT NULL,
Consider the schema on the left and the table
name TEXT NOT NULL,
age INT,
at the top. Which rows violate the NOT NULL
role TEXT constraint?
);

Choice Comment
A Row 1
B Row 2
C Row 3
D Row 4

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 30 / 73


CREATE TABLE Employees ( CREATE TABLE Employees (
id INT UNIQUE, id INT CONSTRAINT emp_id UNIQUE,
name TEXT, name TEXT ,
age INT, age INT,
role TEXT role TEXT
); );

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 31 / 73


CREATE TABLE Teams ( CREATE TABLE Teams (
eid INT, eid INT,
pname TEXT, pname TEXT,
hours INT, hours INT,
UNIQUE (eid, pname) CONSTRAINT team_id UNIQUE (eid, pname)
); );

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 32 / 73


eid pname hours Row
101 NULL 25 Row 1
101 NULL 25 Row 2
102 'Judy' 32 Row 3
102 'Judy' 32 Row 4

CREATE TABLE Teams (


eid INT,
Consider the schema on the left and the table
pname TEXT,
hours INT,
at the top. Which rows are not UNIQUE?
UNIQUE (eid, pname)
);

Choice Comment
A Row 1
B Row 2
C Row 3
D Row 4

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 33 / 73


A primary key is a selected candidate keys.
Uniquely identi es a tuple in a relation
Cannot be NULL

In other words, UNIQUE and NOT NULL

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 34 / 73


CREATE TABLE Employees ( CREATE TABLE Employees (
id INT PRIMARY KEY, id INT CONSTRAINT emp_pk PRIMARY KEY,
name TEXT, name TEXT,
age INT, age INT,
role TEXT role TEXT
); );

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 35 / 73


CREATE TABLE Teams ( CREATE TABLE Teams (
eid INT, eid INT,
pname TEXT, pname TEXT,
hours INT, hours INT,
PRIMARY KEY (eid, pname) CONSTRAINT team_pk PRIMARY KEY (eid, pname)
); );

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 36 / 73


CREATE TABLE Teams ( CREATE TABLE Teams (
eid INT NOT NULL, eid INT CONSTRAINT nn_eid NOT NULL,
pname TEXT NOT NULL, pname TEXT CONSTRAINT nn_pname NOT NULL,
hours INT, hours INT,
UNIQUE (eid, pname) CONSTRAINT team_pk PRIMARY KEY (eid, pname)
); );

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 37 / 73


A foreign key is a subset of attributes of relation R1 that refers to the primary key✱ of relation R2.

Requirement:
Each foreign key in R1 must satisfy one of the following:
Appear as primary key in R2
Be a NULL value (or a tuple containing at least one NULL value)

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 38 / 73


CREATE TABLE Teams (
eid INT,
pname TEXT REFERENCES Projects,
hours INT,
PRIMARY KEY (eid, pname),
FOREIGN KEY (eid) REFERENCES Employees (id)
);

CREATE TABLE Employees ( CREATE TABLE Projects (


id INT PRIMARY KEY, name TEXT,
name TEXT, start_year INT,
age INT, end_year INT,
role TEXT PRIMARY KEY (name)
); );

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 39 / 73


CS2102: Database Systems -- Adi Yoga Sidi Prabawa 40 / 73
Table "Movies"

id title genre opened


What if the rst tuple on "Movies" is deleted? 101 Aliens Action 1986
What if Sigourney Weaver id is updated from 20 to 102 Logan Drama 2017

30? 103 Heat Crime 1995


104 Terminator Action 1984

Table "Cast"

Extend the syntax to specify the behavior movie_id actor_id role


101 20 Ellen Ripley
when data in referenced table is deleted or 101 23 Private Hudson
updated using optional speci cation: 101 54 Corporal Hicks
102 21 Logan

ON DELETE <action> 104 23 Punk Leader

ON UPDATE <action> Table "Actors"

id name dob
20 Sigourney Weaver 08-10-1949
21 Hugh Jackman 12-10-1968
22 Tom Hanks 09-07-1956
23 Bill Paxton 17-05-1955

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 41 / 73


Keyword Action
NO ACTION Reject delete/update if it violates constraint (default value)
Similar to "NO ACTION" except that check of constraint cannot be deferred
RESTRICT
(deferrable constraints are discussed in a bit)

CASCADE Propagates delete/update to the referencing tuples


SET Updates the foreign key of the referencing tuples to some default value (Important:
DEFAULT default value must be a primary key in the referencing table)

Updates the foreign key of the referencing tuples to NULL value (Important:
SET NULL
corresponding column must be allowed to contain NULL values)

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 42 / 73


CREATE TABLE Teams (
eid INT,
pname TEXT DEFAULT 'FastCash',
hours INT,
PRIMARY KEY (eid, pname),
FOREIGN KEY (eid) REFERENCES Employees (id) ON DELETE NO ACTION ON UPDATE CASCADE,
FOREIGN KEY (pname) REFERENCES Projects (name) ON DELETE SET DEFAULT ON UPDATE CASCADE
);

Updates on Employees.id and Projects.name are propagated


Deleting a project will set Teams.pname to default value (i.e., FastCash)
Deleting an employee will raise an error if that employee is still assigned to a team

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 43 / 73


CREATE TABLE Teams (
eid INT,
pname TEXT DEFAULT 'FastCash',
hours INT,
PRIMARY KEY (eid, pname),
FOREIGN KEY (eid) REFERENCES Employees (id) ON DELETE NO ACTION ON UPDATE CASCADE,
FOREIGN KEY (pname) REFERENCES Projects (name) ON DELETE SET DEFAULT ON UPDATE CASCADE
);

name start_year end_year name start_year end_year


BigAI 2020 2025
UPDATE Projects SmartAI 2020 2025
FastCash 2018 2025 SET name = 'SmartAI' FastCash 2018 2025
⁝ ⁝ ⁝ WHERE name = 'BigAI'; ⁝ ⁝ ⁝

eid pname hours eid pname hours


101 BigAi 10 101 SmartAI 10
102 GlobalDB 20 102 GlobalDB 20
⁝ ⁝ ⁝ ⁝ ⁝ ⁝

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 44 / 73


CREATE TABLE Teams (
eid INT,
pname TEXT DEFAULT 'FastCash',
hours INT,
PRIMARY KEY (eid, pname),
FOREIGN KEY (eid) REFERENCES Employees (id) ON DELETE NO ACTION ON UPDATE CASCADE,
FOREIGN KEY (pname) REFERENCES Projects (name) ON DELETE SET DEFAULT ON UPDATE CASCADE
);

name start_year end_year name start_year end_year


BigAI 2020 2025
DELETE FROM Projects FastCash 2018 2025
FastCash 2018 2025 WHERE name = 'BigAI'; ⁝ ⁝ ⁝
⁝ ⁝ ⁝

eid pname hours eid pname hours


101 BigAi 10 101 FastCash 10
102 GlobalDB 20 102 GlobalDB 20
⁝ ⁝ ⁝ ⁝ ⁝ ⁝

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 45 / 73


Speci ed constraints might not behave as expected
SET NULL issue with prime attributes
SET DEFAULT issue with default value not in referenced relation
CASCADE may create a chain of propagation
If the referencing relation is also a referenced relation

CASCADE may signi cantly affect overall performance


Careful de gn and speci cation of foreign key constraints is crucial

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 46 / 73


A B C D Row
1 2 3 NULL Row 1
2 1 NULL 1 Row 2
1 1 1 3 Row 3
1 3 NULL NULL Row 4

R(A, B)
S(C, D)
Consider the foreign key constraints (S.C, S.D) ⇝ (R.A, R.B). Which
rows violate the FOREIGN KEY constraint?

Choice Comment
A Row 1
B Row 2
C Row 3
D Row 4

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 47 / 73


Most basic general constraint (i.e., not a structural integrity constraint)
Allows us to specify that column values must satisfy an arbitrary Boolean expression
Scope: one table, one row

CREATE TABLE Projects ( CREATE TABLE Teams (


eid INT, name TEXT PRIMARY KEY,
pname TEXT, start_year INT,
hours INT CHECK (hours > 0), end_year INT,
PRIMARY KEY (eid, pname) CHECK (start_year <= end_year)
); );

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 48 / 73


Create the Table "Teams" where the minimum hours for 'CoreOS' is at least 30 hours but
there are no such restrictions for other projects.

CREATE TABLE Projects (


eid INT,
pname TEXT,
hours INT CHECK (hours > 0),
PRIMARY KEY (eid, pname),
CHECK (
(pname = 'CoreOS' AND hours >= 30)
OR
(pname <> 'CoreOS' AND hours > 0)
)
);


Is this good enough? Can you do better?
CS2102: Database Systems -- Adi Yoga Sidi Prabawa 49 / 73
CREATE ASSERTION statement (since SQL-92)
Used for (almost) arbitrary constraints (multiple table, multiple rows)
Example: "Each project must have at least one team member being 30 or older"

Assertions may have various potential side-effects and/or limitations


Cannot modify the data
No proper error handling
Not linked to a speci c table (e.g., dropping a table does not affect assertion)

Most RDBMS do NOT support assertions


Alternative: Triggers

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 50 / 73


Type Column Table Condition
Not-NULL NOT NULL - IS NOT NULL
Unique UNIQUE UNIQUE(A1,A2,...) x.Ai <> y.Ai

Primary Key PRIMARY KEY PRIMARY KEY(A1,A2,...) UNIQUE & NOT NULL
FOREIGN KEY (A1,A2,...) The tuple exists in R1
Foreign Key REFERENCES R1(B)
REFERENCES R1(B1,B2,...) or the tuple contains NULL value
General CHECK (c) CHECK (c) Condition c does not evaluate to False

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 51 / 73


CS2102: Database Systems -- Adi Yoga Sidi Prabawa 52 / 73
ALTER TABLE <table_name>
[ALTER / ADD / DROP] [COLUMN / CONSTRAINT] <name>
<changes>;

Common Changes:
Adding/dropping columns
Adding/dropping constraints
Changing the speci cation of a single column:
Data type
Default values

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 53 / 73


ALTER TABLE Projects ALTER COLUMN name TYPE VARCHAR(200);

ALTER TABLE Projects ALTER COLUMN start_year SET DEFAULT 2021;

ALTER TABLE Projects ALTER COLUMN name DROP DEFAULT;

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 54 / 73


ALTER TABLE Projects ADD COLUMN budget NUMERIC DEFAULT 0.0;
ALTER TABLE Projects DROP COLUMN budget;

ALTER TABLE Teams ADD CONSTRAINT


eid_fkey FOREIGN KEY (eid) REFERENCES Employees (id);
ALTER TABLE Teams DROP CONSTRAINT eid_fkey;

Name of constraints need to be known (may be retrieved from metadata)


https://www.postgresql.org/docs/14/sql-altertable.html
CS2102: Database Systems -- Adi Yoga Sidi Prabawa 55 / 73
DROP TABLE
[IF EXISTS] -- no error if table does not exist
<table_name>[, <table_name> [, <table_name> [...]]] -- multiple table
[CASCADE]; -- also delete referencing table

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 56 / 73


CS2102: Database Systems -- Adi Yoga Sidi Prabawa 57 / 73
An SQL statement is any SQL code that ends with a semi-colon (i.e., ;)

Constraints are checked immediately at the end of SQL statement


This is true even for transaction containing multiple SQL statement A violation will cause
the statement/transaction to be rolled back

Check only at the end of a transaction


Available for: UNIQUE, PRIMARY KEY, FOREIGN KEY

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 58 / 73


Deferrable constraints may (temporarily) be violated within the scope of a transaction in
the "internal state"

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 59 / 73


An employee must work in a A department must be managed by
department an employee

CREATE TABLE Employee ( CREATE TABLE Department (


eid INT PRIMARY KEY, did INT PRIMARY KEY,
name TEXT, name TEXT,
did INT eid INT
); );

ALTER TABLE Employee ADD CONSTRAINT ALTER TABLE Department ADD CONSTRAINT
did_fk FOREIGN KEY (did) eid_fk FOREIGN KEY (eid)
REFERENCES Department (did); REFERENCES Employee (eid);

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 60 / 73


BEGIN; -- start of transaction

INSERT INTO Employee VALUES (101, 'Sarah', 1001);


INSERT INTO Department VALUES (1001, 'dev', 101);
COMMIT; -- successful end of transaction

Line 3: Foreign Key Constraint Violation ABORT


Line 4: Foreign Key Constraint Established not executed

ALTER TABLE Employee ADD CONSTRAINT ALTER TABLE Department ADD CONSTRAINT
did_fk FOREIGN KEY (did) eid_fk FOREIGN KEY (eid)
REFERENCES Department (did) REFERENCES Employee (eid)
NOT DEFERRABLE; NOT DEFERRABLE;

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 61 / 73


BEGIN; -- start of transaction

INSERT INTO Employee VALUES (101, 'Sarah', 1001);


INSERT INTO Department VALUES (1001, 'dev', 101);
COMMIT; -- successful end of transaction

Line 3: Foreign Key Constraint Violation constraint check deferred


Line 4: Foreign Key Constraint Established SUCCESS

ALTER TABLE Employee ADD CONSTRAINT ALTER TABLE Department ADD CONSTRAINT
did_fk FOREIGN KEY (did) eid_fk FOREIGN KEY (eid)
REFERENCES Department (did) REFERENCES Employee (eid)
DEFERRABLE INITIALLY DEFERRED; DEFERRABLE INITIALLY DEFERRED;

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 62 / 73


BEGIN; -- start of transaction
SET CONSTRAINT did_fk DEFERRED;
INSERT INTO Employee VALUES (101, 'Sarah', 1001);
INSERT INTO Department VALUES (1001, 'dev', 101);
COMMIT; -- successful end of transaction

Line 3: Foreign Key Constraint Violation constraint check deferred


Line 4: Foreign Key Constraint Established SUCCESS

ALTER TABLE Employee ADD CONSTRAINT ALTER TABLE Department ADD CONSTRAINT
did_fk FOREIGN KEY (did) eid_fk FOREIGN KEY (eid)
REFERENCES Department (did) REFERENCES Employee (eid)
DEFERRABLE INITIALLY IMMEDIATE; DEFERRABLE INITIALLY DEFERRED;

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 63 / 73


No need to care about the order of SQL statements within a transaction
(i.e., intermediate state may temporarily violate constraints)
Allows for cyclic foreign key constraints
Performance boost when constraint checks are bottleneck
(e.g., batch insert of large number of tuples)

Troubleshooting can be more dif cult


Data de nition no longer unambiguous
May incur performance penalty when performing queries
Certain checks may need to be done at run-time especially during the time when the
constraint check is deferred

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 64 / 73


CS2102: Database Systems -- Adi Yoga Sidi Prabawa 65 / 73
The standard language for RDBMS
Different language groups: DDL, DML, DQL, DCL, TCL

DDL: CREATE TABLE, ALTER TABLE, DROP TABLE


DML: INSERT, UPDATE, DELETE

Speci cation of integrity constraints


NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK
Speci cation actions in case of foreign key constraint violations (ON UPDATE/ON DELETE)
Relaxed checks of violations with deferrable constraints

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 66 / 73


CREATE TABLE <table_name> (
<attr> <type> [<column_constraint>],
<attr> <type> [<column_constraint>],
:
[<table_constraint>],
[<table_constraint>],
:
);

DROP TABLE [IF EXISTS] <table_name>;

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 67 / 73


INSERT INTO <table_name> [(<attr>, ...)]
VALUES (<values>, ...) [, (<values>, ...)];

UPDATE <table_name>
SET <attr> = <value> [, <attr> = <value>]
[WHERE <condition>];

DELETE FROM <table_name> [WHERE <condition>];

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 68 / 73


Type Column Table Condition
Not-NULL NOT NULL - IS NOT NULL
Unique UNIQUE UNIQUE(A1,A2,...) x.Ai <> y.Ai

Primary Key PRIMARY KEY PRIMARY KEY(A1,A2,...) UNIQUE & NOT NULL
FOREIGN KEY (A1,A2,...) The tuple exists in R1
Foreign Key REFERENCES R1(B)
REFERENCES R1(B1,B2,...) or the tuple contains NULL value
General CHECK (c) CHECK (c) Condition c does not evaluate to False

CS2102: Database Systems -- Adi Yoga Sidi Prabawa 69 / 73


postgres=# exit
Press any key to continue . . .

CS2102: Database Systems -- Adi Yoga Sidi Prabawa

You might also like