390 likes | 401 Views
This article covers the remaining essential topics in SQL, including NULL values, outer joins, constraints, triggers, and embedded SQL. Learn how to use and interpret NULL values, handle missing information, and specify integrity constraints in SQL. Explore various types of joins and understand how to express join expressions. Discover how to create constraints on attribute values and use assertions to enforce constraints on tables.
E N D
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)
Need 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!
Sometimes 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.
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 T = true F = false U = unknown
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
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 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 <condition> • R LEFT OUTER JOIN S ON <condition> • R 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 • 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 < 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.
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 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
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, 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!
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.
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 CREATE TRIGGER average-price-preserve INSTEAD OF UPDATE OF price ON Product REFERENCING OLD_TABLE AS OldStuff NEW_TABLE AS NewStuff WHEN (1000 < (SELECT AVG (price) FROM ((Product EXCEPT OldStuff) UNION NewStuff)) DELETE FROM Product WHERE (name, price, company) IN OldStuff; INSERTINTO NewStuff (SELECT * FROM NewStuff)
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 language compiler Host language 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 SQLBEGIN DECLARE SECTION; char productName[30]; EXEC SQLEND 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;