Structured Query Language (SQL)

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 145

Structured Query Language

(SQL)
Topics of the Talk
 Purpose and importance of SQL.
 How to retrieve data from database using SELECT a
nd:

– Use compound WHERE conditions.


– Sort query results using ORDER BY.
– Use aggregate functions.
– Group data using GROUP BY and HAVING.
– Use subqueries.

2
Topics of the Talk

– Join tables together.


– Perform set operations (UNION, INTERSECT,
EXCEPT).

 How to update database using INSERT,


UPDATE, and DELETE.
 Data types supported by SQL-92.
 How to create and delete tables.

3
Objectives of SQL
 Ideally, database language should allow user to:
– create the database and relation structures;
– perform insertion, modification, deletion of data
from relations;
– perform simple and complex queries.
 Must perform these tasks with minimal user effort
and command structure and syntax must be easy to
learn.
 It must be portable.

4
Characteristics of SQL

 SQL is a language with 2 major components:

– A DDL for defining the database structure.


– A DML for retrieving and updating data.

 SQL does not contain flow control commands.


– These must be implemented using a
programming language.

5
Characteristics of SQL

 SQL is relatively easy to learn:

– It is a non-procedural language - you specify


what information you require, rather than how
to get it.
– It is essentially free-format.

6
Characteristics of SQL
 Consists of standard English words:

CREATE TABLE staff(sno VARCHAR(5),


lname VARCHAR(15),
salary DECIMAL(7,2));
INSERT INTO staff
VALUES ('SG16', 'Brown', 8300);
SELECT sno, lname, salary
FROM staff
WHERE salary > 10000;

7
Characteristics of SQL

 Can be used by a range of users including DBAs,


management, application programmers, and othe
r types of end users.

 An ISO standard now exists for SQL, making it b


oth the formal and de facto standard language for
relational databases.

8
History of SQL

 In 1974, D. Chamberlin (IBM San Jose Laborator


y) defined language called 'Structured English Qu
ery Language' or SEQUEL.
 A revised version SEQUEL/2 was defined in 1976
but name was subsequently changed to SQL for le
gal reasons.

9
History of SQL

 Still pronounced 'see-quel', though official pronun


ciation is 's-q-l'.
 IBM subsequently produced a prototype DBMS ca
lled System R, based on SEQUEL/2.

10
History of SQL

 In late 70s, ORACLE appeared and was probably


first commercial RDBMS based on SQL.
 In 1987, ANSI and ISO published an initial
standard for SQL.
 In 1989, ISO published an addendum that defined
an 'Integrity Enhancement Feature'.
 In 1992, first major revision to ISO standard
occurred, referred to as SQL2 or SQL/92.

11
Importance of SQL

 SQL has become part of application architectures


such as IBM's Systems Application Architecture
(SAA).
 It is strategic choice of many large and influential
organizations (e.g. X/OPEN).
 SQL is Federal Information Processing Standard
(FIPS) to which conformance is required for all
sales of databases to American Government.

12
Importance of SQL

 SQL Access Group trying to define enhancements


that will support interoperability across disparate
systems.
 SQL is used in other standards and even
influences development of other standards, such as

– ISO's Information Resource Directory System


(IRDS) Standard
– Remote Data Access (RDA) Standard.

13
Writing SQL Commands

 SQL statements consist of reserved words and user-


defined words.

– Reserved words are a fixed part of SQL and


must be spelt exactly as required and cannot be
split across lines.
– User-defined words are made up by user and
represent names of various database objects
such as relations, columns, views.

14
Writing SQL Commands

 Most components of an SQL statement are case ins


ensitive, except for literal character data (name = “
banchong”/”Banchong”/”BANCHONG”).
 More readable with indentation and lineation:
– Each clause should begin on a new line.
– Start of a clause should line up with start of othe
r clauses.
– If clause has several parts, should each appear o
n a separate line and be indented under start of
clause.
15
Writing SQL Commands
 Use extended form of BNF notation:

– Upper case letters represent reserved words.


– Lower case letters represent user-defined words.
– | indicates a choice among alternatives.
– Curly braces ({}) indicate a required element.
– Square brackets ([]) indicate an optional element.
– … indicates optional repetition (0 or more).

16
SELECT Statement

SELECT [DISTINCT | ALL]


{* | [column_expression [AS new_name]] [,...] }
FROM table_name [alias] [, ...]
[WHERE condition]
[GROUP BY column_list]
[HAVING condition]
[ORDER BY column_list]

