Sei sulla pagina 1di 199

-4The Structured Query Language

SQL

SQL What is it ?

A powerful,
set oriented,
non-procedural
Non-proprietary
Language created to perform tasks such as update or
retrieve data from relational databases
First introduced by IBM in mid 70s
First commercial version by Oracle corporation in 79,
followed by IBM in 80
Available on ALL platforms from PC to mainframes
CS 53
Ramasesha Mudigere
. Contd. 2

SQL is ..
1. An interactive query language for ad-hoc queries
2. A database programming language
3. A combo of data definition, manipulation &
administration commands
4. Provides features, for data validation and transaction
support in a multi-user environment
5. Most appropriate language for networked database
servers
6. The flexible language that can be used for any data
storage and access
CS 53

Ramasesha Mudigere

SQL is ..
1. An interactive query language for ad-hoc queries
A
T
2. A database programming language e
A
h
D
t
f
r
o
3. A combo of data definition, manipulation
&l
o
f
o

r
t
administration commands nca
n
o
c
a
r
f
d and transaction
n
4. Provides features, for
data
validation
a
a
u
g
n
n
o
support in a multi
li -usernenvironment
ti
i

i
e
f
h
e
5. Most appropriate
language
for
networked
database
T
d
,
n
o
servers
i
t
a
l
u
p
6. The flexible
i language that can be used for any data
n
a
m and access
storage
CS 53

Ramasesha Mudigere

History Of SQL
In 1974, D. Chamberlin (IBM San Jose Laboratory)
defined language called Structured English Query
Language (SEQUEL)
A revised version, SEQUEL/2, was defined in 1976 but
name was subsequently changed to SQL for legal
reasons
IBM subsequently produced a prototype DBMS called
System R, based on SEQUEL/2
In late 70s, ORACLE appeared and was probably first
commercial RDBMS based on SQL
CS 53

Ramasesha Mudigere

SQL Standards

SQL-86 (A.k.a. SQL1)

issued by ANSI and ISO in 1986

SQL-89 - Minor revision like


intersection of SQL implementations of that time; (SQL
compliance was very easy for most)
Referential integrity
Bindings to standard programming languages

SQL-92 ( A.k.a. SQL2) -- Ratified in late 1992


Full-function RDBMS

Defines three levels of compliance - Entry, Intermediate, &


Full
The most widely used version in vogue even today
CS 53

Ramasesha Mudigere

. Contd.6

SQL Standards
SQL 1999 ( A.k.a. SQL3)

The current version of SQL standards


Over 5 times the size of SQL-92
Included OO features and stored procedures
Most DBMSs conform .. but some features are still not
implemented by some vendors.

SQL 2003 ( A.k.a. SQL4)


Proposed new Standard
XML Extensions and
SQL-1999 bug fixes
CS 53

Ramasesha Mudigere

SQL Standards

s s.
u
l
p
e
r
,
SQL 1999 ( A.k.a. SQL3)
u
s at
e
r
u y fe
t
a
The current version of SQL standards
e tar
f
2 ri e
9
p
Over 5 times the size of SQL-92
L
o
r
Q lp
S
ll , ci a
Included OO features and stored
procedures
a
t spe
o
n
f
i
&features are still not
Most DBMSs conform .. but
some
,
t
s
s ard
o
implemented by some
mvendors.
d
r
n
e sta
f
f
oSQL4)
r
SQL 2003 ( A.k.a.
s
e
t
m
a
l
e
t
s
m
y
Proposed
new
Standard
o
s
r
f
l
a
s
i
t
c
e
r
XML
Extensions
and
s
e
e
m tur
m
a
-1999 bug fixes
e
Co SQL
f
g
n
i
y
r
CS v53
Ramasesha Mudigere
8
a

SQL
Today,
300+ vendors of SQL products on various platforms
like
DB2, Oracle, Sybase, Informix, Microsoft SQL Server,
MSAccess, Ingress, MYSQL etc..
Most of them also have their own additional proprietary
extensions that are usually only used on their system
Has gone ( rather going ) through several revisions and
standardizations by ANSI
CS 53

Ramasesha Mudigere

SQL Commands
Can be Grouped as:
1. DML Component ) To manipulate data in the Tables
2. DDL Component ) To Add / Change / Delete Tables
3. Admin. Component ) To Control & manage access
permissions
4. Programming Component ) To access Database
in procedural way
5. Transaction Support ) To run transactions in a
multi-user environment
CS 53

Ramasesha Mudigere

10

1. SQL DML Component


Comprises FOUR (4 ) basic statements:
1. SELECT

To retrieve rows from tables

2. UPDATE

To modify the rows of tables

3. INSERT

To add new rows to tables

4. DELETE

CS 53

To remove rows from tables.


Ramasesha Mudigere

11

2. SQL DDL Component


Comprises THREE (3) basic statements:
1. CREATE
To create new table specification

2. DROP
To delete the tables

3. ALTER
To add or delete columns from a table, and
To change the specification on an existing
column
CS 53

Ramasesha Mudigere

12

3. SQL Admin Component


Comprises FOUR (4) basic statements:
1. CREATE
To create new users to access database

2. DROP
To delete the users

3. GRANT
To provide specific access permissions to users

4. REVOKE
To withdraw access permissions from users
CS 53

Ramasesha Mudigere

13

4. SQL Programming Component


Comprises FOUR (4) basic statements:
1. DECLARE
To define CURSORS to access database

2. OPEN
To enable / activate CURSORS

3. FETCH
To get data rows based on CURSOR

4. CLOSE
To disable /deactivate the cursor
CS 53

Ramasesha Mudigere

14

5. SQL Transaction Component


Comprises FOUR (4) basic statements:
1. BEGIN
To start a new transaction

2. COMMIT
To make the changes done by a a transaction
permanent

3. ROLLBACK
To undo the changes done by a transaction

4. SAVEPOINT
To create an intermediary commit point
CS 53

Ramasesha Mudigere

15

SQL Statements A Summary


DML

DDL

ADMIN
Support

SELECT

CREATE

CREATE

PGM
Support

TXN
Support

DECLARE

BEGIN

OPEN

UPDATE

DROP

DROP

INSERT

ALTER

GRANT

FETCH

ROLLBACK

REVOKE

CLOSE

SAVEPOINT

DELETE
CS 53

Ramasesha Mudigere

COMMIT

16

SQL Statements Coding Format


SQL is not Case Sensitive.
Exception:
Character values within quotation marks (Use the correct
case for these values.)
Example:
adams will not match with the stored value is Adams

Tabs and Indentations will promote readability.


Keywords cannot be split or abbreviated.
SQL Statements can be split across lines.
Clauses are placed in different lines, to promote
readability.

CS 53

Ramasesha Mudigere

17

1. SQL DML Component


Comprises FOUR (4 ) basic statements:
1. SELECT

To retrieve rows from tables

2. UPDATE

To modify the rows of tables

3. INSERT

To add new rows to tables

4. DELETE

CS 53

To remove rows from tables.


Ramasesha Mudigere

18

SELECT
The most common and most used verb in SQL
The one ( and only one) basic command used to
retrieve data from column (s) of Table (s)
NOT to be confused with the SELECT operation of
Relational Algebra
So many options and flavor are available making it one
of the most versatile and powerful commands
Can vary from very simple to most Complex command
depending on options and parameters used
CS 53

Ramasesha Mudigere

19

An SQL SELECT Query


Has up to six clauses specified in the following order :
SELECT [ DISTINCT | ALL ] < attribute list >
FROM

< table list [alias] [, ...] >

[ WHERE

< condition > ]

[ GROUP BY

< grouping attribute(s) > ]

[ HAVING

< group condition > ]

[ ORDER BY

< attribute list> ]

Only the first two, SELECT and FROM, are mandatory


CS 53

Ramasesha Mudigere

20

Clauses of SELECT Statement


SELECT ) To List the columns (and expressions) that
should be returned from the query
FROM ) To Indicate the table(s) or view(s) from
which data will be obtained
WHERE ) To Indicate the conditions under which a
row will be included in the result
GROUP BY ) To Indicate categorization of results
HAVING ) To Indicate the conditions under which a
category (group) will be included
ORDER BY ) To Sort the result according to specified
criteria
CS 53
Ramasesha Mudigere
21

SQL statement
processing order

CS 53

Ramasesha Mudigere

22

SQL statement
processing order

CS 53

Ramasesha Mudigere

23

Simple SELECT command


1.

2.

3.

4.

SELECT * FROM EMPLOYEE


Lists all columns from table Employee with column name
( underlined ) as heading ;The output format looks something
like this
*
SELECT BDATE, ADDRESS FROM EMPLOYEE
Lists columns BDATE & ADDRESS for all Employees
SELECT DNO FROM EMPLOYEE
Lists dept number column from EMPLOYEE Table
SELECT DISTINCT DNO FROM EMPLOYEE

Lists only unique DNO ( 5, 4 and 1)


5.
CS 53

SELECT ALL DNO FROM EMPLOYEE


N

Ramasesha Mudigere

O/P Same As Q3
24

Simple SELECT with computed fields


