Title: Remaining Topics in SQL to be covered
1Remaining Topics in SQL to be covered
- NULL values in SQL
- Outer joins in SQL
- Constraints and Triggers in SQL
- Embedded SQL.
2Nulls in SQL
- SQL supports a special value -- NULL in place of
a value in a tuple's component - Nulls 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)
3Need for Care in Using Nulls...
- Using nulls for missing values may result in loss
of information
- 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!
4Sometimes Nulls very useful even if possible to
avoid them
- 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.
5Interpreting 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 gt 3 results in UNKNOWN, if x is Null
6Interpreting 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?
73-Valued Logic
- Think of true 1 false 0, and unknown 1/2.
- Then AND min. OR max. NOT(x) 1 - x
8Truth Table
T true F false U unknown
9SQL constraints, assertions, triggers
10Some 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.
11Example
Bar beer price Joe's bar Bud NULL
SELECT bar FROM Sells Where price lt 2.00 OR price
gt 2.00 UNKNOWN UNKNOWN
UNKNOWN
12Modifying 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
13Updatable 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
Emp (ename, dno, sal)
INSERT INTO toyEmp VALUES (Tom, 111)
- Insert a tuple to a view
- 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.
14Non-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
Emp (ename, dno, sal)
INSERT INTO toyEmp VALUES (Tom, 111)
- Insert a tuple to a view
- 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
15Delete 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
- Will be translated to
- DELETE FROM Emp
- WHERE ename Jack AND dno 111
toyEmp (ename, dno)
Emp (ename, dno, sal)
16Update 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
- 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
toyEmp (ename, dno)
Emp (ename, dno, sal)
17Drop Views
- DROP VIEW ltnamegt
- Example DROP VIEW toyEmp
- The base tables will NOT change.
18Join 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.
19Join 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 ltconditiongt
20Other Types of Join Expressions
- R NATURAL JOIN S
- R NATURAL FULL OUTER JOIN S
- R NATURAL LEFT OUTER JOIN S
- R NATURAL RIGHT OUTER JOIN S
- R FULL OUTER JOIN S ON ltconditiongt
- R LEFT OUTER JOIN S ON ltconditiongt
- R RIGHT OUTER JOIN S ON ltconditiongt
21Revisit 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
22Constraints 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
23Constraints 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 lt 100 AND age gt 20)
- CHECK (dno IN (SELECT dno FROM dept))
- )
- these are checked on insertion to relation or
tuple update
24Another 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 lt 50000))
- )
- If someone made a manager whose salary is less
than 50K that insertion/update to dept table will
be rejected. - However, if managers salary reduced to less than
50K, the corresponding update to emp table will
NOT be rejected.
25Attribute 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
26Assertions
- Assertions are constraints over a table as a
whole or multiple tables. - General form
- CREATE ASSERTION ltnamegt CHECK ltcondgt
- 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.
27Example Assertion
- CREATE ASSERTION RichMGR CHECK
- (NOT EXISTS
- (SELECT
- FROM dept, emp
- WHERE emp.name dept.mgrname AND
- emp.salary lt 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 managers salary reduced to less
than 50K, the corresponding update to emp table
will be rejected.
28Different Constraint Types
Type Where Declared When
activated Guaranteed
to hold? Attribute with attribute
on insertion not if contains CHECK
or update
subquery Tuple relation
schema insertion or not if
contains CHECK
update to subquery
relation Assertion database schema
on change to yes !!
any relation
mentioned
29Giving 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 gt
100000000
AND VALUE lt 999999999 CONSTRAINT
rightage CHECK (age gt 0 OR status
dead)
30Altering Constraints
ALTER TABLE Product DROP CONSTRAINT
positivePrice ALTER TABLE Product ADD
CONSTRAINT positivePrice CHECK (price gt
0) ALTER DOMAIN ssn ADD CONSTRAINT
no-leading-1s CHECK (value gt
200000000) DROP ASSERTION assert1.
31Triggers
- 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, and - 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!
32Elements 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.
33Example Row Level Trigger
CREATE TRIGGER NoLowerPrices AFTER UPDATE OF
price ON Product REFERENCING OLD AS
OldTuple NEW AS NewTuple WHEN
(OldTuple.price gt NewTuple.price) UPDATE
Product SET price OldTuple.price
WHERE name NewTuple.name FOR EACH ROW
34Statement Level Trigger
emp(dno), dept(dept, ) Whenever we insert
employees tuples, make sure that their dnos
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))
35Bad Things Can Happen
CREATE TRIGGER Bad-trigger AFTER UPDATE OF
price IN Product REFERENCING OLD AS OldTuple
NEW AS NewTuple WHEN
(NewTuple.price gt 50) UPDATE Product
SET price NewTuple.price 2
WHERE name NewTuple.name FOR EACH ROW
36Embedded 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.
37Programs with SQL
Host language Embedded SQL
Preprocessor
Preprocessor
Host Language function calls
Host language compiler
Host language compiler
Host language program
38The 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.
39Interface 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 productName30 EXEC SQL
END DECLARE SECTION
40Using Shared Variables
Void simpleInsert() EXEC SQL BEGIN
DECLARE SECTION char
productName20, company30 char
SQLSTATE6 EXEC SQL END DECLARE
SECTION / get values for
productName and company somehow
/ EXEC SQL INSERT INTO Product(name,
company) VALUES (productName,
company)
41Single-Row Select Statements
Void getPrice() EXEC SQL BEGIN DECLARE
SECTION char productName20,
company30 integer price
char SQLSTATE6 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 /
42Cursors
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
43More 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).
44Dynamic 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
45Dynamic SQL (II)
- Two special statements of embedded SQL
- PREPARE turns a character string into an SQL
query. - EXECUTE executes that query.
46Example Usage
- EXEC SQL BEGIN DECLARE SECTION char
queryMAX_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 /
47Example Usage (II)
- Once prepared, a query can be executed many
times. - Alternatively, PREPARE and EXECUTE can be
combined into EXEC SQL EXECUTE IMMEDIATE
query