17
SELECT Statement

FROM Specifies table(s) to be used.


WHERE Filters rows.
GROUP BY Forms groups of rows with same
column value.
HAVING Filters groups subject to some
condition.
SELECT Specifies which columns are to
appear in output.
ORDER BY Specifies the order of the output.

18
SELECT Statement

 Order of the clauses cannot be changed.

 Only SELECT and FROM are mandatory.

19
Example 13.1 All Columns, All Rows

List full details of all staff.

SELECT sno, fname, lname, address, tel_no,


position, sex, dob, salary, nin, bno
FROM staff;
 Can use * as an abbreviation for 'all columns':

SELECT *
FROM staff;

20
Example 13.1 All Columns, All Rows

21
Example 13.2 Specific Columns, All Rows

Produce a list of salaries for all staff, showing only


the staff number, Sno, the first and last names, an
d the salary details.

SELECT sno, fname, lname, salary


FROM staff;

22
Example 13.2 Specific Columns, All Rows

23
Example 13.3 Use of DISTINCT

List the property numbers of all properties that h


ave been viewed.

SELECT pno
FROM viewing;

24
Example 13.3 Use of DISTINCT
 Use DISTINCT to eliminate duplicates:

SELECT DISTINCT pno


FROM viewing;

25
Example 13.4 Calculated Fields

Produce a list of monthly salaries for all staff, sho


wing the staff number, the first and last names, an
d the salary details.

SELECT sno, fname, lname, salary/12


FROM staff;

26
Example 13.4 Calculated Fields

 To name column, use AS clause:

SELECT sno, fname, lname, salary/12


AS monthly_salary
FROM staff;

27
Example 13.5 Comparison Search Condition

List all staff with a salary greater than 10,000.

SELECT sno, fname, lname, position, salary


FROM staff
WHERE salary > 10000;

28
Example 13.5 Comparison Search Condition

29
Example 13.6 Compound Comparison Search
Condition

List the addresses of all branch offices in London


or Glasgow.

SELECT bno, street, area, city, pcode


FROM branch
WHERE city = 'London' OR city = 'Glasgow';

30
Example 13.6 Compound Comparison Search
Condition

31
Example 13.7 Range Search Condition

List all staff with a salary between 20,000 and 30,000.

SELECT sno, fname, lname, position, salary


FROM staff
WHERE salary BETWEEN 20000 AND 30000;

 BETWEEN test includes the endpoints of range.

32
Example 13.7 Range Search Condition

33
Example 13.7 Range Search Condition
 Also a negated version NOT BETWEEN.
 BETWEEN does not add much to SQL's expressive
power Could also write:

SELECT sno, fname, lname, position, salary


FROM staff
WHERE salary>=20000 AND salary <= 30000;

 Useful, though, for a range of values.

34
Example 13.8 Set Membership

List all Managers and Deputy Managers.

SELECT sno, fname, lname, position


FROM staff
WHERE position IN ('Manager', 'Deputy');

35
Example 13.8 Set Membership

36
Example 13.8 Set Membership

 There is a negated version (NOT IN).


 IN does not add much to SQL's expressive power.
 Could have expressed this as:

SELECT sno, fname, lname, position


FROM staff
WHERE position='Manager' OR position='Deputy';

37
Example 13.9 Pattern Matching

Find all staff with the string 'Glasgow' in their add


ress.

SELECT sno, fname, lname, address, salary


FROM staff
WHERE address LIKE '%Glasgow%';

38
Example 13.9 Pattern Matching

39
Example 13.9 Pattern Matching

 SQL has two special pattern matching symbols:


– %: sequence of zero or more characters;
– _ (underscore): any single character.
 LIKE '%Glasgow%' means a sequence of
characters of any length containing 'Glasgow'.

40
Example 13.10 NULL Search Condition

List details of all viewings on property PG4 where a comment


has not been supplied.
 There are 2 viewings for property PG4, one with and one with
out a comment.
 Have to test for null explicitly using special keyword IS NULL
:
SELECT rno, date
FROM viewing
WHERE pno = 'PG4' AND comment IS NULL;

41
Example 13.10 NULL Search Condition

 Negated version (IS NOT NULL) can test for non-null


values.

42
Example 13.11 Single Column Ordering

List salaries for all staff, arranged in descending o


rder of salary.

SELECT sno, fname, lname, salary