Computed columns
Data that do not exist in the database Can be computed
using data in existing columns & arithmetic operators
SELECT SSN, LNAME, SALARY *12 FROM EMPLOYEE
Lists SSN, LNAME and SALARY *12 ( A computed figure ) for
all rows under the heading :
SSN
NAME
_SALARY * 12

CS 53

Ramasesha Mudigere

25

Simple SELECT with AS Clause


AS clause is used to name the column differently in the
output ( Not in the database )
AS clause is optional
SELECT SSN, LNAME AS NAME, SALARY *12 AS
ANNUAL_SALARY FROM EMPLOYEE

OR

SELECT SSN, LNAME NAME, SALARY *12


ANNUAL_SALARY FROM EMPLOYEE
Lists SSN, LNAME and SALARY *12 ( A computed figure ) for
all rows under the heading :
SSN
CS 53

NAME
Ramasesha Mudigere

ANNUAL_SALARY

26

CS 53

Ramasesha Mudigere

27

CS 53

Ramasesha Mudigere

B
28

SELECT Statement with WHERE Clause


SELECT FNAME , LNAME, SALARY FROM
EMPLOYEE WHERE DNO = 4
Lists the FNAME LNAME and SALARY from rows where

DNO = 4 ( 3 rows )
Comparison operators allowed are:

CS 53

Ramasesha Mudigere

29

SELECT Statement with compound Condition


Compound conditions
Formed by connecting two or more simple conditions
Uses AND, OR, and NOT operators
1. AND: all conditions must be true
2. OR: any one of conditions is true
3. NOT: reverses the truth of the original condition

The WHERE clause in SQL can include


compound Conditions to fine tune the selection
CS 53

Ramasesha Mudigere

30

SELECT Statement with compound


Condition

CS 53

Ramasesha Mudigere

31

SELECT Statement with compound


Condition

CS 53

Ramasesha Mudigere

32

Range Search Condition


1. BETWEEN operator
Used to search for a range of values
Inclusive values defining range are included
( BETWEEN 10 AND 20 will return 10 and 20 if available. )
Not an essential feature
Can arrive at same answer without it using AND
Does make certain SELECT commands simpler
Can be negated using NOT BETWEEN
CS 53

Ramasesha Mudigere

33

Range Search Condition - Example

CS 53

Ramasesha Mudigere

34

Pattern Matching Condition


LIKE operator
used when exact matches will not work
Can be used with a wildcard symbol
Can be negated using NOT LIKE

Wildcards vary depending on DBMS


% Matches one or more characters
_ Matches any one character
Can be used together and repeatedly
CS 53

Ramasesha Mudigere

35

Pattern Matching Condition


ENAME
SQL> SELECT ename
------2 FROM emp
JAMES
3 WHERE ename LIKE _A%; WARD

CS 53

Ramasesha Mudigere

36

Set Membership Condition


Use of IN
Provides concise way of phrasing certain conditions
Used to search for groups of values ( Replaces = )
List of values are in ( ) and comma separated
Advanced Advantage Can contain list of values from
another query
Can be negated by using NOT IN

List the customer number, last name, and first name


for every customer with a credit limit of $1,000, $1,500,
or $2,000
CS 53

Ramasesha Mudigere

37

Set Membership Condition


Use of IN

CS 53

Ramasesha Mudigere

38

ORDER BY Clause
Generally, the order of rows is immaterial to the DBMS
Results when displayed are in no defined order
Rows can displayed in the order in which they were
entered

However:
ORDER BY clause lists data in a specific order
Last part of SQL statement that controls order of records
returned
ASC Ascending Order (Default order )
DESC Descending Order
CS 53

Ramasesha Mudigere

39

ORDER BY Example

CS 53

Ramasesha Mudigere

40

ORDER BY Example
SQL> SELECT ename, job, deptno, hiredate
2 FROM
emp
3 ORDER BY hiredate DESC;
ENAME
JOB
DEPTNO
---------- --------- --------ADAMS
CLERK
20
SCOTT
ANALYST
20
MILLER
CLERK
10
JAMES
CLERK
30
FORD
ANALYST
20
KING
PRESIDENT
10
MARTIN
SALESMAN
30
...
1453 rows selected.
CS
Ramasesha Mudigere

HIREDATE
--------12-JAN-83
09-DEC-82
23-JAN-82
03-DEC-81
03-DEC-81
17-NOV-81
28-SEP-81
41

ORDER BY using multiple keys


When sorting more than one column
the more important column is called the major key
(or primary sort key)
the less important column is called the minor key
(or secondary sort key)

List keys in the order of importance in the ORDER BY


clause
CS 53

Ramasesha Mudigere

42

ORDER BY with multiple keys

CS 53

Ramasesha Mudigere

43

Handling NULL Values

signifies an unknown value or a value that does not exist.


Any arithmetic operation with NULL results in NULL
NULL values sometimes produce unexpected results
NULLS require special handling when coding
Use the SQL Operator IS NULL to test for NULL values
SQL> SELECT
2 FROM
3 WHERE

CS 53

ENAME
-------KING

ename, mgr
emp
mgr IS NULL;
MGR
---------

Ramasesha Mudigere

44

Aggregate operators in SQL


Also referred to as Group Functions
ISO standard defines five aggregate functions:
1. COUNT returns number of values in specified column
2. SUM

returns sum of values in specified column.

3. AVG

returns average of values in specified column.

4. MIN

returns smallest value in specified column.

5. MAX
returns largest value in specified column
All operators (Except count) used only on numeric data
ignoring NULL values, if any, are encountered

CS 53

Ramasesha Mudigere

45

COUNT

Returns the number of non-null occurrences of a column


Use of asterisk * Counts the rows
Use DISTICNCT to count duplicate values only once

SELECT COUNT(PART_NUMBER) FROM PART


WHERE ITEM_CLASS = HW;

CS 53

Ramasesha Mudigere

46

SUM, AVG, MAX and MIN


Work only on numeric fields
DISTICT can be used with SUM and AVG
Ignore null values ( But sometimes strange results are obtained)

CS 53

Ramasesha Mudigere

47

Summary of Group Functions

All of them Except count, operate on numeric fields only


COUNT alone
Can work on non-numeric as well as numeric fields
Can also use * as parameter to count number of rows

Null values are ignored during computation;


However strange results may occur sometimes with COUNT

Can be used in any combination


BUT
Can not be used together with direct column references
in the SELECT list (unless the SELECT statement
includes a GROUP BY clause)
CS 53

Ramasesha Mudigere

48

GROUP BY Clause
Intimately connected with Aggregates
Allows data to be:

grouped in a particular order and

compute statistics (aggregate functions) on these groups

that share some common characteristics


When used, the SELECT list must can contain
1. List of column names ( these names must appear in
GROUP BY Clause too) and
2. List of terms with aggregate operation
CS 53

Ramasesha Mudigere

49

GROUP BY Example
Consider the Table

CS 53

Find highest salary


Find highest salary in DepartmentNo = 5
Find DNO, and highest salary in each DNO

Ramasesha Mudigere

50

GROUP BY Example
SELECT DNO, MAX (SALARY) FROM EMPLYEE
GROUP BY DNO ORDER BY DNO
DNO
1
4
5

MAX (SALARY)
5500
4300
4000

If we need Max salary in each dept amongst female


employees only ?
SELECT DNO, MAX (SALARY) FROM EMPLYEE WHERE
SEX = F GROUP BY DNO ORDER BY DNO
CS 53

Ramasesha Mudigere

51

GROUP BY Another Example

CS 53

Ramasesha Mudigere

52

HAVING Clause
Designed for use with GROUP BY
Restricts 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 list or be contained within an aggregate function

CS 53

Ramasesha Mudigere

53

HAVING Clause Another Example

CS 53

Ramasesha Mudigere

54

Clauses of SELECT Statement (Revisited)


SELECT ) To List the columns (and expressions) that
should be returned from the query
FROM ) To Indicate the table(s) or view(s) from
which data will be obtained
WHERE ) To Indicate the conditions under which a
row will be included in the result
GROUP BY ) To Indicate categorization of results
HAVING ) To Indicate the conditions under which a
category (group) will be included
ORDER BY ) To Sort the result according to specified
criteria
CS 53
Ramasesha Mudigere
55

Sub Query ( A. k. a. Nested Query)


Query within a Query
( SELECT embedded within another SELECT )
Can be used in WHERE and HAVING clauses of an
outer SELECT, where it is called a subquery or nested
query.
May also appear in INSERT, UPDATE, and DELETE
statements
OUTER Query
SELECT . FROM .
WHERE . ( SELECT .. FROM . WHERE ..)
CS 53

INNER
Ramasesha Mudigere

Query

56

Sub Query Example


Consider the Employee Table
List LNAME with salary higher than salary of Narayan
We need two Queries
SELECT SALARY FROM EMPLOYEE WHERE LNAME = Narayan
SALARY
3800
SELECT LNAME FROM EMPLOYEE WHERE SALARY > 3800

Instead we can Write a single nested query :


SELECT LNAME FROM EMPLOYEE WHERE SALARY > ( SELECT
SALARY FROM EMPLOYEE WHERE LANME = Narayan )
CS 53

Ramasesha Mudigere

57

EMPLOYEE TABLE

CS 53

Ramasesha Mudigere

58

Nested Query Further Example


