0% found this document useful (0 votes)
7 views

b

Uploaded by

nhatthong130403
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)
7 views

b

Uploaded by

nhatthong130403
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/ 40

ISYS3414

Practical Database Concepts


Week 6
Basic SQL queries
RMIT Classification: Trusted

Today’s agenda
ERD to Relational Schema
Arithmetic operators
• AND, OR, NOT,
• <, <=, =, <>,>
Expression
• +,-,*,/
• LIKE _,%
SET operators
• UNION, INTERSECT, EXCEPT
• UNION ALL, INTERSEC ALL, EXCEPT ALL
• IN, NOT IN
• EXISTS, NOT EXISTS
• ANY, ALL
RMIT Classification: Trusted

Entities to Relations
Entities to Relations

Strong entity Weak entity


• Create a new relation • Create a new relation
• Include all attributes as columns • Include all attributes as columns
• Include primary key • Primary key = partial key + primary key
from the strong entity
• Foreign key referencing to the primary
key of the strong entity
Weak Entities to Relations
Creation of a new table + foreign key referencing the strong entity
Primary Key of the table is composed by the partial key and primary key of the
strong entity.

Important Note: In this example, pname is the


partial key, NOT the primary key, of Dependents.
We could add “ON DELETE CASCADE” CREATE TABLE Dependents( Thus, two different dependents can have the same
to enforce that when a Employee is pname CHAR(20), pname. The primary key of dependents is pname
together with the SSNof an employee.
removed its dependents are also age INTEGER,
removed at the same time.
cost REAL,
ssn CHAR(11),
PRIMARY KEY(pname, ssn),
FOREIGN KEY(ssn) REFERENCES Employee(ssn)) 11
RMIT Classification: Trusted

Relationships to Relations
Entity, Many-to-Many relationship

CREATE TABLE Employee ( CREATE TABLE Department (


ssn CHAR(11), did CHAR(10),
name CHAR(30), dname CHAR(30),
address VARCHAR(255), budget INT,
PRIMARY KEY (ssn)) PRIMARY KEY (did))

CREATE TABLE Works_in(


ssn CHAR(11),
did INTEGER,
since DATE,
PRIMARY KEY(ssn, did),
FOREIGN KEY(ssn) REFERENCES Employee(ssn),
FOREIGN KEY(did) REFERENCES Department(did))

Employee(ssn,address,name)
Department(did,dname,budget) Relational Schema
works_in(Employee.ssn ssn, Department.did did,since)
Relationships to Relations | One-to-Many

One-to-Many relationships = Parent – Children relationships


• No new table created
• Table on the “Many” side is added with a new attribute as a foreign key
referencing to the primary key in table on the “One” side.
• Table on the “Many” side is also added with attributes emerging from the
relationship
Relationships to Relations | One-to-Many

Case: One-to-Many Relationships

o Add Foreign Key to the table


that has Many relationship CREATE TABLE Employee (
o Add attribute of relationship (if ssn CHAR(11),
any) to the table name VARCHAR(100),
address VARCHAR(255),
did INTEGER,
since DATE,
PRIMARY KEY(ssn),
FOREIGN KEY(did) REFERENCES Department(did)) 8
Relationships to Relations | One-to-One

One-to-One relationships = Parent – Child relationships


• No new table created
• In case of Optional – Mandatory relationship:
Table on the mandatory side is added with a new attribute as a NOT NULL
foreign key referencing to the primary key in table on the optional side.

• In case of Mandatory – Optional relationship:


Table on the optional side is added with a new attribute as a foreign key
referencing to the primary key in table on the mandatory side
Relationship Sets to Relations | One-to-One

Reading from left-to-right: Optional One-to-Mandatory one Relationship


o Addition of a (NOT NULL) Foreign Key to the existing table Department

