Remaining Topics in SQL to be covered…




NULL values in SQL
Outer joins in SQL
Constraints and Triggers in SQL
Embedded SQL.
Null’s in SQL

SQL supports a special value -- NULL in place of a value in a tuple's
component


Null’s can be used for multiple purposes - Value exists, but we do not know what it is..
 Information does not exist
Example:


boris registered for pass/fail and thus has no project assigned (nulls used to
represent information is inapplicable)
stefan registered for letter grade but has no current project assignment (nulls
used to represent unavailability of information)
Cs184
projects
student
proj title
date
boris
null
null
stefan
null
null
Need for Care in Using Nulls...

Using nulls for missing values may result in loss of information
Cs184
projects
student
proj title
date
boris
oodb
11/16/95
stefan
oodb
11/16/95
monica
par dbms
Cs184
projects
student
proj title
date
boris
null
null
stefan
null
null
monica
null
null
11/21/95
• Information that boris and stefan are part of the same project team
, and that monica is a team by herself is lost by using nulls!
Sometimes Nulls very useful even if
possible to avoid them…
office
employee
relation
office
num
fax number
boris
DCL 2111
333-2400
stefan
DCL 3001
null
monica
DCL 3444
333-0067
• Say 98% of employees have a fax number and a query accessing
office number and fax number is very common.
• Storing information using a different schema (employee, office
num) and (employee, fax number) will cause all such queries to
perform a join!
• Instead using nulls is a better idea in this case.
Interpreting SQL queries with Null (1)

Any arithmetic operation on Null and any other value
results in Null.


E.g., x + 3 == Null, if x is Null
Comparison of Null with any value (including other
Null) results in a value UNKNOWN

E.g., x > 3 results in UNKNOWN, if x is Null
Interpreting SQL with Null (2)




Earlier, we learnt that results of comparison was always
T or F.
Logical operators: AND, OR, NOT combined these truth
values in a natural way to return a T or a F.
However, comparison of Null to a value produces a third
truth value -- UNKNOWN
How to interpret the logical operators in this case?
3-Valued Logic


Think of true = 1; false = 0, and unknown = 1/2.
Then:
AND = min.
OR = max.
NOT(x) = 1 - x
Truth Table
X
T
T
T
U
U
U
F
F
F
T = true
Y
T
U
F
T
U
F
T
U
F
X AND y
T
U
F
U
U
F
F
F
F
X OR Y
T
T
T
T
U
U
T
U
F
F = false
NOT X
F
F
F
U
U
U
T
T
T
U = unknown
SQL …… constraints,
assertions, triggers …
Some Key Laws Fail to Hold in
3-Valued Logic



Example: Law of the excluded middle, i.e.,
p OR NOT p = TRUE
For 3-valued logic: if p = unknown, then left side =
max(1/2,(1-1/2)) = 1/2  1.
there is no way known to make 3-valued logic conform
to all the laws we expect for 2-valued logic.
Example
Bar
beer
price
Joe's bar
Bud
NULL
SELECT bar
FROM Sells
Where price < 2.00 OR price >= 2.00
UNKNOWN
UNKNOWN
UNKNOWN
Modifying Views



How can we modify a view that is “virtual”?
Many views cannot be modified
Some views can be “modified,” called “updatable views”


Their definitions must satisfy certain requirements.
A modification is translated to a modification to its base tables.
views
eName
Jack
Alice
Lisa
Tom
Mary
Dno
111
111
222
333
333
Sal
50K
90K
80K
70K
60K
dno
111
222
333
dname
Sells
Toys
Electronics
Mgr
Alice
Lisa
Mary
eName
Jack
Alice
Lisa
Tom
Mary
Dno
111
111
222
333
333
Sal
50K
90K
80K
70K
60K
Updatable views
toyEmp (ename, dno)
CREATE TABLE Emp(ename char(20),
dno int,
sal float default 0);
CREATE VIEW toyEmp AS
SELECT ename, dno
FROM emp
WHERE dno = 111;
eName
Jack
Alice
Dno
111
111
Tom
111
Emp (ename, dno, sal)
INSERT INTO toyEmp VALUES (‘Tom’, 111);

Insert a tuple to a view:



eName
Jack
Alice
Lisa
Tom
Mary
Dno
111
111
222
333
333
Tom
111
Insert a corresponding tuple to its base table(s)
Missing values will use NULL or default value
Inserted tuples in base table(s) must generate the new view tuple.
Sal
50K
90K
80K
70K
60K
0
Non-updatable views
toyEmp (ename, dno)
CREATE TABLE Emp(ename char(20),
dno int,
sal float default 0);
CREATE VIEW toyEmp AS
SELECT ename, dno
FROM emp
WHERE dno = 111;
eName
Jack
Alice
Tom
Emp (ename, dno, sal)
INSERT INTO toyEmp VALUES (‘Tom’, 111);

Insert a tuple to a view:



eName
Jack
Alice
Lisa
Tom
Mary
Tom
Dno
111
111
222
333
333
??????
Not allowed: what do we insert into Emp?  view not updatable!
The system is not “smart” enough to know the value of “dno” is 111.
If we fill “dno” with “NULL,” then this view tuple cannot be generated
Sal
50K
90K
80K
70K
60K
0
Delete from Updatable Views


When deleting a tuple from a view, should delete all tuples from base
table(s) that can produce this view tuple.
Example:
DELETE FROM toyEmp
WHERE ename = ‘Jack’
toyEmp (ename, dno)
Will be translated to:
DELETE FROM Emp
WHERE ename = ‘Jack’ AND dno = 111;
eName
Jack
Alice
Dno
111
111
Emp (ename, dno, sal)
eName
Jack
Alice
Lisa
Tom
Mary
Dno
111
111
222
333
333
Sal
50K
90K
80K
70K
60K
Update Updatable Views


Will update all tuples in the base relations that produce the updated
tuples in the view
Example:
CREATE VIEW toyEmp AS
SELECT ename, dno, sal
FROM Emp
WHERE dno = 111;
toyEmp (ename, dno)
eName
Jack
Alice
UPDATE toyEmp SET sal = sal * 0.9
WHERE ename = ‘Jack’
Will be translated to:
UPDATE Emp SET sal = sal * 0.9
WHERE ename = ‘Jack’ AND dno = 111;
Dno
111
111
Sal
50K
90K
Emp (ename, dno, sal)
eName
Jack
Alice
Lisa
Tom
Mary
Dno
111
111
222
333
333
Sal
50K
90K
80K
70K
60K
Drop Views



DROP VIEW <name>;
Example: DROP VIEW toyEmp;
The base tables will NOT change.
Join Expressions in SQL



Joins can be expressed implicitly in SQL using
SELECT-FROM-WHERE clause.
Alternatively, joins can also be expressed using
join expressions.
E.g.,



relations: emp (ssn, sal, dno), dept(dno,dname)
emp CROSS JOIN dept
produces a relation with 5 attributes which is a cross product of
emp and dept.
Join Expressions in SQL
Join expressions can also be used in FROM clause
SELECT name
FROM emp JOIN dept ON emp.dno = dept.dno AND
dept.dname = ‘toy’
 Note the join expression


R JOIN S on <condition>
Other Types of Join Expressions







R
R
R
R
R
R
R
NATURAL JOIN S
NATURAL FULL OUTER JOIN S
NATURAL LEFT OUTER JOIN S
NATURAL RIGHT OUTER JOIN S
FULL OUTER JOIN S ON <condition>
LEFT OUTER JOIN S ON <condition>
RIGHT OUTER JOIN S ON <condition>
Revisit to Specifying Integrity
Constraints in SQL

We have already seen how to specify:
 primary key and uniqueness constraints
 constraint checked whenever we do insertion, or
modification to the table
 referential integrity constraints
 constraint checked whenever we do insertion, or
modification to the table, or deletion, or modification in
referred table
Constraints in SQL

Constraints on attribute values:





these are checked whenever there is insertion to table or
attribute update
not null constraint
attribute based check constraint
E.g., sex char(1) CHECK (sex IN (‘F’, ‘M’))
domain constraint
 E.g., Create domain gender-domain CHAR (1) CHECK (VALUE
IN (‘F’, ‘M’))
 define sex in schema defn to be of type gender-domain
Constraints in SQL