Suppose we want to check Narayans salary is above
average in his company by finding names with salary
higher than the average salary of the company ?
SELECT LNAME FROM EMPLOYEE WHERE SALARY > ( SELECT
AVG (SALARY) FROM EMPLOYEE)

Suppose we want to check Narayans salary is above


average in his Department alone
SELECT LNAME FROM EMPLOYEE WHERE SALARY > ( SELECT
AVG (SALARY) FROM EMPLOYEE WHERE DNO = ( SELECT
DNO FROM EMPLOYEE WHERE LANME = Narayan )
CS 53

Ramasesha Mudigere

59

Nested Query More Examples


List the amount by which colleagues salaries higher
than that of Narayan
SELECT ( SALARY ( SELECT SALARY FROM EMPLOYEE
WHERE LANME = Narayan )) AS SALDIFF
FROM EMPLOYEE
WHERE SALARY > ( SELECT SALARY FROM EMPLOYEE
WHERE LANME = Narayan )
CS 53

Ramasesha Mudigere

60

Nested Query More Examples


List the Average of Excess salary of all those employees
who draw salary higher than the average salary of
Narayans department
SELECT AVG ( SALARY ( SELECT SALARY FROM EMPLOYEE
WHERE LANME = Narayan )) AS AVGEXCESS
FROM EMPLOYEE
WHERE SALARY > ( SELECT AVG (SALARY) FROM
EMPLOYEE WHERE DNO = ( SELECT DNO FROM
EMPLOYEE WHERE LANME = Narayan )

Sub-query returned single value output so far; How about


CS muti
53 -value return ?Ramasesha Mudigere
61

USE of IN in Nested Queries


Used to check the existence of a variable in outer query,
when inner query returns a set not a single value
Consider the Table Employee
List Name and salaries of all who work in Departments
with least one female employee
SELECT LNAME, SALARY FROM EMPLOYEE
WHERE DNO IN ( SELECT DISTINCT DNO FROM EMPLOYEE
WHERE SEX = F )

Inner Query Returns a set of DNO {4,5}


Outer query checks + condition for each member of set
CS 53

Ramasesha Mudigere

62

EMPLOYEE TABLE

CS 53

Ramasesha Mudigere

63

USE OF ANY & ALL


May be used with sub-queries that produce a single
column of numbers
With ALL, condition will only be true if it is satisfied by
all values produced by sub-query.
With ANY, condition will be true if it is satisfied by any
values produced by sub-query.
If subquery is empty, ALL returns true, ANY returns
false.
SOME may be used in place of ANY.

CS 53

Ramasesha Mudigere

64

ANY & ALL Example


Consider the Employee Table
List names of all employees whose salary is equal to
salary of any one who woks in dept 4
SELECT LNAME FROM EMPLOYEE WHERE SALARY = ANY
( SELECT DISTINCT SALARY FROM EMPLOYEE
WHERE DNO = 4 )

List names of all employees in other departments


whose salary is equal to salary of any one who woks
in dept 4
SELECT LNAME FROM EMPLOYEE WHERE Dno NOT = 4
AND SALARY = ANY ( SELECT DISTINCT SALARY FROM
EMPLOYEE WHERE DNO = 4 )
CS 53

Ramasesha Mudigere

65

EMPLOYEE TABLE

CS 53

Ramasesha Mudigere

66

Use OF EXISTS & NOT EXISTS


EXISTS and NOT EXISTS are for use only with
subqueries.
Produce a simple true/false result.
True if and only if there exists at least one row in result
table returned by subquery.
False if subquery returns an empty result table.
NOT EXISTS is the opposite of EXISTS.
CS 53

Ramasesha Mudigere

67

EXISTS Example
Consider Employee table
List all Names & department where at least one female
employee is working
SELECT LNAME, DNO FROM EMPLOYEE E
WHERE EXISTS ( SELECT * FROM EMPLOYEE M
WHERE E.DNO = M.DNO
= F )
AND M.SEX
M.

Note the use of variable from outer query in inner


query ( known as Correlated Query)
CS 53

Ramasesha Mudigere

68

SELECT With Multiple Tables


Used to retrieve data from two or more tables
Operation performed will be Joining of the tables
Since there is a possibility of referring to the same
column name in two different fields, the column names
need to be qualified with Table name as
Table name . Column name OR
as Table alias name . Column name
SELECT select_list
FROM table_1 AS T1, table_2 (,table_3)
WHERE T1. column join_operator table2. column
CS 53

Ramasesha Mudigere

69

SELECT with JOIN


Indicate in the SELECT clause all columns to display
List in the FROM clause all tables involved in the query
Give condition(s) in the WHERE clause to restrict the
data to be retrieved to only those rows that have
common values in matching columns
Use Alias , wherever it is necessary, to make the
reference unique
CS 53

Ramasesha Mudigere

70

How JOIN works in SQL


Form Cartesian product of the tables named in FROM
clause.
If there is a WHERE clause, apply the search condition to
each row of the product table, retaining those rows that
satisfy the condition.
For each remaining row, determine value of each item in
SELECT list to produce a single row in result table.
If DISTINCT has been specified, eliminate any duplicate
rows from the result table.
If there is an ORDER BY clause, sort result table as
required.
CS 53

Ramasesha Mudigere

71

Simple JOIN Example


Consider tables: Client & Viewing:
ID
CR76
CR56
CR74
CR62
ID
CR56
CR76
CR56
CSCR74
53

Name
Suresh
Sheela
Milind
Rajani

Phone
4563
7749
2275
9341

Pref
House
Flat
Flat
House

MaxRent
2000
1800
2000
2500

Property
PA14
PG4
PG4
PG36

Date Viewed
24-may-03
20-may-03
26-may-03
28-may-03
Ramasesha
Mudigere

Comments
Too Small
Too far
Looks OK

72

Simple JOIN Example


1. List names of all clients who have viewed a property
along with any comment supplied
SELECT C.ID, Name, property, comment FROM Client C, Viewing V
WHERE C.ID = V.ID;

Alternative ways to Specify JOINS


1. FROM Client C JOIN Viewing V ON C.ID = V.ID
2. FROM Client JOIN Viewing USING ID
3. FROM Client NATURAL JOIN Viewing

Notes
All the above 3 replace both FROM and WHERE in the SQL
First one produces a result with ID column appearing twice
CS 53

Ramasesha Mudigere

73

Relational Database Schema for Example


1
2
3
4
5
CS 53

Ramasesha Mudigere

74

Populated Database

2
5
4

6
CS 53

Ramasesha Mudigere

75

Multi Table SELECT Examples


Retrieve the name and address of all employees who
work for the 'Research' department.
Q1:

SELECT
FNAME, LNAME, ADDRESS
FROM EMPLOYEE, DEPARTMENT
WHERE
DNAME='Research' AND
DNUMBER=DNO

(DNAME='Research') is a selection condition


(corresponds to a SELECT operation in relational algebra)
(DNUMBER=DNO) is a join condition (corresponds to a
JOIN operation in relational algebra)
CS 53

Ramasesha Mudigere

76

SELF JOIN Example


For each employee, retrieve the employee's name, and
the name of his or her immediate supervisor.

SELECT
E.FNAME, E.LNAME, S.FNAME, S.LNAME
FROM
EMPLOYEE AS E S
WHERE
E.SUPERSSN=S.SSN
Note the use of on table employee as two different tables
for join with two different alias names E and S
We can think of E and S as two different copies of
EMPLOYEE, representing employees in role of
supervisees and supervisors respectively

This Process is known as Self Join


CS 53

Ramasesha Mudigere

77

OUTER JOIN
If one row of a joined table is unmatched, row is
omitted from result table of a JOIN.
Outer join operations retain rows that do not satisfy the
join condition.
Outer join can be
LEFT
Rows from left Table are retained

RIGHT
Rows from the right table are retained or

FULL
Rows from the Both tables are retained
CS 53

Ramasesha Mudigere

78

Consider tables above:


The (inner) join of these two tables: SELECT b.*, p.* FROM
Branch1 b, PropertyForRent1 p WHERE b.bCity = p.pCity;
Results in two rows

To include unmatched rows in result table, use an Outer join


CS 53

Ramasesha Mudigere

79

Outer JOIN Example - LEFT


List branches and properties that are in same city along
with any unmatched branches
SELECT b.*, p.* FROM Branch1 b LEFT JOIN PropertyForRent1 p
ON b.bCity = p.pCity;

Includes those rows of first (left) table unmatched with


rows from second (right) table.
Columns from second table are filled with NULLs

CS 53

Ramasesha Mudigere

80

Outer JOIN Example - RIGHT


List branches and properties that are in same city along
with any unmatched Properties
SELECT b.*, p.* FROM Branch1 b RIGHT JOIN PropertyForRent1
p ON b.bCity = p.pCity;

Includes those rows of second (right) table unmatched


with rows from first (left) table.
Columns from First table are filled with NULLs

CS 53

Ramasesha Mudigere

81

Outer JOIN Example - FULL


List branches and properties in same city and any
unmatched branches or properties
SELECT b.*, p.* FROM Branch1 b FULL JOIN PropertyForRent1 p
ON b.bCity = p.pCity;

Includes rows that are unmatched in both tables.


Unmatched columns are filled with NULLs.

CS 53

Ramasesha Mudigere

82

Set Operations with SELECT


Supports UNION, INTERSECTION and DIFFERENCE
to combine results of two or more queries whose
results are union compatible into a single result table
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
CS 53

Ramasesha Mudigere

83

Set Operation Examples - UNION


Consider the following tables:
Branch ( Branchno, street, city, pin)
Property (Propid, street, city, type, rent, ownerid, branchandling)

1. List all cities with either a branch office or a property


SELECT city FROM Branch WHERE city IS NOT NULL)
UNION
SELECT city FROM Property WHERE city IS NOT NULL
OR
SELECT * FROM Branch WHERE city IS NOT NULL
UNION CORRESPONDING BY city
SELECT * FROM Property WHERE city IS NOT NULL
CS 53

Ramasesha Mudigere

84

Set Operation Examples - INTERSECT


2. List all cities with both branch office AND a property
SELECT city FROM Branch
INTERSECT
SELECT city FROM Property

OR
SELECT * FROM Branch
INTERSECT CORRESPONDING BY city
SELECT * FROM Property
CS 53

Ramasesha Mudigere

85

Set Operation Examples - EXCEPT


3. List all cities with branch office but no property
SELECT city FROM Branch
EXCEPT
SELECT city FROM Property

OR
SELECT * FROM Branch

EXCEPT CORRESPONDING BY city


SELECT * FROM Property
CS 53

Ramasesha Mudigere

86

Summary of SQL Queries (cont.)


The SELECT-clause lists the attributes or functions to be
retrieved
The FROM-clause specifies all relations (or aliases) needed in
the query but not those needed in nested queries
The WHERE-clause specifies the conditions for selection and join
of tuples from the relations specified in the FROM-clause
GROUP BY specifies grouping attributes
HAVING specifies a condition for selection of groups
ORDER BY specifies an order for displaying the result of a query
A query is evaluated by first applying the WHERE-clause, then
GROUP BY and HAVING, and finally the SELECT-clause
CS 53

Ramasesha Mudigere

87

1. SQL DML Component


Comprises FOUR (4 ) basic statements:
1. SELECT

To retrieve rows from tables

2. UPDATE

To modify the rows of tables

3. INSERT

To add new rows to tables

4. DELETE

CS 53

To remove rows from tables.


Ramasesha Mudigere

88

UPDATE Command of SQL


Used to modify existing rows with the UPDATE
statement
Can Update more than one row at a time, if required
The format of the UPDATE command is:
UPDATE TableName
SET colName1 = dataValue1 [, colName2 = dataValue2...]
[WHERE searchCondition]

SET clause specifies names of one or more columns


along with new compatible values that are to be updated
WHERE limits rows updated
If omitted all rows are Updated
CS 53

Ramasesha Mudigere

89

UPDATE Example
1. Give all staff a 3% pay increase.
UPDATE Staff SET salary = salary*1.03;

2. Give all Managers a 5% pay increase.


UPDATE Staff SET salary = salary*1.05
WHERE position = Manager;

3. Promote XYZ (staffNo=SG14) to Manager & change


his salary to 55,000
UPDATE Staff
SET position = Manager, salary = 55000
CS 53

WHERE staffNo = SG14

Ramasesha Mudigere

90

1. SQL DML Component


Comprises FOUR (4 ) basic statements:
1. SELECT

To retrieve rows from tables

2. UPDATE

To modify the rows of tables

3. INSERT

To add new rows to tables

4. DELETE

CS 53

To remove rows from tables.


Ramasesha Mudigere

91

INSERT Command of SQL


Add a new row to a table
INSERT INTO TableName [ (colList) ] 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
dataValueList must match colList 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.
CS 53

Ramasesha Mudigere

92

INSERT Example
SQL> INSERT INTO department (deptno, dname, loc)
2 VALUES
(50, 'DEVELOPMENT', 'DETROIT');
1 row created.

Implicit method: Omit the column from the column list


SQL> INSERT INTO department (deptno, dname )
2 VALUES
(60, 'MIS');
1 row created.

Explicit method: Specify the NULL keyword


SQL> INSERT INTO department
2 VALUES
(70, 'FINANCE', NULL);
1 row created.
CS 53

Ramasesha Mudigere

93

INSERT with a sub-query

Allows for multiple rows to be copied from one or more


tables to another
Do not use the VALUES clause .
Match the number of columns in the INSERT clause to
those in the subquery
SQL> INSERT INTO managers (id, name, salary,
hiredate)
2
SELECT empno, ename, sal, hiredate
3
FROM employee
4
WHERE job = 'MANAGER'
3 rows created.
CS 53
Ramasesha Mudigere
94

1. SQL DML Component


Comprises FOUR (4 ) basic statements:
1. SELECT

To retrieve rows from tables

2. UPDATE

To modify the rows of tables

3. INSERT

To add new rows to tables

4. DELETE

CS 53

To remove rows from tables.


Ramasesha Mudigere

95

DELETE Command of SQL


Used to remove existing rows from a table
DELETE FROM TableName [ WHERE searchCondition ]

SearchCondition is optional;
If specified, only the rows that satisfy condition are deleted
if omitted, all rows are deleted ( But not the table itself !)
1. SQL> DELETE FROM department
2 WHERE
dname = 'DEVELOPMENT'
1 row deleted.
2. SQL> DELETE FROM department;
4 rows deleted.
CS 53

Ramasesha Mudigere

96

1. SQL DML Component


Comprises FOUR (4 ) basic statements:
1. SELECT

To retrieve rows from tables

2. UPDATE

To modify the rows of tables

3. INSERT

To add new rows to tables

4. DELETE

CS 53

To remove rows from tables.


Ramasesha Mudigere

97

2. SQL DDL Component


Comprises THREE (3) basic statements:
1. CREATE
To create new table specification

2. DROP
To delete the tables

3. ALTER
To add or delete columns from a table, and
To change the specification on an existing
column
CS 53

Ramasesha Mudigere

98

SQL Data Types

1. Boolean ) Consists of variables which can take truth values