o Bring the Primary key of CREATE TABLE Department(


side to the side of to did INTEGER,
create a NOT NULL dname VARCHAR(20),
Foreign key budget REAL,
ssn CHAR(11) NOT NULL,
o Each department must since DATE,
have a manager PRIMARY KEY(did),
FOREIGN KEY(ssn) REFERENCES Employee(ssn)) 9
Relationship to Relations | One-to-One

Reading from right to left: Mandatory One-to-Optional Relationships


o Addition of a (NOT NULL) Foreign Key to the existing table Employee

o Bring the Primary key of CREATE TABLE Employee(


side to the side of to ssn INTEGER,
create a Foreign key name VARCHAR(20),
address VARCHAR(100),
dept_ID CHAR(11),
o An employee can be a since DATE,
manager of a department PRIMARY KEY(ssn),
FOREIGN KEY(dept_ID) REFERENCES Department(did)) 9
Relationships to Relations | One-to-One

Mandartory participation on both sides


Merge 2 entities in terms of attributes into 1 relation with primary key
selected from either entities

Optional participation of both sides


Determine parent-child from semantics and follow the one-to-one
translation rules in previous slides
Relationships to Relations | One - to - One

• Mandartory participation on both sides


Merge 2 entities in terms of attributes into 1 relation with
primary key selected from either entities
CREATE TABLE Student (
sid INT,
name VARCHAR(50),
email VARCHAR(50),
major_code INT,
major_name VARCHAR(20),
major_description VARCHAR(100),
PRIMARY KEY (sid)
)
Hierarchies to Relations

First Approach: Creation of new tables for the


generalization and specialization number name

The table of the


For each specialization table: generalization is
- Primary Key from generalization created as any
- Foreign Key references the generalization other entity set Staff
- We could add “ON DELETE CASCADE”

CREATE TABLE Academics( ISA


orcid CPA
number INTEGER,
orcid INTEGER,
PRIMARY KEY(number),
FOREIGN KEY(number) REFERENCES Staff(number)))
Academics Accountants
12
Hierarchies to Relations

Second Approach: Creation of new tables (only) for the specializations

CREATE TABLE Academics(


number name
number INTEGER,
name CHAR(30),
orcid INTEGER,
PRIMARY KEY(number)) The attributes of the Staff
generalization are included
in these tables
CREATE TABLE Accountants(
ISA
number INTEGER, orcid CPA
name CHAR(30),
CPA INTEGER,
PRIMARY KEY(number)) Academics Accountants

This approach can be used when there is a COVER


constraint over the generalization entity. What are the Pros and Cons of
Example: Academics AND Accountants COVER Staff these two approaches?

13
Aggregations to Relations

Similar approach as for Relationship Sets


• First, translate the relationship
inside the aggregation (Eg:
works in)

• Then, translate the relationship


that links to the aggregation
(Eg: uses)

Project(pID,pName,budget)
Employee(ssn,name,lot,since,Project.pID pID)
Machinery(mID,info,Project.pID pID)
Uses(Employee.ssn ssn,Machinery.mID mID)

14
RMIT Classification: Trusted

Exercise

15
Exercise
Write the relational schema to implement the below Entity-Relationship diagram.

14
Exercise

14
Documenting Entity-Relationship
Entities
Entity & Description Attribute & Description Data type and example value Nul Primary key

Ex.
Entity & Description Attribute & Description Data type and example value Null Primary key

Student sid: student’s 7-digit number No Primary key


An undergraduate student identication number
who studies a 3-year
bachelor degree email: email address string with email address format of No
issued by the university maximum length of 50 characters
Course
A course in a degree
curriculum
Documenting Entity-Relationship
Relationships
Relationship & Description Attribute & Description Entities Multiplicity Note

Ex.
Relationship & Description Attribute & Description Entities Multiplicity Note

Take_course Final_marks: a single student - course many-to-many A student can take at


A student takes one or number from 0 to 100 most 3 courses a
several courses in a representing student’s semester.
semester performance in a course
RMIT Classification: Trusted

