39
Remaining Topics in SQL to be covered… NULL values in SQL Outer joins in SQL Constraints and Triggers in SQL Embedded SQL.

Remaining Topics in SQL to be covered…

  • Upload
    travis

  • View
    26

  • Download
    0

Embed Size (px)

DESCRIPTION

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 -- - PowerPoint PPT Presentation

Citation preview

Page 1: Remaining Topics  in SQL to be covered…

Remaining Topics in SQL to be covered…

NULL values in SQLOuter joins in SQLConstraints and Triggers in SQLEmbedded SQL.

Page 2: Remaining Topics  in SQL to be covered…

Null’s in SQLSQL 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)

Cs184projects

student proj title date

boris null null

stefan null null

Page 3: Remaining Topics  in SQL to be covered…

Need for Care in using Nulls...

Using nulls for missing values may result in loss of information

Cs184projects

student proj title date

boris oodb 11/16/95

stefan oodb 11/16/95

monica par dbms 11/21/95

Cs184projects

student proj title date

boris null null

stefan null null

monica null null

•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!

Page 4: Remaining Topics  in SQL to be covered…

Sometimes Nulls very useful even if possible to avoid them…

office relation

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

Page 5: Remaining Topics  in SQL to be covered…

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

Page 6: Remaining Topics  in SQL to be covered…

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 -- UNKNOWNHow to interpret the logical operators in this case?

Page 7: Remaining Topics  in SQL to be covered…

3-Valued LogicThink of true = 1; false = 0, and unknown = 1/2.Then: AND = min. OR = max. NOT(x) = 1 - x

Page 8: Remaining Topics  in SQL to be covered…

Truth TableX Y X AND y X OR Y NOT X T T T T F T U U T F T F F T F U T U T U U U U U U U F F U U F T F T T F U F U T F F F F T

T = true F = false U = unknown

Page 9: Remaining Topics  in SQL to be covered…

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.

Page 10: Remaining Topics  in SQL to be covered…

Example

Bar beer price

Joe's bar Bud NULL

SELECT barFROM SellsWhere price < 2.00 OR price >= 2.00 UNKNOWN UNKNOWN UNKNOWN

Page 11: Remaining Topics  in SQL to be covered…

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.

Page 12: Remaining Topics  in SQL to be covered…

Join Expressions in SQL

Join expressions can also be used in FROM clause

SELECT nameFROM emp JOIN dept ON emp.dno =

dept.dno AND dept.dname = ‘toy’Note the join expression R JOIN S on <condition>

Page 13: Remaining Topics  in SQL to be covered…

Other Types of Join Expressions

R NATURAL JOIN SR NATURAL FULL OUTER JOIN SR NATURAL LEFT OUTER JOIN SR NATURAL RIGHT OUTER JOIN SR FULL OUTER JOIN S ON <condition>R LEFT OUTER JOIN S ON <condition>R RIGHT OUTER JOIN S ON <condition>

Page 14: Remaining Topics  in SQL to be covered…

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

Page 15: Remaining Topics  in SQL to be covered…

Constraints in SQLconstraints 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

Page 16: Remaining Topics  in SQL to be covered…

Constraints in SQLTuple Based CHECK contraint:CREATE TABLE Emp (name CHAR(30) UNIQUEgender CHAR(1) CHECK (gender in (‘F’, ‘M’)age intdno intCHECK (age < 100 AND age > 20)CHECK (dno IN (SELECT dno FROM dept)))

these are checked on insertion to relation or tuple update

Page 17: Remaining Topics  in SQL to be covered…

Another Example of Tuple Based Constraint

CREATE TABLE dept (mgrname CHAR(30)dno intdname 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.

Page 18: Remaining Topics  in SQL to be covered…

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

Page 19: Remaining Topics  in SQL to be covered…

Example Assertion

CREATE ASSERTION RichMGR CHECK(NOT EXISTS

(SELECT *FROM dept, empWHERE 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.

Page 20: Remaining Topics  in SQL to be covered…

Different Constraint Types

Type Where Declared When activated Guaranteed to hold?

Attribute with attribute on insertion not if containsCHECK or update subquery

Tuple relation schema insertion or not if containsCHECK update to subquery relation

Assertion database schema on change to Yes any relation mentioned

Page 21: Remaining Topics  in SQL to be covered…

Giving Names to ConstraintsWhy 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”)

Page 22: Remaining Topics  in SQL to be covered…

Altering ConstraintsALTER 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.

Page 23: Remaining Topics  in SQL to be covered…

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, 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!

Page 24: Remaining Topics  in SQL to be covered…

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

Page 25: Remaining Topics  in SQL to be covered…

Example: Row Level Trigger

CREATE TRIGGER NoLowerPrices

AFTER UPDATE OF price ON ProductREFERENCING OLD AS OldTuple NEW AS NewTupleWHEN (OldTuple.price > NewTuple.price) UPDATE Product SET price = OldTuple.price WHERE name = NewTuple.name

FOR EACH ROW

Page 26: Remaining Topics  in SQL to be covered…

Statement Level Trigger CREATE TRIGGER average-price-preserveINSTEAD OF UPDATE OF price ON Product

REFERENCING OLD_TABLE AS OldStuff NEW_TABLE AS NewStuffWHEN (1000 < (SELECT AVG (price) FROM ((Product EXCEPT OldStuff) UNION NewStuff))DELETE FROM Product WHERE (name, price, company) IN OldStuff;INSERT INTO NewStuff (SELECT * FROM NewStuff)

Page 27: Remaining Topics  in SQL to be covered…

Bad Things Can HappenCREATE TRIGGER Bad-trigger

AFTER UPDATE OF price IN ProductREFERENCING OLD AS OldTuple NEW AS NewTuple

WHEN (NewTuple.price > 50)

UPDATE Product SET price = NewTuple.price * 2 WHERE name = NewTuple.name

FOR EACH ROW

Page 28: Remaining Topics  in SQL to be covered…

Embedded SQL Direct SQL is rarely used: usually, SQL is embedded in someapplication code.

We need some method to reference SQL statements.

But: there is an impedance mismatch problem

So: we use cursors.

Page 29: Remaining Topics  in SQL to be covered…

Programs with SQL

Host language + Embedded SQL

Preprocessor

Host Language + function calls

Host language compiler

Host language program

Preprocessor

Host language compiler

Page 30: Remaining Topics  in SQL to be covered…

The Impedance Mismatch ProblemThe 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.

Page 31: Remaining Topics  in SQL to be covered…

Interface: SQL / Host LanguageValues 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 noproblem).

EXEC SQL BEGIN DECLARE SECTION; char productName[30];EXEC SQL END DECLARE SECTION;

Page 32: Remaining Topics  in SQL to be covered…

Using Shared VariablesVoid 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); }

Page 33: Remaining Topics  in SQL to be covered…

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 */ }

Page 34: Remaining Topics  in SQL to be covered…

CursorsEXEC 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;

Page 35: Remaining Topics  in SQL to be covered…

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

Page 36: Remaining Topics  in SQL to be covered…

Dynamic SQLSo 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

Page 37: Remaining Topics  in SQL to be covered…

Dynamic SQL (II)Two special statements of embedded SQL: PREPARE turns a character string into

an SQL query. EXECUTE executes that query.

Page 38: Remaining Topics  in SQL to be covered…

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 */

Page 39: Remaining Topics  in SQL to be covered…

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;