of TRUE, FALSE & UNKNOWN (NULL)


2. Character ) Consists of sequence of characters ( a string)
from vendor defined set ( ASCII or EBCDIC)
3. Numeric ) To define numbers ( both integer and real ) based
on pattern or storage allocation

4. BIT ) Consists of sequence of bits ( 0 / 1) ( bit string)


5. Datetime ) To define points in time to a certain degree of
accuracy
6. Interval ) Used to represent periods of time

7. Large Objects ( LOBs) ) Used to store huge amounts of


binary/character data

CS 53

Ramasesha Mudigere

99

2. SQL Data Types Character types


Two sub types are supported namely
1. Fixed length CHAR (n) where n is number of Characters
2. Variable length VARCHAR (n) or CHAR VARYING (n)
where n is the max size of the data item

When specifying a literal string value, the string is


placed between single Quotes ( E.g. Example)
When the character string stored in a field is less than
the size defined, Fixed length CHAR fields are blank
filled to the right & these blanks are ignored in
comparison
CS 53

Ramasesha Mudigere

100

3. SQL Data Types Numeric types


Two sub-categories namely
1. Approximate Numeric which describes the type &
2. Exact Numeric which describes format of the numbers

2.1 Approximate Numeric has following types

CS 53

INTEGER or INT
SMALLINT
FLOAT ( Precision)
or REAL
DOUBLE PREISION
Precision on FLOAT defines the precision of mantissa
Precision & size of REAL & DOUBLE PRECISION is
implementation dependent
Ramasesha Mudigere

101
. Contd.

3. SQL Data Types Numeric types


Two sub-categories namely
1. Approximate Numeric which describes the type &
2. Exact Numeric which describes format of the numbers

2.2 Exact Numeric

Used for declaring formatted numbers


NUMERIC ( p, s ) or DECIMAL ( p, s) where
p represents the TOTAL number of digits ( precision) and
S represents the number of digits to the right of decimal
point ( scale) ( 0 < or = s < or = p & default is 0)
Example : SALARY TYPE NUMERIC (5,2) can hold a
maximum value of 999.99 & min value of 999.99
CS 53

Ramasesha Mudigere

102

4. SQL Data types Bit String Type


Used to store strings of bits that can take value 0 or 1
Two types are supported
BIT (n) where n specifies the length of the bit string
BIT VARYING (n) specifies a variable length string of
maximum size n
Literal bit strings are specified by placing the string
between single quotes but preceded by B ( like fo
example B101101

1.
2.

If the string size is a multiple of even hexa-decimal


notation can be used with preceding character X

Data is right justified and zero filled to the left

CS 53

Ramasesha Mudigere

103

5. SQL Data types Datetime Type


Used to define points in time to a certain degree of
accuracy

E.g. dates, times, and times of a day

ISO standard subdivides this data type to YEAR, MONTH,


DAY, HOUR, MINUTE, SECOND, TIMEZONE_ HOUR &
TIMEZONE_MINUTE

1.
2.
3.

Three types of Datetime data type is supported


DATE
TIME [ timePrecision] WITH TIME ZONE]
TIMESTAMP [ timePrecision] WITH TIME ZONE]

CS 53

Ramasesha Mudigere

104
. Contd.

5. SQL Data types Datetime Type