Notes

Every SQL query references, at least, one table


We can show all columns (using * symbol) or only a few
Ex. SELECT * FROM student;
Ex. SELECT name, number FROM student;
RMIT Classification: Trusted

SQL Statement

Selected data comes from one or more tables from from-list

SELECT [DISTINCT] select-list


FROM from-list
[WHERE conditions]

select-list indicates which columns are selected from these tables


• Similar to the algebra operator 𝜋.
• DISTINCT removes duplicated tuples
We can filter the rows by adding conditions
Selection operator 𝜎 allowing: AND, OR, NOT, <, <=, =, <>,>, ...
RMIT Classification: Trusted

How DBMS evaluates a SQL query

DBMS way
Step 1. Checks if the query is according to the (correct) syntax
Step 2. Checks if all the tables and columns exist
Step 3. Executes the query in the most efficient way possible

Generic Algorithm way (not efficient) of executing a SQL query


Step 1. Computes the Cartesian product of all tables in from-list (FROM)
Step 2. Removes the rows that do not satisfy qualification (WHERE)
Step 3. Removes the columns not in select-list (SELECT)
Step 4. Removes duplicated rows if DISTINCT is used

DBMS always tries to avoid computing Cartesian product;


Wheneveritis possible,DBMS applies conditions from qualification.
RMIT Classification: Trusted

Example – Intended database


RMIT Classification: Trusted

Example – Create database

Syntax: CREATE TABLE Table_name(list of attributes data-type and list of constraints)

CREATE TABLE Sailors(sid INT, sname VARCHAR(20), rating INT, age FLOAT, PRIMARY KEY (sid));
CREATE TABLE Boats(bid INT, bname VARCHAR(20), color VARCHAR(10), PRIMARY KEY (bid));
CREATE TABLE Reserves(sid INT, bid INT, day VARCHAR(30), PRIMARY KEY (sid, bid), FOREIGN KEY
(sid) REFERENCES Sailors(sid), FOREIGN KEY (bid) REFERENCES Boats(bid));
RMIT Classification: Trusted

Example – Create database


CREATE TABLE Sailors(
sid INT,
sname VARCHAR(20),
rating INT,
age FLOAT,
PRIMARY KEY (sid)
);

CREATE TABLE Boats(


bid INT,
bname VARCHAR(20),
color VARCHAR(10),
PRIMARY KEY (bid)
);

CREATE TABLE Reserves(


sid INT,
bid INT,
day VARCHAR(30),
PRIMARY KEY (sid, bid),
FOREIGN KEY (sid) REFERENCES Sailors(sid),
FOREIGN KEY (bid) REFERENCES Boats(bid));

Rewritten for easy-to-read


RMIT Classification: Trusted

Example – Insert data into database


Syntax
INSERT INTO Table_name(list-of-attributes) VALUES (data
values for a row), (data values for another row),

INSERT INTO Sailors(sid, sname, rating, age)


VALUES (22, 'Dustin', 7, 45.0),
(29, 'Brutus', 1, 33.0),
(31, 'Lubber', 8, 55.5),
(32, 'Andy', 8, 25.5),
(58, 'Rusty', 10, 35.0),
(64, 'Horatio', 7, 35.0),
(71, 'Zorba', 10, 16.0),
(74, 'Horatio', 9, 35.0),
(85, 'Art', 3, 25.5),
(95, 'Bob', 3, 63.5);

INSERT INTO Boats(bid, bname, color)