FROM staff
ORDER BY salary DESC;

43
Example 13.11 Single Column Ordering

44
Example 13.12 Multiple Column Ordering

Produce abbreviated list of properties in order of


property type.

SELECT pno, type, rooms, rent


FROM property_for_rent
ORDER BY type;

45
Example 13.12 Multiple Column Ordering

46
Example 13.12 Multiple Column Ordering

 Four flats in this list - as no minor sort key specifi


ed, system arranges these rows in any order it cho
oses.
 To arrange in order of rent, specify minor order:

SELECT pno, type, rooms, rent


FROM property_for_rent
ORDER BY type, rent DESC;

47
Example 13.12 Multiple Column Ordering

48
SELECT Statement - Aggregates
 ISO standard defines five aggregate functions:

COUNT returns number of values in a specified column.


SUM returns sum of values in a specified column.
AVG returns average of values in a specified column.
MIN returns smallest value in a specified column.
MAX returns largest value in a specified column.

49
SELECT Statement - Aggregates

 Each operates on a single column of a table and


return single value.
 COUNT, MIN, and MAX apply to numeric and
non-numeric fields, but SUM and AVG may be
used on numeric fields only.
 Apart from COUNT(*), each function eliminates
nulls first and operates only on remaining non-null
values.

50
SELECT Statement - Aggregates

 COUNT(*) counts all rows of a table, regardless of


whether nulls or duplicate values occur.
 Can use DISTINCT before column name to
eliminate duplicates.
 DISTINCT has no effect with MIN/MAX, but may
have with SUM/AVG.
 Aggregate functions can be used only in SELECT
clause and in HAVING clause.

51
Example 13.13 Use of COUNT(*)

How many properties cost more than 350 per


month to rent?
SELECT COUNT(*) AS count
FROM property_for_rent
WHERE rent > 350;

53
Example 13.14 Use of COUNT(DISTINCT)

How many different properties viewed in May ‘98?


SELECT COUNT(DISTINCT pno) AS count
FROM viewing
WHERE date BETWEEN DATE'1998-05-01’
AND DATE'1998-05-31';

54
Example 13.15 Use of COUNT and SUM

Find number of Managers and sum of their salaries.


SELECT COUNT(sno) AS count,
SUM(salary) AS sum
FROM staff
WHERE position = 'Manager';

55
Example 13.16 Use of MIN, MAX, AVG

Find minimum, maximum, and average staff salar


y.
SELECT MIN(salary) AS min,
MAX(salary) AS max,
AVG(salary) AS avg
FROM staff;

56
SELECT Statement - Grouping
 Use GROUP BY clause to get sub-totals.
 Each item in a result table must be single-valued per
group (see table 13.17 also).
 A SELECT clause may only contain:
– Column names.
– Aggregate functions.
– Constants.
– An expression involving combinations of the above.

57
SELECT Statement - Grouping

 All column names in SELECT clause must appear


in GROUP BY clause unless name is used only in
an aggregate function (See exam 13.17 also).
 If WHERE is used with GROUP BY, WHERE is
applied first, then groups are formed from
remaining rows satisfying condition.
 ISO considers two nulls to be equal for purposes
of GROUP BY.

58
Example 13.17 Use of GROUP BY

Find number of staff in each branch and their total


salaries.

SELECT bno, COUNT(sno) AS count,


SUM(salary) AS sum
FROM staff
GROUP BY bno
ORDER BY bno;

59
Example 13.17 Use of GROUP BY

60
Restricted Grouping

 HAVING clause is designed for use with GROUP


BY clause to restrict groups that appear in final
result table.
 Similar to WHERE, but WHERE filters
individual rows whereas HAVING filters groups.
 Column names in HAVING clause must also
appear in the GROUP BY clause or be contained
within an aggregate function.

61
Example 13.18 Use of HAVING

For each branch with more than 1 member of staff, find n


umber of staff in each branch and sum of their salaries.
SELECT bno, COUNT(sno) AS count,
SUM(salary) AS sum
FROM staff
GROUP BY bno
HAVING COUNT(sno) > 1
ORDER BY bno;

62
Example 13.18 Use of HAVING

63
Subqueries

 Some SQL statements can have a SELECT embed


ded within them.
 A subselect can be used in WHERE and HAVING
clauses of an outer SELECT, where it is called a su
bquery or nested query.
 Subselects may also appear in INSERT, UPDATE,
and DELETEs.