5.1 DATE
Used to store calendar dates
Has TEN positions with components as YEAR MONTH and DAY
in the form YYYYMMDD
Literal values can be mentioned as DATE2006-09-27 and
comparison performed directly

5.2 TIME [ timePrecision] WITH TIME ZONE]


Used to store time with at least 8 positions with components
HOUR, MINUTE and SECOND in the form HH:MM:SS
timeprecision is the number of the decimal places of accuracy
to which the second field is kept ( Max vendor dependent) and
it defaults to 0
CS 53
Ramasesha Mudigere
CS 53

Ramasesha Mudigere

105
. Contd.

5. SQL Data types Datetime Type


5.2 TIME [ timePrecision] WITH TIME ZONE]
WITH TIME ZONE keyword includes additional six positions
for specifying the displacement from the standard universal
time zone
Literal values can be mentioned as TIME09:22:15 and
comparison performed directly
5.3 TIMESTAMP
Includes both the DATE and TIME fields plus a minimum of
six positions for decimal fractions of seconds and optional with
TIME ZONE Qualifier
Literal values are placed by single-quoted-strings preceded by
TIMESTAMP ( E.g. TIMESTAMP 2006-09-1115:35:648302)
CS 53

Ramasesha Mudigere

106

6. SQL Data types Interval Type


Used to represent periods of time ( Durations)
Consists of contiguous subset of fields YEAR, MONTH,
DAY, HOUR, MINUTE, SECOND

Two types of INTERVAL fields


1. Year-Month intervals &
2. Day-time Intervals
Generally used in Temporal databases
Format

CS 53

INTERVAL [{startfield] TO [Endfield}] or [singletimefield]


Ramasesha Mudigere

107

7. SQL Data types LOBs


Used to store large size objects which are generally
not kept as a part of data base (E.g. (photos, videos,
CAD files, etc.)
1. blob: binary large object

A large collection of un-interpreted binary data (whose


interpretation is left to an application outside of the
database system)

2. clob: character large object

a large collection of character data

When a query returns a large object, a pointer is


returned rather than the large object itself.
CS 53

Ramasesha Mudigere

108

8. User Defined data Types


SQL 3 supports user Defined data types (UDT)
A specific domain can be declared and the domain
name used with the attribute Specification
CREATE DOMAIN AGE_TYPE AS numeric (2)
CHECK(VALUE BETWEEN 16 AND 58);
The domain may later be used as data type in defining
the column type as AGE_TYPE
CS 53

Ramasesha Mudigere

109

ISO Standard SQL Data Types

CS 53

Ramasesha Mudigere

110

Data Types Supported in SQL 92 ( ORACLE)


Data type

Description

VARCHAR2(size)

Variable-length character data

CHAR(size)

Fixed-length character data

NUMBER(p,s)

Variable-length numeric data

DATE

Date and time values

LONG

Variable-length character data up to 2 GB

CLOB

Single-byte character data up to 4 GB

RAW and LONG RAW


BLOB
BFILE
CS 53

Raw binary data

Binary data up to 4 gigabytes


Binary data stored in an external file; up to 4 GB
Ramasesha Mudigere

111

Integrity Enhancement Features


SQL Standards provide for Integrity Control using
which we can define constraints, that protect database
from becoming inconsistent
FIVE types of Integrity constraints are supported
1. Required data.
2. Domain constraints.
3. Entity integrity.
4. Referential integrity.
5. Enterprise constraints
CS 53

Ramasesha Mudigere

112
. Contd.

Integrity Enhancement Features (Contd.)


1. Required data

A mandatory column that must have data in it can be


Specified using NOT NULL clause as:
position
VARCHAR(10)
NOT NULL
All primary key fields MUST have this clause

2. Domain Constraint

CS 53

Set of legal values for the variable can be specified


Gender CHAR NOT NULL CHECK (Gender IN (M, F))
Can also create a specific domain with CHECK
constraints that can be used with several columns in the
entire database
Ramasesha Mudigere

113
. Contd.

Integrity Enhancement Features (Contd.)


3. Entity Integrity

Specified at the table level

Primary key of a table must contain a unique, non-null


value for each row.

Can have ONLY ONE primary key definition per table (


Could be made up of multiple columns though)

Can still ensure uniqueness for alternate keys using


UNIQUE clause as:

CS 53

UNIQUE ( Tel-No)
Ramasesha Mudigere

114
. Contd.

Integrity Enhancement Features (Contd.)


4. Referential Integrity

Achieved using FOREIGN KEY (FK) Definition


(FK is column or set of columns that links each row in
child table containing foreign FK to row of parent table
containing matching PK. ) For example

FOREIGN KEY ( branchNo ) REFERENCES Branch

CS 53

Referential integrity means that, if FK contains a value,


that value must refer to existing row in parent table

Any INSERT that attempts to create FK value in child


table without matching candidate key value in parent is
rejected.
Ramasesha Mudigere

115
. Contd.

Integrity Enhancement Features (Contd.)


4. Referential Integrity ( Contd.)
Referential Action

CS 53

Action taken when attempts to update/delete a candidate


key value in parent table with matching rows in child is
dependent on referential action

Specified using ON UPDATE and ON DELETE subclauses of FOREIGN KEY clause of CREATE Statement

Possible Options are

1. CASCADE

2. SET NULL

3. SET DEFAULT &

4. NO ACTION

Ramasesha Mudigere

116
. Contd.

Integrity Enhancement Features (Contd.)


Referential Action
CASCADE ) Automatically delete the matching rows in the
child table recursively
SET NULL ) Set the foreign Key column in child table to
NULL ( Valid only if that column is not
declared as NOT NULL)

SET DEFAULT ) Set the foreign Key column in child table


to DEFAULT Value ( Valid only if that
column is declared with a DEFAULT
option)

NO ACTION ) Reject the command (Default Action)


CS 53

Ramasesha Mudigere

117

Integrity Enhancement Features (Contd.)


5. Enterprise Constraints

A set of rules that are application specific that can be set

Done Using CHECK / UNIQUE clauses in CREATE and


ALTER TABLE Statements of SQL

No manager can manage more than 100 properties.

CREATE ASSERTION StaffNotHandlingTooMuch

CHECK (NOT EXISTS (SELECT staffNo


FROM PropertyForRent
GROUP BY staffNo
HAVING COUNT(*) > 100))

CS 53

Ramasesha Mudigere

118

CREATE Command of SQL


Creates a table with one or more columns of the
specified data Type.
With any column
Specifying NOT NULL system rejects any attempt to insert
a null in the column.
UNIQUE specification rejects duplicates in the column
CHECK clause can be specified to restrict allowed values
A DEFAULT value for the column Can be specified
FOREIGN KEY clause specifies FK along with the
referential action

Primary keys can be specified for each table


CS 53

Ramasesha Mudigere

119

CREATE Command Syntax


CREATE TABLE TableName
{(colName dataType [NOT NULL] [UNIQUE]
[DEFAULT defaultOption]
[CHECK searchCondition] [,...]}
[ CONSTRAINT] [PRIMARY KEY (listOfColumns),]
{[UNIQUE (listOfColumns),] [,]}
{[FOREIGN KEY (listOfFKColumns)
REFERENCES ParentTableName [(listOfCKColumns)],
[ON UPDATE referentialAction]
[ON DELETE referentialAction ]] [,]}
{[CHECK (searchCondition)] [,] })
CS 53

Ramasesha Mudigere

120

Defining attributes and their data types

CS 53

Ramasesha Mudigere

121

CREATE Command Example

CS 53

Ramasesha Mudigere

122

CREATE Command Example

CS 53

Ramasesha Mudigere

123

CREATE Command Example

CS 53

Ramasesha Mudigere

124

Assertions
A predicate expressing a condition that we wish the
database always to satisfy
An assertion in SQL takes the form
create assertion <assertion-name> check
<predicate>
When an assertion is made, the system tests it for
validity, and tests it again on every update that may
violate the assertion
May introduce a significant amount of overhead; hence
assertions should be used with great care.
CS 53

Ramasesha Mudigere

125

Assertions
Every loan has at least one borrower who maintains an
account with a minimum balance or $1000.00
create assertion balance_constraint check
(not exists (
select *
from loan
where not exists (
select * from borrower, depositor, account
where loan.loan_num = borrower.loan_num
and borrower.cust_name = depositor.cust_name
and depositor.acct_num = account.acct_num
and account.balance >= 1000)))
CS 53

Ramasesha Mudigere

126

2. SQL DDL Component


Comprises THREE (3) basic statements:
1. CREATE
To create new table specification

2. DROP
To delete the tables

3. ALTER
To add or delete columns from a table, and
To change the specification on an existing
column
CS 53

Ramasesha Mudigere

127

DROP Command
Removes named table and all rows within it.
Format :
DROP TABLE TableName [RESTRICT | CASCADE]

e.g. DROP TABLE PropertyForRent;

With RESTRICT, if any other objects depend for their


existence on continued existence of this table, SQL
does not allow request.
With CASCADE, SQL drops all dependent objects (and
objects dependent on these objects).
CS 53

Ramasesha Mudigere

128

2. SQL DDL Component


Comprises THREE (3) basic statements:
1. CREATE
To create new table specification

