Lecture 4 - Structural Query Language (SQL) - Part II PDF
Lecture 4 - Structural Query Language (SQL) - Part II PDF
Database Systems
Unit 4 :
Structural Query
Language
(SQL) Part 2
Unit 4 :
Structural Query Language (SQL)
Topic 4
Objective :
At the end of this unit, you should be able to:
Use SQL subquery for data retrieval
Data Manipulation Language (DML) and
Data Definition Language (DDL) in SQL
Referential Integrity in database tables
Topic 4
Content
Subqueries in SQL
Data Definition Language Create
database, Create Table, Alter table, Drop
database, Drop table
Data Manipulation Language - INSERT /
UPDATE / DELETE
Topic 4
Subqueries in SQL
Subqueries
(Nested Queries)
Topic 4
Subqueries in SQL
( with = )
StateName
Population
Customer
CustId
Fname Lname
AK
Alaska
628,000
C01
John
Brown
AK
CA
California
34,000,000
C02
Ethan
Harris
CA
AL
Alabama
4,500,000
C03
Sophia
Cole
AL
FL
Florida
16,000,000
StateCode
Fname
Lname
Ethan
Harris 5
Topic 4
Subqueries in SQL
Topic 4
Subqueries in SQL
( with IN )
SELECT CName
FROM STUDENT
WHERE SID IN
(SELECT StudNo
FROM ENROLLMENT
WHERE ClassNo = BD445) ;
CName
Jones
Baker
ENROLLMENT
STUDENT
SID
CName Major
Age
100
Jones
Accounting
150
Parks
200
StudNo
ClassNo
21
100
BD445
Math
19
150
BA200
Baker
History
16
200
BD445
250
Glass
History
18
250
CS250
300
Andy
Accounting
17
300
CS250
Position
Topic 4
Subqueries in SQL
CLASS
CName
Time
BA200
MWF9
SC110
BD445
MWF3
SC213
BF410
MWF8
SC213
CS150
MWF3
EA304
CS250
MWF12
EB210
Room
ENROLLMENT
StudNo
ClassNo
SELECT STUDENT.CName
FROM STUDENT
WHERE STUDENT.SID IN
(SELECT ENROLLMENT.StudNo
FROM ENROLLMENT
WHERE ENROLLMENT.ClassNo IN
(SELECT CLASS.CName
FROM CLASS
WHERE CLASS.Time = MWF3))
STUDENT
Position
SID
CName Major
Age
100
BD445
100
Jones
Accounting
21
150
BA200
150
Parks
Math
19
200
BD445
200
Baker
History
16
CName
200
CS250
250
Glass
History
18
Jones
300
CS250
300
Andy
Accounting
17
Baker
Topic 4
Parks
Math
19
200
Baker
History
16
250
Glass
History
18
300
Andy
Accounting
17
ENROLLMENT
CName
200
BD445
200
CS250
CLASS
CName
Time
Position
Room
StudNo
ClassNo
100
BD445
BA200
M-F9
SC110
150
BA200
BD445
MWF3
SC213
200
BD445
BF410
MWF8
SC213
200
CS250
CS150
MWF3
EA304
300
CS250
CS250
MWF12
EB210
Position
SID
Topic 4
Subqueries in SQL
( with EXISTS )
10
Topic 4
Subqueries in SQL
( with EXISTS )
ENROLLMENT_A
ENROLLMENT_B
StudNo
ClassNo
Position
StudNo
ClassNo
Position
100
BD445
100
BD445
150
BA200
150
BA200
200
BD445
200
BD445
200
CS250
200
CS250
300
CS250
300
CS250
The result is :
StudNo
200
Compare row 1 in A with row 1 in B. If StudNo and ClassNo are identical, non-exist, no display.
Compare row 3 in A with row 4 in B. Same StudNo but different ClassNo, exist, display StudNo from A
IT1768 Database Systems
11
Topic 4
Emp_Num
Employee
Emp_Name Salary
E-01
James
2,500
E-02
Jennifer
3,600
E-03
Gilbert
3,200
12
Topic 4
Emp_Name Salary
E-01
James
SELECT Salary
E-02
Jennifer
FROM Employee
E-03
Gilbert
WHERE Salary >
(SELECT AVG(salary)
FROM employee) ;
2,500
3,600
3,200
Emp_Num
Emp_Name Salary
E-02
Jennifer
3,600
E-03
Gilbert
3,200
SELECT Salary
FROM Employee
WHERE Salary > AVG(Salary)
13
Topic 4
14
Topic 4
DROP TABLE
DROP INDEX
DROP VIEW
15
Topic 4
16
Topic 4
A Table definition
Consists of a list of definitions of columns that make up a row in
the table.
17
Topic 4
CREATE TABLE
(Cust_Num
Last_Name
First_Name
State
CUSTOMER
Cust_Num
Last_Name
First_Name
State
Jennifer
CA
What is a constraint
A constraint implements a business rule that restricts
values stored in a table.
Constraints are implemented as either:
Table constraints that apply to the entire table or
Column constraints that apply to a single column.
IT1768 Database Systems
18
Topic 4
Unique constraint
prevents duplicate values for a column or group of columns.
Default constraint
if value for a column is not specify during an insert, it will take
the default given.
Domain constraint
to specify the set of allowable values that a column can have.
IT1768 Database Systems
19
Topic 4
Example 1 ( create table with Primary Key & Foreign Key constraint )
CREATE TABLE CUSTOMER
( CUST_NUM
NUMBER(5) NOT NULL,
Constraints
LAST_NAME
VARCHAR(15),
FIRST_NAME
VARCHAR(8),
STATE
VARCHAR(2),
CONSTRAINT cust_num_pk
PRIMARY KEY ( CUST_NUM ),
CONSTRAINT state_fk
FOREIGN KEY( STATE ) REFERENCES STATE(STATE_CODE ) );
NUMBER(5),
VARCHAR(3) NOT NULL,
VARCHAR(30) );
20
Topic 4
21
Topic 4
ALTER TABLE
T-01
Sugar
T-02
Salt
T-03
Powder
NOT NULL ;
22
Topic 4
ALTER TABLE
Alter Table by
altering attribute
properties
23
Topic 4
DROP Table
Format/Syntax
Drop == Destroy
DROP TABLE command deletes a table. By default, DROP TABLE also deletes
the tables data.
DROP TABLE CUSTOMER CASCADE automatically drops objects that depend
on the table
DROP TABLE CUSTOMER RESTRICT refuses to drop the table if there are any
dependent objects.
DROP TABLE CUSTOMER %NODELDATA, this option can prevent the
automatic deletion of the table's data.
IT1768 Database Systems
24
Topic 4
INSERT statement ;
Add a new row into a table.
Copy data from one table to another.
UPDATE statement ;
Modify attribute values of existing rows.
DELETE statement ;
Drop any number of rows from a table.
COMMIT ;
To commit the changes, i.e. make the change permanent
ROLLBACK ;
To rollback (discard) the changes
IT1768 Database Systems
25
Topic 4
INSERT Statement
Create a single row
INSERT INTO [table-name] [(column1, ... , columnN)]
VALUES
(value1, .., valueN) ;
column1, column2, is optional.
If omitted, SQL assumes a list of all columns in the table.
26
Topic 4
INSERT Statement
ClassNo
100
BD445
150
BA200
200
BD445
200
CS250
300
CS250
400
BD445
44
Position
Topic 4
INSERT Statement
INSERT INTO
REGISTER ( StudNum, Course, Semester, Date_Reg )
VALUES ( 072416P, ITDF04, One, NULL );
Note:
It is mandatory to supply values for all columns; besides those columns
defined as NOT NULL, those with no default value should be assigned
with NULL or DEFAULT).
StudNum
Course
Semester
Date_Reg
074592G
ITDF02
One
16-Mar-2008
072789K
ITDF03
One
16-Mar-2008
072416P
ITDF04
One
NULL
The newly inserted row
28
Topic 4
INSERT Statement
The newly
inserted rows
Emp_Num
Fname
Lname
DOB
Salary
Purc-06
Jennifer
Yee
16-Mar-1965
2,800
Wh-05
Peter
Ng
26-Feb-1986
2,950
Prod-01
Jacob
Lee
12-Mar-1976
3,000
Engg-12
Sunny
Chin
03-May-1968
3,500
QA-08
Susan
Kwek
23-Dec-1980
2,600
29
Topic 4
INSERT Statement
(Advanced statement)
Example 1:
INSERT INTO STUD_DETAIL
SELECT StudNo, Name, Major
FROM STUDENT
WHERE StudNo = 072318P ;
Note : This syntax may not work with MS Access
30
Topic 4
INSERT Statement
(Advanced statement)
Example 2:
Suppose a follow-up call is required for every order that has
been paid but not shipped.
Create those rows in the CUST_CALLS table.
31
Topic 4
INSERT Statement
(Advanced statement)
Example :
Suppose retrieving sales records in year 2008 and insert new
rows in the STORE_INFOR table.
32
Topic 4
UPDATE Statement
Format/Syntax
UPDATE
SET
WHERE
[table-name]
column-name1 = data-value1
[,column-name = data-value2...]
[condition] ;
33
Topic 4
UPDATE Statement
Example 1
UPDATE
CUSTOMER
SET
FNAME = Barnaby,
LNAME = Dorfler
WHERE CUSTOMER_NUM = 113;
Example 2
Write an update statement to show that the supplier HRO
has raised all prices by 5%.
UPDATE PRODUCT
SET
UNIT_PRICE = UNIT_PRICE * 1.05
WHERE SUPPL_CODE = HRO;
IT1768 Database Systems
34
Topic 4
UPDATE Statement
Example 3 :
UPDATE
SET
WHERE
ENROLLMENT
Position = 44
StudNo = 400
ENROLLMENT
StudNo
ClassNo
100
BD445
150
BA200
200
BD445
200
CS250
400
CS250
Position
ENROLLMENT
StudNo
ClassNo
Position
100
BD445
150
BA200
200
BD445
200
CS250
400
CS250
44
35
Topic 4
UPDATE Statement
Example 4 :
UPDATE
SET
WHERE
ENROLLMENT
Position = MAX(Position) + 1
StudNo = 400
ENROLLMENT
StudNo
ClassNo
100
BD445
150
BA200
200
BD445
StudNo
ClassNo
200
CS250
100
BD445
400
CS250
150
BA200
200
BD445
200
CS250
400
CS250
Position
ENROLLMENT
Position
Note : MAX(Position) is 3
36
Topic 4
UPDATE Statement
Example 5 :
UPDATE ENROLLMENT
SET
Position = 6
WHERE StudNo = 200 AND ClassNo=CS250
ENROLLMENT
StudNo
ClassNo
100
BD445
ENROLLMENT
150
BA200
StudNo
ClassNo
200
BD445
100
BD445
200
CS250
150
BA200
300
CS250
200
BD445
200
CS250
300
CS250
Position
Position
37
Topic 4
DELETE Statement
Format/Syntax
DELETE FROM [table-name]
WHERE [condition] ;
WHERE clause is optional:
If omitted, all rows are deleted from table. This does
not delete the table.
If condition is specified, only those rows that satisfy
the condition are deleted.
38
Topic 4
DELETE Statement
Address
Phone
C-01
5 AMK Ave 1
61111111
C-02
62222222
C-03
63333333
Cust_Num
Cust_Name
Address
Phone
39
Topic 4
DELETE Statement
Address
Phone
C-01
5 AMK Ave 1
61111111
C-02
62222222
C-03
63333333
Cust_Num
Cust_Name
Address
Phone
C-01
5 AMK Ave 1
61111111
C-03
63333333
40
Topic 4
DELETE Statement
Address
Phone
C-01
5 AMK Ave 1
61111111
C-02
62222222
C-03
63333333
Cust_Num
Cust_Name
Address
Phone
C-01
5 AMK Ave 1
61111111
C-02
62222222
41
Topic 4
DELETE Statement
Example 4 (Use Specific tables name in WHERE command):
DELETE FROM STUDENT
WHERE STUDENT.Major = Accounting)
STUDENT
ENROLLMENT
SID
CName Major
Age
100
Jones
Accounting
150
Parks
200
StudNo
ClassNo
21
150
BA200
Math
19
200
BD445
Baker
History
16
200
CS250
250
Glass
History
18
300
Andy
Accounting
17
Position
42
Topic 4
DELETE Statement
Example 5 :
StudNo
DELETE FROM ENROLNMENT
150
WHERE ENROLLMENT.StudNo IN
200
(SELECT STUDENT.SID
FROM STUDENT
200
WHERE STUDENT.Major = Accounting)
STUDENT
ClassNo
Position
BA200
BD445
CS250
ENROLLMENT
SID
CName Major
Age
100
Jones
Accounting
150
Parks
200
StudNo
ClassNo
21
100
BD445
Math
19
150
BA200
Baker
History
16
200
BD445
250
Glass
History
18
200
CS250
300
Andy
Accounting
17
300
CS250
Position
43
Topic 4
EXERCISE REVIEW 1
Guest
CheckInDate
Hotel
Diana Jones
12-Jul-2004
Costa Bonaventure
John Smith
18-Aug-2004
Sun Palm
Justin Black
12-Aug-2004
Costa Bonaventure
Booking
HotelName
WebAddress
Costa Bonaventure
www.costabonaventure.com.la
Sand Coasts
www.sancoasts.com.la
Sun Palm
www.sunpalm.com.sf
Star_Rating
Min_price
Hotel
Max_price
$300
$499
$200
$299
$100
$199
$50
$99
Rating
Category
44
Topic 4
EXERCISE REVIEW 1
..continue
(b) Display the names of hotels that have more than one
booking.
(c)
(d) Add a new booking for guest, Brian Williams who wants
to check-in on the 5th August 2004 to Sun Palm.
45
Topic 4
Referential Integrity
Name
Title
Address
Sector
Size
branch_ID
FK in child table
ISO standard supports the definition of foreign keys with the FOREIGN
KEY clause in the CREATE and ALTER TABLE statements, for example :
FOREIGN KEY (branch_ID) REFERENCES Branch (branchNo)
IT1768 Database Systems
46
Topic 4
Referential Integrity
B_ID
Name
Bravo
Alpha
TESTA
B_ID
TESTB
B_No fk
47
Topic 4
Referential Integrity
B_ID
Name
Bravo
Alpha
48
Topic 4
Summary
SQL statements for multiple tables :
- Sub-queries
- Joins
49
Topic 4
EXERCISE REVIEW 1
(Solution)
(c) Display the names and web addresses of hotels that charge
$100 and above but less than $300.
SELECT HotelName, WebAddress from HOTEL where
Rating in (SELECT STAR_rating from CATEGORY where MinPrice
>=$100 and MaxPrice <$300)
(d) Add a new booking for guest, Brian Williams who wants to
check-in on the 5th August 2004 to Sun Palm.
INSERT into BOOKING (Guest, CheckInDate,Hotel) values (Brian
Williams,05-Aug-2004,Sun Palm)
IT1768 Database Systems
50