64
Example 13.19 Subquery with Equality

List staff who work in branch at '163 Main St'.

SELECT sno, fname, lname, position


FROM staff
WHERE bno =
(SELECT bno
FROM branch
WHERE street = '163 Main St');

65
Example 13.19 Subquery with Equality

 Inner SELECT finds branch number correspondi


ng to branch at '163 Main St' ('B3').
 Outer SELECT then retrieves details of all staff w
ho work at this branch.
 Outer SELECT then becomes:

SELECT sno, fname, lname, position


FROM staff
WHERE bno = 'B3';
66
Example 13.19 Subquery with Equality

67
Example 13.20 Subquery with Aggregate

List all staff whose salary is greater than the averag


e salary.

SELECT sno, fname, lname, position, salary


FROM staff
WHERE salary >
(SELECT AVG(salary)
FROM staff);

68
Example 13.20 Subquery with Aggregate

70
Subquery Rules

 ORDER BY clause may not be used in a subquery


(although it may be used in outermost SELECT).
 When subquery is an operand in a comparison, su
bquery must appear on right-hand side (See exam
13.20 also).

71
Example 13.21 Nested subquery: use of IN
List properties handled by staff at '163 Main St'.

SELECT pno, street, area, city, pcode, type, rooms, rent


FROM property_for_rent
WHERE sno IN
(SELECT sno
FROM staff
WHERE bno =
(SELECT bno
FROM branch
WHERE street = '163 Main St'));
73
Example 13.21 Nested subquery: use of IN

74
ANY and ALL
 ANY and ALL may be used with subqueries that pro
duce a single column of numbers. (numerical)

 If a subquery is preceded by ALL, condition will only


be true if it is satisfied by all values produced by the s
ubquery.

 If a subquery is preceded by ANY, condition will be tr


ue if it is satisfied by any values produced by the subq
uery.

75
ANY and ALL

 If subquery is empty, ALL returns true, ANY retu


rns false.

 ISO standard allows SOME to be used in place of


ANY.

76
Example 13.22 Use of ANY/SOME

Find staff whose salary is larger than salary of at least 1 m


ember of staff at branch B3.

SELECT sno, fname, lname, position, salary


FROM staff
WHERE salary > SOME
(SELECT salary
FROM staff
WHERE bno = 'B3');

77
Example 13.22 Use of ANY/SOME

 Inner query produces set {12000, 18000, 24000}


and outer query selects those staff whose salaries
are greater than any of the values in this set.

78
Example 13.23 Use of ALL

Find staff whose salary is larger than salary of every membe


r of staff at branch B3.

SELECT sno, fname, lname, position, salary


FROM staff
WHERE salary > ALL
(SELECT salary
FROM staff
WHERE bno = 'B3');

79
Example 13.23 Use of ALL

80
Multi-Table Queries

 In (sub)queries shown earlier, note that all 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).

81
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


(See exam 13.24 also).

 Alias can be used to qualify column names when


there is ambiguity.

82
Example 13.24 Simple Join

List names of all renters who have viewed a prope


rty along with any comment supplied.

SELECT r.rno, fname, lname, pno, comment


FROM renter r, viewing v
WHERE r.rno = v.rno;

83
Example 13.24 Simple Join

 To obtain correct rows, include only those rows fr


om both tables that have identical values in the Rn
o columns: r.rno = v.rno. (See Renter and Viewing
Tables)

 These two columns are the matching columns for t


wo tables.

 Equivalent to equi-join in relational algebra.

84
Example 13.24 Simple Join

85
Alternative JOIN Constructs
 SQL2 provides alternative ways to specify joins:

FROM renter r JOIN viewing v ON r.rno=v.rno (equi)


FROM renter JOIN viewing USING rno (natural)
FROM renter NATURAL JOIN viewing (natural)

 In each case, FROM replaces original FROM and WHERE.


However, first produces table with two identical Rno colum
ns, remaining two produce table with single Rno column.

86
Example 13.25 Sorting a join

For each branch, list names of staff who manage p


roperties.

SELECT s.bno, s.sno, fname, lname, pno


FROM staff s, property_for_rent p
WHERE s.sno = p.sno
ORDER BY s.bno, s.sno, pno;

87
Example 13.25 Sorting a join

88
Example 13.26 Three Table Join

For each branch, list staff who manage properties,


including city in which branch is located and prop
erties they manage.