2. DROP
To delete the tables

3. ALTER
To add or delete columns from a table, and
To change the specification on an existing
column
CS 53

Ramasesha Mudigere

129

ALTER Command
Can be used for following functions
1. Add a new column to a table.
2. Drop a column from a table.
3. Add a new table constraint.
4. Drop a table constraint.
5. Set a default for a column.
6. Drop a default for a column.
CS 53

Ramasesha Mudigere

130

ALTER command Format


ALTER TABLE TableName
[ADD [COLUMN] Colname, datatype [NOT NULL]., [ UNIQUE]
[ DEFAULT defaultOption ] [CHECK searchCondition]
[ DROP [COLUMN} colname [ RESTRICT [ CASCADE ]]
[ADD [ CONSTRAINT [ ConstraintName]]
[DROP [ CONSTRAINT [ ConstraintName]]
[ALTER [COLUMN] SET DEFAULT defaultOption]
[ALTER [COLUMN] DROP DEFAULT defaultOption]
CS 53

Ramasesha Mudigere

131

ALTER Examples

Change Staff table by removing default of Assistant


for position column and setting default for sex column
to female (F).
ALTER TABLE Staff ALTER position DROP DEFAULT;
ALTER TABLE Staff ALTER sex SET DEFAULT F;

Remove constraint from Property that staff not allowed


to handle more than 100 properties at time
ALTER TABLE Property
DROP CONSTRAINT StaffNotHandlingTooMuch;

Add new column to Client table


ALTER TABLE Client ADD prefNoRooms NUMERIC (2);

CS 53

Ramasesha Mudigere

132

Steps in table creation:


1. Identify data types for attributes
2. Identify columns that can and cannot be null
3. Identify columns that must be unique (candidate keys)
4. Identify primary key-foreign key mates
5. Determine default values
6. Identify constraints on columns (domain specifications)
7. Create the table and associated indexes
CS 53

Ramasesha Mudigere

133

VIEWS in RDBMS
A virtual table created dynamically with one or more
relational operations on base relations
Virtual relation that does not necessarily exist in the
DB, but is produced upon request, at time of request.
Contents of a view are defined as a query on one or
more base relations or other views
Allows full query operations ( With some restricitons)
Allows for limited update operations (since the table
may not physically be stored)
CS 53
Ramasesha Mudigere
134
. Contd.

VIEWS in RDBMS

With view resolution,

any operations on view are automatically translated into


operations on relations from which it is derived.

With view materialization


the view is stored as a temporary table, which is maintained
as the underlying base tables are updated
assumption: other queries on the view will follow
concerns: maintaining correspondence between the base
table and the view when the base table is updated
strategy: incremental update
Generally used in SQL procedural programming
environments
CS 53

Ramasesha Mudigere

135
. Contd.

Views Advantages & Disadvantages

Advantages:

Simplify query commands


Assist with data security (but don't rely on views for
security, there are more important security measures)
Enhance programming productivity
Contain most current base table data
Use little storage space
Provide customized view for user
Establish physical data independence

Disadvantages
Use processing time each time view is referenced
May or may not be directly updateable
CS 53

Ramasesha Mudigere

136

Creation of VIEWS

Using CREATE Command with following formant:


CREATE VIEW ViewName [ (newColumnName [,...]) ]
AS sub-select [WITH [CASCADED | LOCAL] CHECK OPTION]

Can assign a name to each column in view.


If list of column names is specified, it must have same number
of items as number of columns produced by sub-select.
((A.k.a. defining query ; it cant have ORDER BY)
If omitted, each column takes name of corresponding column
in sub-select
Need SELECT privilege on all tables referenced in subselect
and USAGE privilege on any domains used in referenced
columns
CS 53

Ramasesha Mudigere

137

CREATE VIEW ( horizontal) Example


Create view so that manager at branch B003 can only
see details for staff who work in his or her office.
CREATE VIEW Manager3Staff
AS SELECT * FROM Staff WHERE branchNo = B003;

CS 53

Ramasesha Mudigere

138

CREATE VIEW ( Vertical) Example


Create view of staff details at branch B003 excluding
salaries
CREATE VIEW Staff3
AS SELECT staffNo, fName, lName, position, sex
FROM Staff WHERE branchNo = B003;

CS 53

Ramasesha Mudigere

139

Grouped and Joined Views


A complex view that contains group functions to
display values from two tables
SQL> CREATE VIEW
2
3

(name, minsal, maxsal, avgsal)


AS SELECT d.dname, MIN(e.sal), MAX(e.sal),

AVG(e.sal)

FROM

WHERE

GROUP BY

View created.
CS 53

dept_sum_vu

employee e, department d
e.deptno = d.deptno
d.dname;
Ramasesha Mudigere

140

DML Operations on a View


Cannot update / delete a row if the view contains any
of the following:

Group functions
A GROUP BY clause
The DISTINCT keyword

Columns defined by expressions


Can not add data through INSERT INTO view if:
The view contains any of the conditions mentioned above
There are NOT NULL columns in the base tables that are
not selected by the view
CS 53

Ramasesha Mudigere

141

WITH CHECK OPTION on View CREATE


Must be added to the definition of a view if the view is to
be updated
Rows exist in a view because they satisfy WHERE
condition of defining query.
If a row changes and no longer satisfies condition, it
disappears from the view.
New rows appear within view when insert/update on view
cause them to satisfy WHERE condition.
Rows that enter or leave a view are called migrating
rows.
WITH CHECK OPTION prohibits a row migrating out of the
view
CS 53
Ramasesha Mudigere
142

WITH CHECK OPTION - Example


Consider the view defined as
CREATE VIEW Manager3Staff
AS SELECT * FROM Staff
WHERE branchNo = B003
WITH CHECK OPTION;
Cannot update branch number of row B003 to B002 as
this would cause row to migrate from view.
Also cannot insert a row into view with a branch
number that does not equal B003.
CS 53

Ramasesha Mudigere

143

Removing Views
Done using DROP Command
DROP VIEW ViewName [RESTRICT | CASCADE]
Causes definition of view to be deleted from database.
For example:
DROP VIEW Manager3Staff;
NOTE:
Unlike the dropping of tables, the data rows still remain
even after View is dropped, since data rows belong to
base tables and NOT views
CS 53

Ramasesha Mudigere

144

INDEX

Used to speed up the retrieval of rows by using a pointer


Reduces disk I/O by using rapid path access method to
locate the data quickly
Independent of the table it indexes
Automatically used and maintained by the RDBMS
Index is created
Automatically
A unique index is created automatically when you define a
PRIMARY KEY or UNIQUE key constraint in a table definition.

Manually
CS 53

Users can create non-unique indexes on columns to speed up


access time to the rows
Ramasesha Mudigere

145

Creating an Index - Example


The Syntax is :
CREATE INDEX index
ON table (column[, column]...);
Improve the speed of query access on the ENAME
column in the EMP table
SQL> CREATE INDEX
2 ON
Index created.
CS 53

emp_ename_idx
employee(ename);

Ramasesha Mudigere

146

Removing the Index


DROP command is used to remove the index from DB
The Syntax is :
DROP INDEX index
Example:
Remove the EMP_ENAME_IDX index from the data
dictionary
SQL> DROP INDEX emp_ename_idx;
Index dropped.
CS 53

Ramasesha Mudigere

147

2. SQL DDL Component


Comprises THREE (3) basic statements:
1. CREATE
To create new table specification

2. DROP
To delete the tables

3. ALTER
To add or delete columns from a table, and
To change the specification on an existing
column
CS 53

Ramasesha Mudigere

148

3. SQL Admin Component


Comprises FOUR (4) basic statements:
1. CREATE
To create new users to access database

2. DROP
To delete the users

3. GRANT
To provide specific access permissions to users

4. REVOKE
To withdraw access permissions from users
CS 53

Ramasesha Mudigere

149

CREATE & DROP Users


The DBA creates users by using the CREATE USER
statement CREATE USER
user
Format : IDENTIFIED BY password;
Example:
SQL> CREATE USER scott
2 IDENTIFIED BY tiger;
User created.

Users are Removed Using DROP command


SQL> DROP USER
CS 53

User dropped.

scott

Ramasesha Mudigere

150

3. SQL Admin Component


Comprises FOUR (4) basic statements:
1. CREATE
To create new users to access database

2. DROP
To delete the users

3. GRANT
To provide specific access permissions to users

4. REVOKE
To withdraw access permissions from users
CS 53

Ramasesha Mudigere

151

GRANT Command

Used to provide privileges to users


Privileges:

Actions user permitted to carry out on given base table or view:


SELECT
Retrieve data from a table.
INSERT Insert new rows into a table.
UPDATE
Modify rows of data in a table.
DELETE
Delete rows of data from a table.
REFERENCESReference columns of named table in
integrity constraints.
USAGE Use domains, collations, character sets, and
translations.
Can restrict INSERT/UPDATE/REFERENCES to named columns.
CS 53

Ramasesha Mudigere

152

GRANT Command
GRANT {PrivilegeList | ALL PRIVILEGES}
ON ObjectName TO {AuthorizationIdList | PUBLIC}
[WITH GRANT OPTION]
PrivilegeList consists of one or more of privileges
separated by commas.
ALL PRIVILEGES grants all privileges to a user
GRANT Can be executed by the owner of the table
PUBLIC allows access to be granted to all present and
future authorized users
WITH GRANT OPTION allows privileges to be passed
on

CS 53

Ramasesha Mudigere

153

GRANT Example
Give Scott full privileges to Staff table.
GRANT ALL PRIVILEGES
ON Staff
TO Scott WITH GRANT OPTION;
Give users Scott and Narayan SELECT and UPDATE
on column salary of Staff.
GRANT SELECT, UPDATE (salary)
ON Staff
TO Scott, Narayan ;
CS 53

Ramasesha Mudigere

154

Concept of ROLE

Users
Manager

Privileges
Allocating privileges
Without a role
CS 53

Ramasesha Mudigere

Allocating privileges
with a role
155

GRANTing with ROLEs - Example


SQL>
SQL>
Role
Role

CREATE
CREATE ROLE
ROLE manager;
manager;
created.
created.

SQL>
SQL> GRANT
GRANT create
create table,
table, create
create view
view
22
to
to manager;
manager;
Grant
Grant succeeded.
succeeded.

SQL>
SQL> GRANT
GRANT manager
manager to
to BLAKE,
BLAKE, CLARK;
CLARK;
Grant
Grant succeeded.
succeeded.
CS 53

Ramasesha Mudigere

156

3. SQL Admin Component


Comprises FOUR (4) basic statements:
1. CREATE
To create new users to access database

2. DROP
To delete the users

3. GRANT
To provide specific access permissions to users

4. REVOKE
To withdraw access permissions from users
CS 53

Ramasesha Mudigere

157

REVOKE Command
Takes away privileges granted with GRANT
The format is
REVOKE [GRANT OPTION FOR]
{PrivilegeList | ALL PRIVILEGES}
ON ObjectName
FROM {AuthorizationIdList | PUBLIC}
[RESTRICT | CASCADE]
ALL PRIVILEGES refers to all privileges granted to a
user by user revoking privileges.
CS 53

Ramasesha Mudigere

158

REVOKE Command Options


GRANT OPTION FOR allows privileges passed on via
WITH GRANT OPTION of GRANT to be revoked
separately from the privileges themselves.
Privileges granted to this user by other users are not
affected.
Example:
SQL> REVOKE select, insert
2 ON department
3 FROM
scott;
Revoke succeeded.
CS 53

Ramasesha Mudigere

159

3. SQL Admin Component


Comprises FOUR (4) basic statements:
1. CREATE
To create new users to access database

2. DROP
To delete the users

3. GRANT
To provide specific access permissions to users

4. REVOKE
To withdraw access permissions from users
CS 53

Ramasesha Mudigere

160

Database Programming
Objective: ) To access a database from an application

program (as opposed to interactive interfaces)


Reason ) An interactive I/F is convenient but not sufficient;
) Many DB operations are made thru application
programs (nowadays thru web applications

Solution: ( Two fold)


1. Embedded SQL ) 1.Database commands are embedded in a
general-purpose programming languages
) 2. Augment SQL with program constructs
E.g. PL/SQL , TRANSACT_SQL etc.
2. API ) Library of database functions available to the host
language for database calls ( ODBC, JDBC, CLI )
CS 53