Constraints on tuples
Tuple based CHECK constraint:
CREATE TABLE Emp (
name CHAR(30) UNIQUE
gender CHAR(1) CHECK (gender in (‘F’, ‘M’)
age int
dno int
CHECK (age < 100 AND age > 20)
CHECK (dno IN (SELECT dno FROM dept))
)
these are checked on insertion to relation or tuple
update
Another Example of Tuple Based
Constraint
CREATE TABLE dept (
mgrname CHAR(30)
dno int
dname CHAR(20)
check (mgrname NOT IN (SELECT name
FROM emp
WHERE emp.sal < 50000))
)


If someone made a manager whose salary is less than 50K that
insertion/update to dept table will be rejected.
However, if manager’s salary reduced to less than 50K, the
corresponding update to emp table will NOT be rejected.
Attribute and Tuple Based Constraints

If refer to (attributes from) another relation then DBMS
ignores any changes to the other relations

Even if constraint condition violated
Assertions


Assertions are constraints over a table as a
whole or multiple tables.
General form:
CREATE ASSERTION <name> CHECK <cond>


An assertion must always be true at transaction
boundaries. Any modification that causes it to
become false is rejected.
Similar to tables, assertions can be dropped by a
DROP command.
Example Assertion




CREATE ASSERTION RichMGR CHECK
(NOT EXISTS
(SELECT *
FROM dept, emp
WHERE emp.name = dept.mgrname AND
emp.salary < 50000))
This assertion correctly guarantees that each manager makes more than
50000.
If someone made a manager whose salary is less than 50K that
insertion/update to dept table will be rejected.
Furthermore, if manager’s salary reduced to less than 50K, the
corresponding update to emp table will be rejected.
Different Constraint Types
Type
Where Declared
When activated
Guaranteed
to hold?
Attribute
CHECK
with attribute
on insertion
or update
not if contains
subquery
Tuple
CHECK
relation schema
insertion or
update to
relation
not if contains
subquery
Assertion
database schema
on change to
any relation
mentioned
yes !!
Giving Names to Constraints
Why give names?
- In order to be able to alter constraints.
Add the keyword CONSTRAINT and then a name:
ssn CHAR(50) CONSTRAINT ssnIsKey PRIMARY KEY
CREATE DOMAIN ssnDomain INT
CONSTRAINT ninedigits CHECK (VALUE >= 100000000
AND VALUE <= 999999999
CONSTRAINT rightage
CHECK (age >= 0 OR status = “dead”)
Altering Constraints
ALTER TABLE Product DROP CONSTRAINT positivePrice
ALTER TABLE Product ADD CONSTRAINT
positivePrice CHECK (price >= 0)
ALTER DOMAIN ssn ADD CONSTRAINT no-leading-1s
CHECK (value >= 200000000)
DROP ASSERTION assert1.
Triggers
Enable the database programmer to specify:
• when to check a constraint,
• what exactly to do.
A trigger has 3 parts:
• An event (e.g., update to an attribute)
• A condition (e.g., a query to check)
• An action (deletion, update, insertion)
When the event happens, the system will check the constraint, a
if satisfied, will perform the action.
NOTE: triggers may cause cascading effects.
Triggers not part of SQL2 but included in SQL3… however,
database vendors did not wait for standards with triggers!
Elements of Triggers (in SQL3)
• Timing of action execution
• before
• after
• instead of
…. the triggering event
• The action can refer to both the old and new state of the database.
• Update events may specify a particular column or set of columns.
• A condition is specified with a WHEN clause.
• The action can be performed either for
• once for every tuple, or
• once for all the tuples that are changed by the database operation.
Example: Row Level Trigger
CREATE TRIGGER
NoLowerPrices
AFTER UPDATE OF price ON Product
REFERENCING
OLD AS OldTuple
NEW AS NewTuple
WHEN (OldTuple.price > NewTuple.price)
UPDATE Product
SET price = OldTuple.price
WHERE name = NewTuple.name
FOR EACH ROW
Statement Level Trigger
emp(dno…), dept(dept#, …)
“Whenever we insert employees tuples, make sure that their dno’s exist in
Dept.”
CREATE TRIGGER deptExistTrig
AFTER INSERT ON emp
REFERENCING
OLD_TABLE AS OldStuff
NEW_TABLE AS NewStuff
WHEN (EXSITS (SELECT * FROM NewStuff
WHERE dno NOT IN
(SELECT dept# FROM dept)))
DELETE FROM NewStuff
WHERE dno NOT IN
(SELECT dept# FROM dept));
Bad Things Can Happen
CREATE TRIGGER Bad-trigger
AFTER UPDATE OF price IN Product
REFERENCING OLD AS OldTuple
NEW AS NewTuple
WHEN (NewTuple.price > 50)
UPDATE Product
SET price = NewTuple.price * 2
WHERE name = NewTuple.name
FOR EACH ROW
Embedded SQL
Direct SQL is rarely used: usually, SQL is embedded in some
application code.
We need some method to reference SQL statements.
But: there is an impedance mismatch problem
So: we use cursors.
Programs with SQL
Host language + Embedded SQL
Preprocessor
Preprocessor
Host Language + function calls
Host
Host language
language compiler
compiler
Host language program
The Impedance Mismatch Problem
The host language manipulates variables, values, pointers
SQL manipulates relations.
There is no construct in the host language for manipulating
relations.
Why not use only one language?
• Forgetting SQL: definitely not a good idea!
• SQL cannot do everything that the host language can do.
Interface: SQL / Host Language
Values get passed through shared variables.
Colons precede shared variables when they occur within the
SQL statements.
EXEC SQL: precedes every SQL statement in the host language.
The variable SQLSTATE provides error messages and status
reports (e.g., 00000 says that the operation completed with no
problem).
EXEC SQL BEGIN DECLARE SECTION;
char productName[30];
EXEC SQL END DECLARE SECTION;
Using Shared Variables
Void simpleInsert() {
EXEC SQL BEGIN DECLARE SECTION;
char productName[20], company[30];
char SQLSTATE[6];
EXEC SQL END DECLARE SECTION;
/* get values for productName and company
somehow */
EXEC SQL INSERT INTO Product(name, company)
VALUES (:productName, :company);
}
Single-Row Select Statements
Void getPrice() {
EXEC SQL BEGIN DECLARE SECTION;
char productName[20], company[30];
integer price;
char SQLSTATE[6];
EXEC SQL END DECLARE SECTION;
/* read value of product name */
EXEC SQL SELECT price
INTO :price
FROM Product
WHERE Product.name = :productName;
/* print out value of price */
}
Cursors
EXEC SQL DECLARE cursorName CURSOR FOR
SELECT …. FROM …. WHERE …. ;
EXEC SQL OPEN cursorName;
while (true) {
EXEC SQL FETCH FROM cursorName INTO :variables;
if (NO_MORE_TUPLES) break;
/* do something with values */
}
EXEC SQL CLOSE cursorName;
More on Cursors
• cursors can modify a relation as well as read it.
• We can determine the order in which the cursor will get
tuples by the ORDER BY keyword in the SQL query.
• Cursors can be protected against changes to the
underlying relations.
• The cursor can be a scrolling one: can go forward, backward
+n, -n, Abs(n), Abs(-n).
Dynamic SQL





So far we have only considered embedding ‘static’ SQL in programming
languages.
Static SQL embedding is fine for fixed applications when we wish to
execute a specific SQL query from a programming language, e.g., a
program that is used by a sales clerk to book an airline seat.
What if the SQL query that we wish to embed is itself not known in
advance at compile time?
For example, the code that implements dbaccess takes a user query at
run time and submits it to the database.
Dynamic SQL allows for the query to be specified at run-time
Dynamic SQL (II)

Two special statements of embedded SQL:


PREPARE turns a character string into an SQL query.
EXECUTE executes that query.
Example
Usage
 EXEC SQL BEGIN DECLARE

SECTION;
char query[MAX_QUERY_LENGTH];
EXEC SQL END DECLARE SECTION;
/* read user's text into array query */
EXEC SQL PREPARE q FROM :query;
EXEC SQL EXECUTE q;
/* program that reads an SQL query and
executes it */
Example Usage (II)


Once prepared, a query can be executed many times.
Alternatively, PREPARE and EXECUTE can be combined
into:
EXEC SQL EXECUTE IMMEDIATE :query;
Descargar

SQL Introduction