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
9Some 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.
10Example
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
11Join 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.
12Join 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
13Other 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
14Revisit 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
15Constraints 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
16Constraints in SQL
- Tuple Based CHECK contraint
- 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
17Another 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.
18Assertions
- 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.
19Example 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.
20Different 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
21Giving 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)
22Altering 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.
23Triggers
- 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!
24Elements of Triggers (in SQL3)
- Timing of action execution before, after or
instead of 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.
25Example 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
26Statement Level Trigger
CREATE TRIGGER average-price-preserve INSTEAD OF
UPDATE OF price ON Product REFERENCING
OLD_TABLE AS OldStuff NEW_TABLE AS
NewStuff WHEN (1000 lt (SELECT AVG
(price) FROM ((Product EXCEPT OldStuff)
UNION NewStuff)) DELETE FROM Product
WHERE (name, price, company) IN
OldStuff INSERT INTO NewStuff (SELECT FROM
NewStuff)
27Bad 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
28Embedded 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.
29Programs with SQL
Host language Embedded SQL
Preprocessor
Preprocessor
Host Language function calls
Host language compiler
Host language compiler
Host language program
30The 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.
31Interface 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
32Using 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)
33Single-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 /
34Cursors
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
35More 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).
36Dynamic 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
37Dynamic SQL (II)
- Two special statements of embedded SQL
- PREPARE turns a character string into an SQL
query. - EXECUTE executes that query.
38Example 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 /
39Example Usage (II)
- Once prepared, a query can be executed many
times. - Alternatively, PREPARE and EXECUTE can be
combined into EXEC SQL EXECUTE IMMEDIATE
query