Ramasesha Mudigere

161

Database Programming Issues


The basic issue is the Incompatibilities between a host
programming language and the database model
(Impedance Mismatch) like.,
1. Type mismatch and incompatibilities; requires a new
binding for each language
2. set vs. record-at-a-time processing
Need special iterators to loop over query results and
manipulate individual values
CS 53

Ramasesha Mudigere

162

1. Type mismatch problem

Solution
Try and match the DBMS data types to the
corresponding closest match in the language like:
CHAR datatype to CHAR in C and PIC X field in COBOL
NUMERIC to Char in C ( with external to care to store only
numbers) and PIC 9 fields in COBOL

Define a mechanism to declare variables to be used as


interface between DB attributes and program variables
An EXEC DECLARE SECTION

Define an elaborate error interface to report errors


back to the programs in case of type mismatch after
each SQL execution in the program

CS 53

Ramasesha Mudigere

163

2. Set vs. record-at-a-time processing


Solution: cursors
Functions as follows:
Open (a table or a result table): position the cursor just
before the first row
Get next: move the cursor to the next row and return that
row; raise a flag if there is no more next row
Close: clean up and release DBMS resources

Found in virtually every database language/API (with


slightly different syntaxes)
Some support more cursor positioning and movement
options, modification at the current cursor position, etc.
CS 53

Ramasesha Mudigere

164

Steps IN DB Programming
How it all works ?
1. Client program opens a connection to the database server
2. Client program submits queries to and/or updates the DB
3. When database access is no longer needed, client program
terminates the connection

What needs to be done ?


1. Declare variables to be used as interfaces in the program
1. Data items ( A.k.a. Host Language variables)
2. Error handling & Communication

2. Embed SQLs where needed in the program


3. Devise an error Handling Strategy
CS 53

Ramasesha Mudigere

165

