Post on 04-Apr-2018
7/30/2019 Lecture04(3)
1/9
CXB 3104
Advanced Database Systems
Lecture 4 SQL, Sub Queries
1
SQL Principals
SQL as a data definition language:
allows users to describe the relations and constraints.
SQL as a query language:
declarative - you specify what you want and not how to
retrieve
relationally complete
Updates in SQL:
allows users to insert, delete and modify tables
2
SQL Principals - Enhancements
Triggers (SQL:1999)
Programs that respond to events relating to a given
table Stored Procedures(SQL:1999):
Predefined sequences of SQL statements
New data types:
Object-oriented features in SQL:1999, XML in
SQL:2003/2006
Application Programming Interface (API):
ODBC and JDBC provide standard set of DDL/DML
functions
3
Deleting Database Components
The drop command allows the removal of
database components, e.g.
DROP TABLE Lecture RESTRICT; Options:
restrict - specifies that the command must not
be carried out if the component being deleted is
not empty.
cascadethe component is removed together
with the components that depend on it.
4
7/30/2019 Lecture04(3)
2/9
Constraints in RDBMS
UNIQUE, NOT NULL, CHECK
Entity integrity - Primary keys
Referential integrity - Foreign keys
5
Primary Keys
A primary key is a set of columns that together
makes each row distinct
No two rows will have the same value of this
primary key (implies that no two rows can be
identicalduplicates are disallowed)
Every table must have one primary key
A primary key should not contain a null value
since then it may not be possible to identify
some tuples.
6
Intra-relational constraints1
The simplest intra-relational constraints are NOT
NULL, UNIQUE, PRIMARY KEY and CHECK
The first three can be included in a tabledefinition on each column or after the column
definitions
If multiple columns are used to form a composite
PRIMARY KEY, the key definition must be
included in the table definition after the column
definitions.
7
Foreign Keys
A FOREIGN KEY is an inter-relational
constraint that references one or more
rows in the table in which it is defined to aprimary key (strictly a candidate key) in another
table.
Every non-NULL value that exists in a foreign
key attribute must also exist in the table for
which it is the primary key. i.e.:
if B references A, A must exist
8
7/30/2019 Lecture04(3)
3/9
Inter-relational constraints-2
If a row of a table with a foreign key is updated or
deleted violations in the referential constraints can
occur.
Four response modes can be given to the foreign key:
cascade, set null, set default, no action, restrict
9
Altering a Foreign Key
ALTER TABLE Student DROP PRIMARY KEY
CASCADE;
ALTER TABLE Student DROP CONSTRAINT
stLec CASCADE;
ALTER TABLE Student ADD CONSTRAINT
stLec FOREIGN KEY (roomNo,occurs)
REFERENCES Lecture(roomNo,occurs) ON
DELETE CASCADE;
10
Data Manipulation Statements - 1
Data retrieval (Queries)
SELECT custName FROM Customer WHERE
customerCity = Kuala Lumpur; Data storage
INSERT INTO Customer (custName,
customerCity) VALUES (Smith,Penang);
11
Data Manipulation Statements - II
Data modification
UPDATE Customer SET customerCity =
Penang, street = Cheras WHEREcustomerName = Smith;
Data removal
DELETE FROM Customer WHERE
customerName = Smith;
12
7/30/2019 Lecture04(3)
4/9
SQL Simple Selects
Find the branch names for each deposit of customers Smith and
Chen that have a balance greater than 200 or less than 100:
SELECT DISTINCT branchName FROM Deposit WHERE
customerName = Smith OR customerName = Chen
AND balance > 200 OR balance < 100;
SELECT DISTINCT branchName FROM Deposit WHERE
balance NOT BETWEEN 100 AND 200 AND
customerName IN (Smith, Chen);
13
SQL Union
Find the names of all customers who have either a loan
or an account at the RHB branch:
( SELECT customerName FROM Deposit
WHERE branchName = RHB ) UNION
( SELECT customerName FROM Loan WHERE
branchName = RHB );
14
SQL Intersection
Find the names of all customers who have both a loan
and an account at the RHB branch
( SELECT customerName FROM Deposit
WHERE branchName = RHB ) INTERSECT
( SELECT customerName FROM Loan
WHERE branchName = RHB );
15
SQL Minus
Return the rows that are in the first table except those
rows that also appear in the second table:
( SELECT customerName FROM Deposit
WHERE branchName = RHB ) MINUS
( SELECT customerName FROM Borrow
WHERE branchName = RHB );
16
7/30/2019 Lecture04(3)
5/9
Multiple Table Queries (Joins)
Can specify multiple tables in the FROM clause to
perform an inner join:
SELECT * FROM Loan, Customer WHERE
Loan.customerName=Customer.customerName;
An alternative way of writing joins:
SELECT * FROM Loan JOIN Customer ON
Loan.customerName =Customer.customerName;
17
Inner Join with condition
Specify which column to join and a conditional clause:
SELECT Loan.customerName FROM Loan,
Customer WHERE Loan.customerName =
Customer.customerName AND Loan.amount >
2000 AND Customer.customerCity = Kuala
Lumpur;
18
Inner Joinsexample (aliases)
19
Outer Joins
Preserve unmatched rows from one or both
tables
LEFT [OUTER] JOIN - preserves unmatchedrows from the left table
RIGHT [OUTER] JOIN - preserves
unmatched rows from the right table
FULL [OUTER] JOIN - preserves unmatched
rows from both tables
Rows that dont match are given NULL values
for columns from the other table
20
7/30/2019 Lecture04(3)
6/9
Left Outer Join - example
21
Right outer join
22
Full Outer Join
23
Single Table Self-Join
Find all the customers who have an account at
same branch at which Patel has an account (also
output the branch names)
SELECT T.customerName FROM
Deposit S, Deposit T WHERE
S.customerName = Patel AND
S.branchName = T.branchName;
24
7/30/2019 Lecture04(3)
7/9
Built-In Functions
Operate on the set of values in a column of a relation and
return a single value. E.g.
SUM([DISTINCT] column-name): sum of values
AVG([DISTINCT] column-name): average value
MIN(column-name): minimum value
MAX(column-name): maximum value
COUNT([DISTINCT] column-name): number of values
excluding NULLS
COUNT(*): number of values in column including NULLS
- where DISTINCT means only include values that are different
25
Sub queries: The IN Clause
A sub query is a query that appears in the body of
another expression.
E.g. find the names of a ll customers who have both a
loan and account at the RHB
SELECT customerName FROM Loan
WHERE branchName = RHB AND
customerName IN
(SELECT customerName FROM Deposit
WHERE branchName = RHB);
26
Sub queries and Joins
A sub query can sometimes also be expressed as a join.
E.g. find the names of a ll customers who have both a
loan and account at the RHB
SELECT Loan.customerName FROM Loan, Deposit
WHERE Loan.branchName = RHB AND
Deposit.branchName = RHB AND
Loan.customerName = Deposit.customerName;
27
Sub queries: The ANY Clause
Find all branches that have greater assets than
at least one branch located in Kuala Lumpur
SELECT branchName
FROM Branch
WHERE assets > ANY
(SELECT assets
FROM Branch
WHERE branchCity = Kuala Lumpur);
28
7/30/2019 Lecture04(3)
8/9
Sub queries: The ALL Clause
Find the names of all branches that have greater assets
than every branches located in Kuala Lumpur
SELECT branchName
FROM Branch
WHERE assets > ALL
(SELECT assets
FROM Branch
WHERE branchCity = Kuala Lumpur);
29
Sub queries: The IN Clause
Find all customers who DO NOT have an account at a
branch named RHB:
SELECT S.customerName
FROM Customer S
WHERE customerName NOT IN
(SELECT customerName
FROM Deposit T
WHERE branchName = RHB);
30
Sub queries: The EXISTS Clause
Find all customers who DO NOT have an account at a
branch named CIMB:
SELECT S.customerName
FROM Customer S
WHERE NOT EXISTS
(SELECT T.customerName
FROM Deposit T
WHERE branchName = CIMB
AND S.customerName =
T.customerName);
31
Insertion using a query
Provide all loan customers in the RHB branch with a $
200 saving account. Let the loan number serve as the
account number for the new savings account
INSERT INTO Deposit
SELECT customerName, branchName,
loanNumber, 200
FROM Loan WHERE branchName = RHB;
32
7/30/2019 Lecture04(3)
9/9
Deletion using a sub query
Delete all accounts at banks located in CIMB
DELETE FROM Deposit
WHERE branchName IN
(SELECT branchName
FROM Branch
WHERE branchCity = CIMB);
33