VALUES (101, 'Interlake', 'blue’),
(102, 'Interlake', 'red’),
(103, 'Clibber', 'green’),
(104, 'Marine', 'red’);

INSERT INTO Reserves(sid, bid, day)


SQL Statements are separated by a “ ; ” VALUES (22, 101, '10/10/96’), (58, 103, '11/12/96');
RMIT Classification: Trusted

Query one table


Syntax
SELECT list-of-columns
FROM table_name

Name and age of all sailors


SELECT DISTINCT S.sname, S.age
FROM Sailors S

Without distinct With distinct = duplication removed


RMIT Classification: Trusted

Applying conditions over rows on a table


Syntax
SELECT list-of-columns
FROM table_name
WHERE conditions

Sailors with a rating above 7


SELECT S.sid, S.sname, S.rating, S.age
FROM Sailor S
WHERE S.rating > 7

WHERE condition is applied to every row of Sailors


Rows that satisfy the condition are selected

This query shows all columns of Sailors. Instead of writing all columns
in the SELECT clause, we can write SELECT *
RMIT Classification: Trusted

Query two tables


Question:
What are the names of sailors who reserve the
boat 103?

SELECT S.sname
FROM Sailors S, Reserves R
WHERE S.sid = R.sid AND R.bid = 103

table-join
row filter condition
condition
FROM Sailors S, Reserves R WHERE S.sid = R.sid R.bid = 103
RMIT Classification: Trusted

Example

Question:
Who reserved a red boat?

Query:
Get the names of Sailors who
reseved a red boat.
RMIT Classification: Trusted

Example
Query: Get the names of Sailors who reseved a red boat.

SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND
B.color = 'red'

Reserves ⋈ Boats ⋈ Sailors


RMIT Classification: Trusted

Expressions in the SELECT - list

Select-List can include arithmetic expressions or functions’ calls


Sailors.rating + 1 , Length(Sailors.name)
Use the keyword “AS” to change a column’s name in the query result
Sailors.rating + 1 AS new_rating

Ex. Calculate the rating increments (+1) of the sailors who reserved two boats in the same day

SELECT DISTINCT S.sname, S.rating + 1 AS new_rating


FROM Sailors S, Reserves R1, Reserves R2
WHERE S.sid = R1.sid AND S.sid = R2.sid
AND R1.day = R2.day AND R1.bid <> R2.bid
RMIT Classification: Trusted

Expressions in the WHERE - list

Where-List can include arithmetic expressions or functions’ calls


Ex. Name of the Sailors who have double or higher rating than another sailor
SELECT S1.sname, S2.sname
FROM Sailors S1, Sailors S2
WHERE S1.rating >= 2 * S2.rating
LIKE operator supports simple regular expressions
• Symbol% represents 0 or more (arbitrary) characters
• Symbol _ represents one (arbitrary) character
Ex. The age and name of the sailors whose names start with ‘L’ and end with ‘R’ and with at least 3 characters
SELECT S.age, S.sname
FROM Sailors S
WHERE S.sname LIKE 'L_%R'
RMIT Classification: Trusted

Set operators

Two compatible sets of rows, which have


Same number of columns with the same domains
can be combined.
• Union
SELECT ... UNION SELECT ...
• Intersection
SELECT ... INTERSECT SELECT ...
• Difference
SELECT ... EXCEPT SELECT...

* All duplicated rows are removed by default. To include duplicates, use UNION ALL, INTERSECT ALL,
EXCEPT ALL
RMIT Classification: Trusted

UNION Example
Names of the sailors who reserve green OR red boats

SELECT DISTINCT S.sname


FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid AND
R.bid = B.bid AND (B.color = 'green' OR B.color = 'red')

Alternative
with UNION
SELECT DISTINCT S.sname
FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid AND
R.bid = B.bid AND B.color = 'green'
UNION
SELECT DISTINCT S.sname
FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid AND
R.bid = B.bid AND B.color = 'red'
RMIT Classification: Trusted

Summary
Practice translating ERD to Relational Schema
Arithmetic operators
AND, OR, NOT,
<, <=, =, <>,>
Expression
+,-,*,/
LIKE _,%
SET operators
UNION, INTERSECT, EXCEPT
UNION ALL, INTERSEC ALL, EXCEPT ALL

Further reading
Chapter 17. Methodology – Logical Database Design for the Relational Model

You might also like