SELECT b.bno, b.city, s.sno, fname, lname, pno


FROM branch b, staff s, property_for_rent p
WHERE b.bno = s.bno AND s.sno = p.sno
ORDER BY b.bno, s.sno, pno;

89
Example 13.26 Three Table Join

90
Example 13.26 Three Table Join

 SQL2 provides alternative formulations for FRO


M and WHERE:

FROM (branch b JOIN staff s USING bno) AS


bs JOIN property_for_rent p USING sno

91
Example 13.27 Multiple Grouping Columns

Find number of properties handled by each staff memb


er in each branch.

SELECT s.bno, s.sno, COUNT(*) AS count


FROM staff s, property_for_rent p
WHERE s.sno = p.sno
GROUP BY s.bno, s.sno
ORDER BY s.bno, s.sno;

92
Example 13.27 Multiple Grouping Columns

93
Outer Joins
 With a join, if one row of a table is unmatched, that r
ow is omitted from result table.
 The outer join operations retain rows that do not sati
sfy the join condition.
 Consider following two simplified tables:
BRANCH1 PROPERTY_FOR_RENT1
bnocity pno pcity
B3 Glasgow PA14 Aberdeen
B4 Bristol PL94 London
B2 London PG4 Glasgow

97
Outer Joins
 The (inner) join of these two tables:

SELECT b.*, p.*


FROM branch1 b, property_for_rent1 p
WHERE b.bcity = p.pcity;

98
Outer Joins

 Result table has two rows where the cities are the
same.
 There are no rows corresponding to branches in
Bristol and Aberdeen.
 To include unmatched rows in result table, use an
outer join.

99
Example 13.28 Left Outer Join

List branches and properties that are in same city


along with any unmatched branches.

SELECT b.*, p.*


FROM branch1 b LEFT JOIN
property_for_rent1 p ON b.bcity = p.pcity;

100
Example 13.28 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.

101
Example 13.29 Right Outer Join

List branches and properties in same city and any


unmatched properties.

SELECT b.*, p.*


FROM branch1 b RIGHT JOIN
property_for_rent1 p ON b.bcity = p.pcity;

102
Example 13.29 Right Outer Join
 Right outer join includes those rows of second (rig
ht) table that are unmatched with rows from first (
left) table.
 Columns from first table are filled with NULLs.

103
Example 13.30 Full Outer Join

List branches and properties in same city and any


unmatched branches or properties.

SELECT b.*, p.*


FROM branch1 b FULL JOIN
property_for_rent1 p ON b.bcity = p.pcity;

104
Example 13.30 Full Outer Join

 Includes those rows that are unmatched in both ta


bles.
 Unmatched columns are filled with NULLs.

105
EXISTS and NOT EXISTS

 EXISTS and NOT EXISTS are for use only with s


ubqueries.
 They produce a simple true/false result.
 EXISTS is true if and only if there exists at least o
ne row in result table returned by subquery.
 It is false if subquery returns an empty result table
.
 NOT EXISTS is the opposite of EXISTS.

106
EXISTS and NOT EXISTS

 Since EXISTS and NOT EXISTS check only for ex


istence or non-existence of rows in subquery result
table, subquery can contain any number of column
s.
 Subqueries following (NOT) EXISTS are of the for
m:
(NOT) EXISTS (SELECT * ...)

107
Example 13.31 Query using EXISTS

 Find all staff who work in a London branch.

SELECT sno, fname, lname, position


FROM staff s
WHERE EXISTS
(SELECT *
FROM branch b
WHERE s.bno = b.bno AND city = 'London');

108
Example 13.31 Query using EXISTS

109
Example 13.31 Query using EXISTS

 Could also have written this query using join const


ruct:

SELECT sno, fname, lname, position


FROM staff s, branch b
WHERE s.bno = b.bno AND city = 'London';

111
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.

112
Union, Intersect, and Difference (Except)

 Format of set operator clause in each case is:

op [ALL] [CORRESPONDING [BY { column1 [, ...] } ] ]

 If CORRESPONDING BY specified, set operation


performed on the named column(s).
 If CORRESPONDING specified but not BY
clause, operation performed on common columns.
 If ALL specified, result can include duplicate rows.

113
Union, Intersect, and Difference (Except)

114
Example 13.32 Use of UNION

List all areas where there is either a branch or rental


property.

(SELECT area
FROM branch
WHERE area IS NOT NULL) UNION
(SELECT area
FROM property_for_rent
WHERE area IS NOT NULL);

