0% found this document useful (0 votes)
36 views42 pages

W9. SQL - Data Manipulation Language Advanced

Uploaded by

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

W9. SQL - Data Manipulation Language Advanced

Uploaded by

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

Database Systems

SQL
Data Manipulation - Advanced
Prepared By
Mehak Usmani

Content taken from: © Pearson Education Limited 1995, 2005 1


Objectives
• How to build SQL statements that:
• Join tables together.
• Perform set operations (UNION, INTERSECT, EXCEPT).
• How to update database using INSERT, UPDATE, and DELETE.

2
Multi-Table Queries
• Can use subqueries provided result columns come from same table.

• If result columns come from more than one table must use a join.

• To perform join, include more than one table in FROM clause.

• Use comma as separator and typically include WHERE clause to specify join
column(s).

3
Multi-Table Queries
• Also possible to use an alias for a table named in FROM clause.

• Alias is separated from table name with a space.

• Alias can be used to qualify column names when there is ambiguity.

4
Simple Join
List names of all clients who have viewed a property along with any
comment supplied.

SELECT c.clientNo, fName, lName,


propertyNo, comment
FROM Client c, Viewing v
WHERE c.ID= v.clientNo;

5
Simple Join
• Only those rows from both tables that have identical values in the clientNo
columns (c.clientNo = v.clientNo) are included in result.

• Equivalent to equi-join in relational algebra.

6
Alternative JOIN Constructs
• SQL provides alternative ways to specify joins:

• FROM Client c JOIN Viewing v ON c.clientNo = v.clientNo


• FROM Client JOIN Viewing USING clientNo

• In each case, FROM replaces original FROM and WHERE. However, first
produces table with two identical clientNo columns.

7
Sorting a join
For each branch, list numbers and names of staff who manage
properties.

SELECT s.branchNo, s.staffNo, fName, lName,


propertyNo
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo
ORDER BY s.branchNo, s.staffNo, propertyNo;

8
Sorting a join

9
Three Table Join
For each branch, list staff who manage properties, including city in which
branch is located

SELECT s.staffNo, s.fName, s.lName, b.branchNo, b.city, p.*


FROM Branch b,
Staff s,
PropertyForRent p
WHERE b.branchNo = s.branchNo
AND s.staffNo = p.staffNo
ORDER BY fName;

10
Three Table Join

• Alternative formulation for FROM and WHERE:

FROM (Branch b JOIN Staff s USING branchNo) AS


bs JOIN PropertyForRent p USING staffNo

11
Computing a Join
Procedure for generating results of a join are:

1. Form Cartesian product of the tables named in FROM clause.

2. If there is a WHERE clause, apply the search condition to each row of the
product table, retaining those rows that satisfy the condition.

3. For each remaining row, determine value of each item in SELECT list to
produce a single row in result table.

4. If DISTINCT has been specified, eliminate any duplicate rows from the
result table.

5. If there is an ORDER BY clause, sort result table as required.

12
Outer Joins
• If one row of a joined table is unmatched, row is omitted from result table.
• Outer join operations retain rows that do not satisfy the join condition.
• Consider following tables:

13
Outer Joins
• The (inner) join of these two tables:

SELECT b.*, p.*


FROM Branch1 b, PropertyForRent1 p
WHERE b.bCity = p.pCity;

14
Outer Joins
• Result table has two rows where cities are same.
• There are no rows corresponding to branches in Bristol and
Aberdeen.
• To include unmatched rows in result table, use an Outer join.

15
Left Outer Join
List branches and properties that are in same city along with any
unmatched branches.

SELECT b.*, p.*


FROM Branch b LEFT JOIN
PropertyForRent p ON b.City = p.City;

16
Left Outer Join
• Includes those rows of first (left) table unmatched with rows from
second (right) table.
• Columns from second table are filled with NULLs.

17
Right Outer Join
List branches and properties in same city and any unmatched
properties.

SELECT b.*, p.*


FROM Branch b RIGHT JOIN
PropertyForRent p ON b.City = p.City;

18
Right Outer Join
• Right Outer join includes those rows of second (right) table that are
unmatched with rows from first (left) table.
• Columns from first table are filled with NULLs.

19
Union, Intersect, and Difference (Except)
• Can use normal set operations of Union, Intersection, and
Difference to combine results of two or more queries into a single
result table.
• Union of two tables, A and B, is table containing all rows in either A
or B or both.
• Intersection is table containing all rows common to both A and B.
• Difference is table containing all rows in A but not in B.
• Two tables must be union compatible.

20
Union, Intersect, and Difference (Except)

21
Use of UNION
List all cities where there is either a branch office or a property.

(SELECT city
FROM Branch
WHERE city IS NOT NULL) UNION
(SELECT city
FROM PropertyForRent
WHERE city IS NOT NULL);