Embedding SQL
Embedded SQL starts with identifier,
usually EXEC SQL [ @SQL( in MUMPS].
Ends with terminator dependent on host language:

Ada, C, and PL/1: terminator is semicolon (;)


COBOL: terminator is END-EXEC
FORTRAN: ends when no more continuation lines.

Embedded SQL can appear anywhere an executable


host language statement can appear
Will be processed by the pre-processor before
language compiler is invoked
CS 53

Ramasesha Mudigere

166

Embedded Program Preparation


Pgm
Editor

Save

Source
Module

precompiler
Pre-compile

Object
Module

ORACLE
Run Time
Library
CS 53

Compile

Modified
Source
Module

Compiler

Linker
Ramasesha Mudigere

Link

Application
Program
167

CS 53

Ramasesha Mudigere

168

Host language Variables


Used in embedded SQL to transfer data from database
into program and vice versa
Cannot be used to represent database objects, such
as table names or column names
Declared in a special Section of the program initially
Prefixed by colon : , when used in the program
Additional variables called indicators can be
associated with these variables to indicate the status of
data transfer like:
Indicating NULL values in Db
Truncation of data etc..
CS 53

Ramasesha Mudigere

169

Host Variables DECLARE Section

CS 53

Ramasesha Mudigere

170

Indicator variables
Integer Variables Used to indicate the status of data
transfer between host variables and the database
Can be associated with any host language variable
Used immediately following associated host variable
with a colon (:) separating two variables.
0 in Indicator variable indicates successful transfer
Non-zero value to indicate conditions like

CS 53

Data truncation (> 0)


Null value transfer ( < 0)
Type mismatch etc
Ramasesha Mudigere

171

Declaration & Use of Indicator variables


EXEC SQL BEGIN DECLARE SECTION;
char address[51];
short addressInd;
EXEC SQL END DECLARE SECTION;

addressInd = -1;
EXEC SQL UPDATE PrivateOwner
SET address = :address :addressInd
WHERE ownerNo = CO21;
CS 53

Ramasesha Mudigere

172

SQLCA Area
A data structure to be included in the program by the
programmer
Used ( initialized) by DBMS to indicate the status of
every SQL execution in the program
Set by DBMS after execution of each DBMS command
Contains several fields of which SQLCODE is of
special interest

CS 53

0 - statement executed successfully;


< 0 - an error occurred;
> 0 - statement executed successfully, but an exception
occurred, such as no more rows returned by SELECT.
Ramasesha Mudigere

173

CS 53

Ramasesha Mudigere

174

Embedding SQL Commands


Starts with identifier, usually EXEC SQL
Ends with terminator dependent on host language:
Ada, C, and PL/1: terminator is semicolon (;)
COBOL: terminator is END-EXEC
Fortran: ends when no more continuation lines.

Embedded SQL can appear anywhere an executable


host language statement can appear
CS 53

Ramasesha Mudigere

175

Embedded SQL Example

CS 53

loop = 1;
while (loop) {
prompt (Enter SSN: , ssn);
EXEC SQL
select FNAME, LNAME, ADDRESS, SALARY
into :fname, :lname, :address, :salary
from EMPLOYEE where SSN == :ssn;
if (SQLCODE == 0) printf(fname, );
else printf(SSN does not exist: , ssn);
prompt(More SSN? (1=yes, 0=no): , loop);
END-EXEC
}
Ramasesha Mudigere

176

Cursor
Used when multiple rows are Expected to be returned
by SQL query
Allows host language to access rows of query one at a
time
Acts as a pointer to a row of query result
Can be advanced by one to access next row
Using of cursor:

CS 53

Must be declared
opened before it can be used and
Must be closed to deactivate it after it is no longer required
Ramasesha Mudigere

177

Cursor Declaration & Opening


Declared using the SQL DECLARE as follows:
EXEC SQL DECLARE
propertyCursor CURSOR FOR
SELECT propertyNo, street, city
FROM PropertyForRent
WHERE staffNo = SL41;

OPEN statement opens specified cursor and positions


it before first row of query result:
EXEC SQL OPEN propertyCursor;
CS 53

Ramasesha Mudigere

178

Use of Cursor to access data


FETCH retrieves next row of query result table:
EXEC SQL FETCH propertyCursor
INTO :propertyNo, :street, :city
FETCH is usually placed in a loop.
When there are no more rows to be returned,
SQLCODE is set to NOT FOUND
Cursor needs to be closed at the end of use using
EXEC SQL CLOSE propertyCursor;
CS 53

Ramasesha Mudigere

179

Dynamic SQL
SQL that does not need to be hard coded into the program
Built with character string on the fly
Example of using Dynamic SQL in C
char * sqlprog = update account
setbalance = balance * 1.05
where account-number = ?
EXEC SQL preparedynprogfrom :sqlprog;
characcount [10] = A-101;
EXEC SQL execute dynprogusing :account;
The dynamic SQL program contains a ?, which is a place
holder for a value that is provided when the SQL program is
executed.

CS 53

Ramasesha Mudigere

180

4. SQL Programming Component


Comprises FOUR (4) basic statements:
1. DECLARE
To define CURSORS to access database

2. OPEN
To enable / activate CURSORS

3. FETCH
To get data rows based on CURSOR

4. CLOSE
To disable /deactivate the cursor
CS 53

Ramasesha Mudigere

181

Dynamic Embedded SQL


With static embedded SQL, cannot use host variables
where database object names required.
Dynamic SQL allows this.
Idea is to place complete SQL statement in a host
variable, which is passed to DBMS to be executed.
If SQL statements do not involve multi-row queries,
use EXECUTE IMMEDIATE statement:
sprintf(buffer, UPDATE Staff
SET salary = salary + %f
WHERE staffNo = SL21 , increment);
EXEC SQL EXECUTE IMMEDIATE :buffer;
CS 53

Ramasesha Mudigere

182

PL / SQL The other alternative


A new language defined with programming constructs
Like:
Variable definition
Control branching
Looping

etc..

That allows for writing programs


Pioneered by ORACLE
Now part of SQL 1999 Standard (SQL /PSM)
CS 53

Ramasesha Mudigere

183

SQL/PSM: An Example
CREATE FUNCTION DEPT_SIZE (IN deptno INTEGER)
RETURNS VARCHAR[7]
DECLARE TOT_EMPS INTEGER;
SELECT COUNT (*) INTO TOT_EMPS
FROM SELECT EMPLOYEE WHERE DNO = deptno;
IF TOT_EMPS > 100 THEN RETURN HUGE
ELSEIF TOT_EMPS > 50 THEN RETURN LARGE
ELSEIF TOT_EMPS > 30 THEN RETURN MEDIUM
ELSE RETURN SMALL

ENDIF;
CS 53

Ramasesha Mudigere

184

Call Level Interfaces (CLI)


A more modern approach to the host language SQL
connection
C or other language program creates SQL statements
as character strings and passes them to functions that
are part of a library
Similar to what really happens in embedded dynamic
SQL implementations
A part of the SQL standard, that Provides easy access
to several databases within the same program
Certain libraries (e.g., sqlcli.h for C) have to be
installed and available
CS 53

Ramasesha Mudigere

185

Steps in SQL /CLI Programming


1. Load SQL/CLI libraries
2. Declare record handle variables for the above
components (called: SQLHSTMT, SQLHDBC,
SQLHENV, SQLHDEC)

3. Set up an environment record using SQLAllocHandle


4. Set up a connection record using SQLAllocHandle
5. Set up a statement record using SQLAllocHandle
CS 53

Ramasesha Mudigere

186

Steps in SQL /CLI Programming (Contd.)


6. Prepare a statement using SQL/CLI function
SQLPrepare

7. Bound parameters to program variables


8. Execute SQL statement via SQLExecute
9. Bound columns in a query to a C variable via
SQLBindCol

10. Use SQLFetch to retrieve column values into C


variables
CS 53

Ramasesha Mudigere

187

ODBC A CLI from Microsoft


An extended version of SQL/CLI originally designed for
windows, but got extended to other platforms later by
other vendors like Visigenic, Intersolv, OpenLink etc
Current version is 3.5 the unicode enabled version
Has over 80 calls that fall into 3 conformance levels

CS 53

Core that lets you connect to DB, execute SQL , fetch


results, Commit & rollback transactions, handle exceptions
and terminate connections
Level 1 - that lets you retrieve info from DB catalog, fetch
large objects & deal with driver specific functions
Level 2 that lets you retrieve data using cursors (forward
& backward)
Ramasesha Mudigere

188

ODBC (Contd.)
Very successful API, with virtually every database
vendor providing an ODBC driver for its database,
However
Each vendor have their own proprietary native API
(Oracle Oracle CLI, IBM ESQL/DRDA, Sybase
Sybase open client MS- SQL ODBC)

Vendors have added their own extensions to ODBC


driver making it non-standard again !!!
Specs are controlled by Microsoft ; not open standards
Future is uncertain with Microsoft pushing its OLE
based ADO as new standards
CS 53

Ramasesha Mudigere

189

JDBC A Java based CLI

A portable SQL CLI written entirely in JAVA


Provides 2 major sets of interfaces ( similar to ODBC)
Lets you write DBMS-independent Java code (with a
fair amount of effort) ; Part of Java Core
1. An application Interface that lets you access DBMS
services in an independent manner
2. A driver interface that DBMS vendors must adapt to
their particular databases
Uses a driver manager to automatically load the right
JDBC driver to talk to a given Database
All major DB vendors have agreed to support JDBC

CS 53

Ramasesha Mudigere

190

End of Chapter
-4-

Structured Query Language

CS 53

Ramasesha Mudigere

192

SQL 92 Features

SQL-92 -- Ratified in late 1992

SQL client / server connections (SET CONNECTION )


More granular transaction control

CS 53

Read only transactions


Multiple isolation levels ( Read-committed, read-uncommited etc)

Embedded SQL support for C, ADA etc..


Support for dynamic SQL
New data types ( BLOBS, VARCHAR, DATE, TIMESTAMP)
Support for temporary tables
Standardized error codes & Diagnostics & meta-data structures
Support for JOIN operators ( Outer JOIN, Inner JOIN etc..)
Domain checks and constraints
Miscellaneous improvements like backward & forward cursors, new
string functions
Ramasesha Mudigere

. Contd.

193

SQL 1999 Features


New Semantics:

New data types:


Large Objects (LOBs,
CLOBs, BLOBS)
BOOLEAN
Composite Types: ARRAY
and ROW
Distinct Types

New Predicates:
SIMILAR TO 'pattern'
(analogous to regular
expression matching)
DISTINCT objects
CS 53

Broader classes of views


Recursive queries
Locators

Enhanced Security:
Roles

Active Database:
Triggers and Stored
Procedures

Object Orientation:

Structured types & UDT


Methods, with Functional or
Dot Notations
Objects and REF Types

Ramasesha Mudigere

194

SQL 1999 Features

"
?
e
r
o
New Semantics:
New data types:
m
y
n classes of views
Broader
w
A
e
Large Objects (LOBs,
i
)
d tm queries
v
r
r

Recursive
a
e
h
CLOBs, BLOBS)
d
v
.
n Locators
o
1
a
0
t
n
y
a
S
h
BOOLEAN
l
s
6
a i0Enhanced
e Security:
1
e
s
v
i
r
R
/
g do
Composite Types: ARRAY
m
A

Roles
d
o
n
n
L
c
e
a
.
Q an esActive Database:
v
and ROW
l
S
a
s
d
r
r
I
t
e
.
u
"
t
,
v
Distinct Types
w
a

Triggers and Stored

e
e
w
s
f
e
l ://w
y
Procedures
9
c
i
b
9
t
New Predicates:
r
9 ce
p
t
a
1
t
Object Orientation:
e
n
h
&
(
h
a
i
2
T SIMILAR TO 'pattern'
l
9
p
Structured types & UDT
9
m
1
o
(analogous
to regular
L
c
Methods, with Functional or
Q
f
o
S
expression
matching)
Dot Notations
s
t
li s
DISTINCT objects

CS 53

Objects and REF Types

Ramasesha Mudigere

195

SQL Standards Criticisms


A former member of the Committee (Joe Celko) states:
"Seriously, the SQL-99 Standard is going nowhere

Another member (Michael Gorman) wrote a critical article


titled, "Is SQL A Real Standard Anymore?"
(http://www.tdan.com/i016hy01.htm) with following predictions:
"Competition among DBMS vendors will drop, prices will rise,
portability of programs, data & trained staff will end

The key criticism is that there is no enforcer to ensure that


vendors really follow the standard
Without enforcement, fission occurs as it did with Unix and
It's too easy for a vendor to reap benefit from the standard by
claiming compliance without really providing it.
CS 53

Ramasesha Mudigere

196

SQL Data types


Data Types
Binary
String

Character
String

UDT

Double-Byte
Char String

DateTime

Numeric
decimal

DATE time timestamp


integer
CHAR
BLOB

CS 53

CLOB

GRAPHIC
DBCLOB
VARCHAR
VARGRAPHIC

DECIMAL
floating
point

SMALLINT
INTEGER

Ramasesha Mudigere

REAL
DOUBLE

197

Relational Database Schema for Examples


1
2
3
4
5
CS 53

Ramasesha Mudigere

198

Populated Database

2
5
4

6
CS 53

Ramasesha Mudigere

199

Potrebbero piacerti anche