115
Example 13.32 Use of UNION

– Or

(SELECT *
FROM branch
WHERE area IS NOT NULL)
UNION CORRESPONDING BY area
(SELECT *
FROM property_for_rent
WHERE area IS NOT NULL);

116
Example 13.32 Use of UNION
 Produces result tables from both queries and
merges both tables together.

117
Example 13.33 Use of INTERSECT

List all cities where there is both a branch and


rental property.

(SELECT city FROM branch)


INTERSECT
(SELECT city FROM property_for_rent);

118
Example 13.33 Use of INTERSECT

 Or

(SELECT * FROM branch)


INTERSECT CORRESPONDING BY city
(SELECT * FROM property_for_rent);

119
Example 13.33 Use of INTERSECT
 Produces result tables from both queries and
creates single result table consisting of those rows
that are common to both result tables.

120
Example 13.33 Use of INTERSECT

 Could rewrite this query without INTERSECT


operator:

SELECT city
FROM branch b property_for_rent p
WHERE b.city = p.city;

121
Example 13.33 Use of INTERSECT
 Or

SELECT distinct city


FROM branch b
WHERE EXISTS
(SELECT *
FROM property_for_rent p
WHERE p.city = b.city);
 Ability to write a query in several equivalent forms is
one of the (dis)advantages of SQL.
122
Example 13.34 Use of EXCEPT

List of all cities where there is a branch but no


rental properties.

(SELECT city FROM branch)


EXCEPT
(SELECT city FROM property_for_rent);

123
Example 13.34 Use of EXCEPT

 Or

(SELECT * FROM branch)


EXCEPT CORRESPONDING BY city
(SELECT * FROM property_for_rent);

124
Example 13.34 Use of EXCEPT
 Produces result tables from both queries and then
creates single result table consisting of those rows
appearing in first result table but not in second.

125
Example 13.34 Use of EXCEPT

 Could rewrite this query without EXCEPT:

SELECT distinct city


FROM branch
WHERE city NOT IN
(SELECT city
FROM property_for_rent);

126
Example 13.34 Use of EXCEPT

 Or

SELECT distinct city


FROM branch b
WHERE NOT EXISTS
(SELECT *
FROM property_for_rent p
WHERE p.city = b.city);

127
INSERT

INSERT INTO table_name [ (column_list) ]


VALUES (data_value_list)

 column_list is optional.
 If omitted, SQL assumes a list of all columns in
their original CREATE TABLE order.

128
INSERT

 data_value_list must match column_list as follows:


 Number of items in each list must be the same.
 Must be direct correspondence in position of items
in two lists.
 Data type of each item in data_value_list must be
compatible with data type of corresponding
column.

129
Example 13.35 INSERT … VALUES

Insert a new record into Staff table supplying data for a


ll columns.

INSERT INTO staff


VALUES ('SG16', 'Alan', 'Brown',
'67 Endrick Rd, Glasgow G32 8QX',
'0141-211-3001', 'Assistant', 'M', '25-May-57',
8300, 'WN848391H', 'B3');

130
Example 13.36 INSERT using Defaults

Insert a new record into Staff table supplying data


for all mandatory columns.
INSERT INTO staff (sno, fname, lname, position,
salary, bno)
VALUES ('SG44', 'Anne', 'Jones', 'Assistant',
8100, 'B3');

131
Example 13.36 INSERT using Defaults

 Or

INSERT INTO staff


VALUES ('SG44', 'Anne', 'Jones', NULL, NULL,
'Assistant', NULL, NULL, 8100, NULL, 'B3');

132
INSERT … SELECT

 Second form of INSERT allows multiple rows to


be copied from one or more tables to another:

INSERT INTO table_name [ (column_list) ]


SELECT ...

133
Example 13.37 INSERT … SELECT

Assume there is a table Staff_Prop_Count that contains


names of staff and the number of properties they mana
ge:

Staff_Prop_Count(sno, fname, lname, prop_cnt)

Populate Staff_Prop_Count using Staff and Property_f


or_Rent.

134
Example 13.37 INSERT … SELECT

INSERT INTO staff_prop_count


(SELECT s.sno, fname, lname, COUNT(*)
FROM staff s, property_for_rent p
WHERE s.sno = p.sno (staff with some properties)
GROUP BY s.sno, fname, lname)
UNION
(SELECT sno, fname, lname, 0
FROM staff
WHERE sno NOT IN (staff with no property)
(SELECT DISTINCT sno
FROM property_for_rent));
135
Example 13.37 INSERT … SELECT

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