22
Use of UNION
• Produces result tables from both queries and merges both tables
together.

23
Use of INTERSECT
List all cities where there is both a branch office and a property.

(SELECT city FROM Branch)


INTERSECT
(SELECT city FROM PropertyForRent);

24
Use of INTERSECT
• Could rewrite this query without INTERSECT operator:

SELECT b.city
FROM Branch b PropertyForRent p
WHERE b.city = p.city;

Could rewrite this query with IN also.

25
Use of EXCEPT
List of all cities where there is a branch office but no properties.

(SELECT city FROM Branch)


EXCEPT
(SELECT city FROM PropertyForRent);

26
Use of EXCEPT
• Could rewrite this query without EXCEPT:

SELECT DISTINCT city FROM Branch


WHERE city NOT IN
(SELECT city FROM PropertyForRent);

27
INSERT, UPDATE AND
DELETE

28
INSERT
INSERT INTO TableName [ (columnList) ]
VALUES (dataValueList)

• columnList is optional; if omitted, SQL assumes a list of all columns in


their original CREATE TABLE order.
• Any columns omitted must have been declared as NULL when table
was created, unless DEFAULT was specified when creating column.

29
INSERT
• dataValueList must match columnList as follows:
• number of items in each list must be same;
• must be direct correspondence in position of items in two lists;
• data type of each item in dataValueList must be compatible with
data type of corresponding column.

30
INSERT … VALUES
Insert a new row into Staff table supplying data for all columns.

INSERT INTO Staff


VALUES
('SG16', 'Alan', 'Brown', 'Assistant', 'M', '1957-05-25', 8300, 'B003','454654',
'0665-8965874','alan@gmail.com','stree 1 block 4 ');

31
INSERT using null
Insert a new row into Staff table supplying data for all mandatory
columns.

INSERT INTO Staff


(staffNo, fName, lName, position, salary, branchNo, Telephone,
Mobile, Email, address)
VALUES ('SG16', 'Alan', 'Brown', 'Assistant', 'M', '1957-05-25',
8300, 'B003','454654', '0665-8965874','alan@gmail.com','stree 1
block 4 ');
• Or
INSERT INTO Staff
VALUES (‘SG44’, ‘Anne’, ‘Jones’, ‘Assistant’, NULL,
NULL, 8100, ‘B003’, NULL, NULL, NULL, NULL);

32
INSERT … SELECT
• Second form of INSERT allows multiple rows to be copied from
one or more tables to another:

INSERT INTO TableName [ (columnList) ]


SELECT ...

33
INSERT … SELECT
Assume there is a table StaffPropCount that contains names of
staff and number of properties they manage:

StaffPropCount(staffNo, fName, lName, propCnt)

Populate StaffPropCount using Staff and PropertyForRent tables.

34
INSERT … SELECT
INSERT INTO StaffPropCount
(SELECT s.staffNo, fName, lName, COUNT(*)
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo
GROUP BY s.staffNo, fName, lName)
UNION
(SELECT staffNo, fName, lName, 0
FROM Staff
WHERE staffNo NOT IN
(SELECT DISTINCT staffNo
FROM PropertyForRent));

35
INSERT … SELECT

• If second part of UNION is omitted, excludes those staff who currently


do not manage any properties.

36
UPDATE
UPDATE TableName
SET columnName1 = dataValue1
[, columnName2 = dataValue2...]
[WHERE searchCondition]

• TableName can be name of a base table or an updatable view.


• SET clause specifies names of one or more columns that are to be
updated.

37
UPDATE
• WHERE clause is optional:
• if omitted, named columns are updated for all rows in table;
• if specified, only those rows that satisfy searchCondition are
updated.
• New dataValue(s) must be compatible with data type for
corresponding column.

38
UPDATE All Rows
Give all staff a increment by doubling the salary.

UPDATE Staff
SET salary = salary*2;

Give all Managers a 5% pay increase.

UPDATE Staff
SET salary = salary + (salary * 0.05)
WHERE position = ‘Manager’;

39
UPDATE Multiple Columns
Promote David Ford (staffNo=‘SG14’) to Manager and change his
salary to 38,000.

UPDATE Staff
SET position = ‘Manager’, salary = 38000
WHERE staffNo = ‘SG14’;

40
DELETE
DELETE FROM TableName
[WHERE searchCondition]

• TableName can be name of a base table or an updatable view.


• searchCondition is optional; if omitted, all rows are deleted from
table. This does not delete table. If search_condition is specified,
only those rows that satisfy condition are deleted.

41
DELETE Specific Rows
Delete all viewings that relate to property PG4.

DELETE FROM Viewing


WHERE propertyNo = ‘PG4’;

Delete all records from the Viewing table.

DELETE FROM Viewing;

42

You might also like