currently do not manage any properties.

136
UPDATE

UPDATE table_name
SET column_name1 = data_value1
[, column_name2 = data_value2...]
[WHERE search_condition]
 table_name can be name of a base table or an upda
table view.
 SET clause specifies names of one or more columns
that are to be updated.

137
UPDATE

 WHERE clause is optional:


– If omitted, named columns are updated for all
rows in table.
– If specified, only those rows that satisfy
search_condition are updated.
 New data_value(s) must be compatible with data
type for corresponding column.

138
Example 13.38 UPDATE All Rows

Give all staff a 3% pay increase.

UPDATE staff
SET salary = salary*1.03;

139
Example 13.39 UPDATE Specific Rows

Give all Managers a 5% pay increase.

UPDATE staff
SET salary = salary*1.05
WHERE position = 'Manager';

 WHERE clause finds rows that contain data for


Managers. Update is applied only to these
particular rows.

140
Example 13.40 UPDATE Multiple Columns

Promote David Ford (sno = 'SG14') to Manager a


nd change his salary to 18,000.

UPDATE staff
SET position = 'Manager', salary = 18000
WHERE sno = 'SG14';

141
DELETE

DELETE FROM table_name


[WHERE search_condition]
 table_name can be name of a base table or an upda
table view.
 search_condition is optional; if omitted, all rows ar
e deleted from table. This does not delete table. If s
earch_condition is specified, only those rows that sa
tisfy condition are deleted.

142
Example 13.41 DELETE Specific Rows

Delete all viewings that relate to property PG4.

DELETE FROM viewing


WHERE pno = 'PG4';

143
Example 13.42 DELETE All Rows

Delete all records from the Viewing table.

DELETE FROM viewing;

144
ISO SQL Data Types

145
Data Definition

 In SQL92, relations and other database objects


exist in an environment.
 Each environment contains one or more catalogs,
and each catalog consists of set of schemas.
 Schema is a named collection of related database
objects (tables, views, domains, and assertions).

146
Data Definition

CREATE SCHEMA [name |


AUTHORIZATION creator_id ]
DROP SCHEMA name [RESTRICT | CASCADE ]
 With RESTRICT (default), schema must be empty
or operation fails.
 With CASCADE, operation cascades to drop all
objects associated with schema. If any of these
operations fail, DROP SCHEMA fails.

147
CREATE TABLE (Basic)

CREATE TABLE table_name


(col_name data_type [NULL | NOT NULL] [,...])

 Creates a table with one or more columns of the specif


ied data_type.
 NULL (default) indicates whether column can contain
nulls.
 With NOT NULL, system rejects any attempt to inser
t a null in the column.

148
CREATE TABLE (Basic)

 Primary keys should always be specified as NOT


NULL.
 Foreign keys are often (but not always)
candidates for NOT NULL.

149
Example 13.43 CREATE TABLE
CREATE TABLE staff(
sno VARCHAR(5) NOT NULL,
fname VARCHAR(15)NOT NULL,
lname VARCHAR(15) NOT NULL,
address VARCHAR(50),
tel_no VARCHAR(13),
position VARCHAR(10) NOT NULL,
sex CHAR,
dob DATETIME,
salary DECIMAL(7,2) NOT NULL,
nin CHAR(9),
bno VARCHAR(3) NOT NULL);

150
Example 13.43 CREATE TABLE
CREATE TABLE property_for_rent(
pno VARCHAR(5) NOT NULL,
street VARCHAR(25)NOT NULL,
area VARCHAR(15),
city VARCHAR(15) NOT NULL,
pcode VARCHAR(8),
type CHAR(1) NOT NULL,
rooms SMALLINT NOT NULL,
rent DECIMAL(6,2) NOT NULL,
ono VARCHAR(5) NOT NULL,
sno VARCHAR(5),
bno VARCHAR(3) NOT NULL);

151
DROP TABLE

DROP TABLE tbl_name [RESTRICT | CASCADE]

e.g. DROP TABLE property_for_rent;

 Removes named table and all rows within it.


 With RESTRICT, if any other objects depend for their ex
istence on continued existence of this table, SQL does not
allow request.
 With CASCADE, SQL drops all dependent objects (and o
bjects dependent on these objects).

152

You might also like