Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 10: Dr. Taysir Hassan Abdel Hamid May 11, 2014.

Similar presentations


Presentation on theme: "Lecture 10: Dr. Taysir Hassan Abdel Hamid May 11, 2014."— Presentation transcript:

1 Lecture 10: Dr. Taysir Hassan Abdel Hamid May 11, 2014

2 Outline Relational Algebra Data Control Language (DCL) JDBC

3 Slide 6- 3 Chapter Outline Relational Algebra –Unary Relational Operations –Relational Algebra Operations From Set Theory –Binary Relational Operations –Additional Relational Operations

4 Slide 6- 4 Relational Algebra Overview Relational algebra is the basic set of operations for the relational model These operations enable a user to specify basic retrieval requests (or queries) The result of an operation is a new relation, which may have been formed from one or more input relations –This property makes the algebra “closed” (all objects in relational algebra are relations)

5 Slide 6- 5 Relational Algebra Overview (continued) The algebra operations thus produce new relations –These can be further manipulated using operations of the same algebra A sequence of relational algebra operations forms a relational algebra expression –The result of a relational algebra expression is also a relation that represents the result of a database query (or retrieval request)

6 Slide 6- 6 Relational Algebra Overview Relational Algebra consists of several groups of operations –Unary Relational Operations SELECT (symbol:  (sigma)) PROJECT (symbol:  (pi)) RENAME (symbol:  (rho)) –Relational Algebra Operations From Set Theory UNION (  ), INTERSECTION (  ), DIFFERENCE (or MINUS, – ) –Binary Relational Operations JOIN (several variations of JOIN exist) –Additional Relational Operations AGGREGATE FUNCTIONS (These compute summary of information: for example, SUM, COUNT, AVG, MIN, MAX)

7 Slide 6- 7 Database State for COMPANY All examples discussed below refer to the COMPANY database shown here.

8 Slide 6- 8 Unary Relational Operations: SELECT The SELECT operation (denoted by  (sigma)) is used to select a subset of the tuples from a relation based on a selection condition. –The selection condition acts as a filter –Keeps only those tuples that satisfy the qualifying condition –Tuples satisfying the condition are selected whereas the other tuples are discarded (filtered out) Examples: –Select the EMPLOYEE tuples whose department number is 4:  DNO = 4 (EMPLOYEE) –Select the employee tuples whose salary is greater than $30,000:  SALARY > 30,000 (EMPLOYEE)

9 Slide 6- 9 Unary Relational Operations: SELECT –In general, the select operation is denoted by  (R) where the symbol  (sigma) is used to denote the select operator the selection condition is a Boolean (conditional) expression specified on the attributes of relation R tuples that make the condition true are selected –appear in the result of the operation tuples that make the condition false are filtered out –discarded from the result of the operation

10 Slide 6- 10 Unary Relational Operations: SELECT (contd.) SELECT Operation Properties –The SELECT operation  (R) produces a relation S that has the same schema (same attributes) as R –SELECT  is commutative:  (  (R)) =  (  (R)) –Because of commutativity property, a cascade (sequence) of SELECT operations may be applied in any order:  (  (  (R)) =  (  (  ( R))) –A cascade of SELECT operations may be replaced by a single selection with a conjunction of all the conditions:  (  (  (R)) =  AND AND (R))) –The number of tuples in the result of a SELECT is less than (or equal to) the number of tuples in the input relation R

11 Slide 6- 11 The following query results refer to this database state

12 Slide 6- 12 Unary Relational Operations: PROJECT PROJECT Operation is denoted by  (pi) This operation keeps certain columns (attributes) from a relation and discards the other columns. –PROJECT creates a vertical partitioning The list of specified columns (attributes) is kept in each tuple The other attributes in each tuple are discarded Example: To list each employee’s first and last name and salary, the following is used:  LNAME, FNAME,SALARY (EMPLOYEE)

13 Slide 6- 13 Unary Relational Operations: PROJECT (cont.) The general form of the project operation is:  (R) –  (pi) is the symbol used to represent the project operation – is the desired list of attributes from relation R. The project operation removes any duplicate tuples –This is because the result of the project operation must be a set of tuples Mathematical sets do not allow duplicate elements.

14 Slide 6- 14 Unary Relational Operations: PROJECT (contd.) PROJECT Operation Properties –The number of tuples in the result of projection  (R) is always less or equal to the number of tuples in R If the list of attributes includes a key of R, then the number of tuples in the result of PROJECT is equal to the number of tuples in R –PROJECT is not commutative  (  (R) ) =  (R) as long as contains the attributes in

15 Slide 6- 15 Examples of applying SELECT and PROJECT operations

16 Slide 6- 16 Relational Algebra Expressions We may want to apply several relational algebra operations one after the other –Either we can write the operations as a single relational algebra expression by nesting the operations, or –We can apply one operation at a time and create intermediate result relations. In the latter case, we must give names to the relations that hold the intermediate results.

17 Slide 6- 17 Single expression versus sequence of relational operations (Example) To retrieve the first name, last name, and salary of all employees who work in department number 5, we must apply a select and a project operation We can write a single relational algebra expression as follows: –  FNAME, LNAME, SALARY (  DNO=5 (EMPLOYEE)) OR We can explicitly show the sequence of operations, giving a name to each intermediate relation: –DEP5_EMPS   DNO=5 (EMPLOYEE) –RESULT   FNAME, LNAME, SALARY (DEP5_EMPS)

18 Slide 6- 18 Unary Relational Operations: RENAME The RENAME operator is denoted by  (rho) In some cases, we may want to rename the attributes of a relation or the relation name or both –Useful when a query requires multiple operations –Necessary in some cases (see JOIN operation later)

19 Slide 6- 19 Unary Relational Operations: RENAME (contd.) The general RENAME operation  can be expressed by any of the following forms: –  S (B1, B2, …, Bn ) (R) changes both: the relation name to S, and the column (attribute) names to B1, B1, …..Bn –  S (R) changes: the relation name only to S –  (B1, B2, …, Bn ) (R) changes: the column (attribute) names only to B1, B1, …..Bn

20 Slide 6- 20 Unary Relational Operations: RENAME (contd.) For convenience, we also use a shorthand for renaming attributes in an intermediate relation: –If we write: RESULT   FNAME, LNAME, SALARY (DEP5_EMPS) RESULT will have the same attribute names as DEP5_EMPS (same attributes as EMPLOYEE) If we write: RESULT (F, M, L, S, B, A, SX, SAL, SU, DNO)   FNAME, LNAME, SALARY (DEP5_EMPS) The 10 attributes of DEP5_EMPS are renamed to F, M, L, S, B, A, SX, SAL, SU, DNO, respectively

21 Slide 6- 21 Example of applying multiple operations and RENAME

22 Slide 6- 22 Relational Algebra Operations from Set Theory: UNION UNION Operation –Binary operation, denoted by  –The result of R  S, is a relation that includes all tuples that are either in R or in S or in both R and S –Duplicate tuples are eliminated –The two operand relations R and S must be “type compatible” (or UNION compatible) R and S must have same number of attributes Each pair of corresponding attributes must be type compatible (have same or compatible domains)

23 Slide 6- 23 Relational Algebra Operations from Set Theory: UNION Example: –To retrieve the social security numbers of all employees who either work in department 5 (RESULT1 below) or directly supervise an employee who works in department 5 (RESULT2 below) –We can use the UNION operation as follows: DEP5_EMPS   DNO=5 (EMPLOYEE) RESULT1   SSN (DEP5_EMPS) RESULT2(SSN)   SUPERSSN (DEP5_EMPS) RESULT  RESULT1  RESULT2 –The union operation produces the tuples that are in either RESULT1 or RESULT2 or both

24 Slide 6- 24 Example of the result of a UNION operation UNION Example

25 Slide 6- 25 Relational Algebra Operations from Set Theory Type Compatibility of operands is required for the binary set operation UNION , (also for INTERSECTION , and SET DIFFERENCE –, see next slides) R1(A1, A2,..., An) and R2(B1, B2,..., Bn) are type compatible if: –they have the same number of attributes, and –the domains of corresponding attributes are type compatible (i.e. dom(Ai)=dom(Bi) for i=1, 2,..., n). The resulting relation for R1  R2 (also for R1  R2, or R1– R2, see next slides) has the same attribute names as the first operand relation R1 (by convention)

26 Slide 6- 26 Relational Algebra Operations from Set Theory: INTERSECTION INTERSECTION is denoted by  The result of the operation R  S, is a relation that includes all tuples that are in both R and S –The attribute names in the result will be the same as the attribute names in R The two operand relations R and S must be “type compatible”

27 Slide 6- 27 Relational Algebra Operations from Set Theory: SET DIFFERENCE (cont.) SET DIFFERENCE (also called MINUS or EXCEPT) is denoted by – The result of R – S, is a relation that includes all tuples that are in R but not in S –The attribute names in the result will be the same as the attribute names in R The two operand relations R and S must be “type compatible”

28 Slide 6- 28 Example to illustrate the result of UNION, INTERSECT, and DIFFERENCE

29 Slide 6- 29 Some properties of UNION, INTERSECT, and DIFFERENCE Notice that both union and intersection are commutative operations; that is –R  S = S  R, and R  S = S  R Both union and intersection can be treated as n-ary operations applicable to any number of relations as both are associative operations; that is –R  (S  T) = (R  S)  T –(R  S)  T = R  (S  T) The minus operation is not commutative; that is, in general –R – S ≠ S – R

30 Slide 6- 30 Binary Relational Operations: JOIN JOIN Operation (denoted by ) –The sequence of CARTESIAN PRODECT followed by SELECT is used quite commonly to identify and select related tuples from two relations –A special operation, called JOIN combines this sequence into a single operation –This operation is very important for any relational database with more than a single relation, because it allows us combine related tuples from various relations –The general form of a join operation on two relations R(A1, A2,..., An) and S(B1, B2,..., Bm) is: R S –where R and S can be any relations that result from general relational algebra expressions.

31 Slide 6- 31 Binary Relational Operations: JOIN (cont.) Example: Suppose that we want to retrieve the name of the manager of each department. –To get the manager’s name, we need to combine each DEPARTMENT tuple with the EMPLOYEE tuple whose SSN value matches the MGRSSN value in the department tuple. –We do this by using the join operation. –DEPT_MGR  DEPARTMENT MGRSSN=SSN EMPLOYEE MGRSSN=SSN is the join condition –Combines each department record with the employee who manages the department –The join condition can also be specified as DEPARTMENT.MGRSSN= EMPLOYEE.SSN

32 Slide 6- 32 Example of applying the JOIN operation

33 Slide 6- 33 Binary Relational Operations: EQUIJOIN EQUIJOIN Operation The most common use of join involves join conditions with equality comparisons only Such a join, where the only comparison operator used is =, is called an EQUIJOIN. –In the result of an EQUIJOIN we always have one or more pairs of attributes (whose names need not be identical) that have identical values in every tuple. –The JOIN seen in the previous example was an EQUIJOIN.

34 Slide 6- 34 Binary Relational Operations: NATURAL JOIN Operation NATURAL JOIN Operation –Another variation of JOIN called NATURAL JOIN — denoted by * — was created to get rid of the second (superfluous) attribute in an EQUIJOIN condition. because one of each pair of attributes with identical values is superfluous –The standard definition of natural join requires that the two join attributes, or each pair of corresponding join attributes, have the same name in both relations –If this is not the case, a renaming operation is applied first.

35 Slide 6- 35 Example of NATURAL JOIN operation

36 Slide 6- 36 Complete Set of Relational Operations The set of operations including SELECT , PROJECT , UNION , DIFFERENCE , RENAME , and CARTESIAN PRODUCT X is called a complete set because any other relational algebra expression can be expressed by a combination of these five operations. For example: –R  S = (R  S ) – ((R  S)  (S  R)) –R S =  (R X S)

37 Slide 6- 37 Recap of Relational Algebra Operations

38 Slide 6- 38 Additional Relational Operations: Aggregate Functions and Grouping A type of request that cannot be expressed in the basic relational algebra is to specify mathematical aggregate functions on collections of values from the database. Examples of such functions include retrieving the average or total salary of all employees or the total number of employee tuples. –These functions are used in simple statistical queries that summarize information from the database tuples. Common functions applied to collections of numeric values include –SUM, AVERAGE, MAXIMUM, and MINIMUM. The COUNT function is used for counting tuples or values.

39 Slide 6- 39 Aggregate Function Operation Use of the Aggregate Functional operation ℱ – ℱ MAX Salary (EMPLOYEE) retrieves the maximum salary value from the EMPLOYEE relation – ℱ MIN Salary (EMPLOYEE) retrieves the minimum Salary value from the EMPLOYEE relation – ℱ SUM Salary (EMPLOYEE) retrieves the sum of the Salary from the EMPLOYEE relation – ℱ COUNT SSN, AVERAGE Salary (EMPLOYEE) computes the count (number) of employees and their average salary Note: count just counts the number of rows, without removing duplicates

40 Slide 6- 40 Using Grouping with Aggregation The previous examples all summarized one or more attributes for a set of tuples –Maximum Salary or Count (number of) Ssn Grouping can be combined with Aggregate Functions Example: For each department, retrieve the DNO, COUNT SSN, and AVERAGE SALARY A variation of aggregate operation ℱ allows this: –Grouping attribute placed to left of symbol –Aggregate functions to right of symbol – DNO ℱ COUNT SSN, AVERAGE Salary (EMPLOYEE) Above operation groups employees by DNO (department number) and computes the count of employees and average salary per department

41 Slide 6- 41 Examples of applying aggregate functions and grouping

42 Slide 6- 42 Illustrating aggregate functions and grouping

43 Slide 6- 43 Additional Relational Operations (cont.) Recursive Closure Operations –Another type of operation that, in general, cannot be specified in the basic original relational algebra is recursive closure. This operation is applied to a recursive relationship. –An example of a recursive operation is to retrieve all SUPERVISEES of an EMPLOYEE e at all levels — that is, all EMPLOYEE e’ directly supervised by e; all employees e’’ directly supervised by each employee e’; all employees e’’’ directly supervised by each employee e’’; and so on.

44 Slide 6- 44 Additional Relational Operations (cont.) Although it is possible to retrieve employees at each level and then take their union, we cannot, in general, specify a query such as “retrieve the supervisees of ‘James Borg’ at all levels” without utilizing a looping mechanism. –The SQL3 standard includes syntax for recursive closure.

45 Slide 6- 45 Additional Relational Operations (cont.)

46 Slide 6- 46 Examples of Queries in Relational Algebra Q1: Retrieve the name and address of all employees who work for the ‘Research’ department. RESEARCH_DEPT   DNAME=’Research’ (DEPARTMENT) RESEARCH_EMPS  (RESEARCH_DEPT DNUMBER= DNOEMPLOYEE EMPLOYEE) RESULT   FNAME, LNAME, ADDRESS (RESEARCH_EMPS) Q6: Retrieve the names of employees who have no dependents. ALL_EMPS   SSN (EMPLOYEE) EMPS_WITH_DEPS ( SSN )   ESSN ( DEPENDENT ) EMPS_WITHOUT_DEPS  (ALL_EMPS - EMPS_WITH_DEPS) RESULT   LNAME, FNAME (EMPS_WITHOUT_DEPS * EMPLOYEE)

47 Data Control Language (DCL)

48 Sub-sets of SQL Data Manipulation Language (DML): INSERT, UPDATE, DELETE, SELECT Data Definition Language (DDL): CREATE, ALTER, DROP, RENAME Data Control Language (DCL): GRANT, REVOKE 48

49 Introduction to DB Security Secrecy: Users shouldn’t be able to see things they are not supposed to. –E.g., A student can’t see other students’ grades. Integrity: Users shouldn’t be able to modify things they are not supposed to. –E.g., Only instructors can assign grades. Availability: Users should be able to see and modify things they are allowed to.

50 GRANT Command GRANT privileges ON object TO users [WITH GRANT OPTION] The following privileges can be specified: –SELECT Can read all columns including those added later via ALTER TABLE command –INSERT(column-name) Can insert tuples with non-null or nondefault values in this column. –INSERT means same right with respect to all columns. –DELETE Can delete tuples. –REFERENCES (column-name) Can define foreign keys (in other tables) that refer to this column. If you want the recipient(s) to be able to pass the privilege(s) to others add: WITH GRANT OPTION

51 Grant Example I Suppose Joe has created the tables –Sailors(sid, sname, rating, age) –Boats(bid, bname, color) –Reserves(sid, bid, day) Joe now executes the following: GRANT INSERT, DELETE ON Reserves TO Omar WITH GRANT OPTION; Omar can now insert or delete Reserves rows and authorize someone else to do the same.

52 Grant Example II Joe further executes: GRANT SELECT ON Reserves TO Michael; GRANT SELECT ON Sailors TO Michael WITH GRANT OPTION; Michael can now execute SELECT queries on Sailors and Reserves, and he can pass this privilege to others for Sailors but not for Reserves.

53 Grant Example II With the SELECT privilege, Michael can create a view that accesses the Sailors and Reserves tables, for example, the ActiveSailors view: CREATE VIEW ActiveSailors (name,age,day) AS SELECT S.sname, S.age, R.day FROM Sailors S, Reserves R WHERE S.sid = R.sid AND S.rating > 6; However, Michael cannot grant SELECT on ActiveSailors to others. Why? A user who creates a view has precisely those privileges on the view that he has on every one of the views or base tables used to define the view. –Since Michael doesn't have a privilege to grant SELECT on Reserves he can't grant SELECT on ActiveSailors.

54 Grant Example III On the other hand, suppose that Michael creates the following view: CREATE VIEW YoungSailors (sid, age, rating) AS SELECT S.sid, S.age, S.rating FROM Sailors S WHERE S.age < 18; The only underlying table is Sailors, for which Michael has SELECT with grant option. Therefore he can pass this on to Adel and Ahmed: GRANT SELECT ON YoungSailors TO Adel,Ahmed;

55 Grant Example III Eric and Guppy can now execute SELECT queries on view YoungSailors. –Note, however, that Adel and Ahmed don’t have the right to execute SELECT queries directly on the underlying Sailor table.

56 Grant Example IV Suppose now Joe executes: GRANT UPDATE (rating) ON Sailors TO Leah; Leah can update only the rating column of Sailors. E.g. UPDATE Sailors S SET S.rating = 8;

57 Role-Based Authorization Privileges can also be assigned to roles. Roles can then be granted to users and to other roles. Reflects how real organizations work. Example. CREATE ROLE some_role; GRANT SELECT ON Reserves TO some_role; GRANT INSERT ON Sailors TO some_role; GRANT UPDATE ON Boats TO some_role; GRANT some_role TO Michael; GRANT some_role TO Bill;

58 Revoke Example I REVOKE [GRANT OPTION FOR] privileges ON object FROM users {RESTRICT | CASCADE} Suppose Joe is the creator of Sailors. GRANT SELECT ON Sailors TO Art WITH GRANT OPTION (executed by Joe) GRANT SELECT ON Sailors TO Bob WITH GRANT OPTION (executed by Art) REVOKE SELECT ON Sailors FROM Art CASCADE (executed by Joe)

59 Revoke Example II Art loses the SELECT privilege on Sailors. Then Bob, who received this privilege from Art, and only Art, also loses this privilege. –Bob’s privilege is said to be abandoned When CASCADE is specified, all abandoned privileges are also revoked –Possibly causing privileges held by other users to become abandoned and thereby revoked recursively. If the RESTRICT keyword is specified, the command is rejected if revoking privileges causes other privileges becoming abandoned.

60 Revoke Example III Joe executes: GRANT SELECT ON Sailors TO Art WITH GRANT OPTION Joe executes: GRANT SELECT ON Sailors TO Bob WITH GRANT OPTION Art executes: GRANT SELECT ON Sailors TO Bob WITH GRANT OPTION Joe executes: REVOKE SELECT ON Sailors FROM Art CASCADE As before, Art loses the SELECT privilege on Sailors. But what about Bob? Bob received this privilege from Art, but he also received it independently from Joe. So, he doesn’t lose the privilege.

61 Revoke Example IV Joe executes: GRANT SELECT ON Sailors TO Art WITH GRANT OPTION REVOKE SELECT ON Sailors FROM Art CASCADE Since Joe granted the privilege to Art twice and only revoked it once, does Art get to keep the privilege? As per the SQL, NO. It doesn’t matter how many times we grant a privilege.

62 Privilege Descriptors When a GRANT is executed, a privilege descriptor is added to a table of such descriptors maintained by the DBMS. The privilege descriptor specifies the: –grantor of the privilege, –grantee who receives the privilege, –granted privilege –grant option When a user creates a table or view he 'automatically' gets privileges, –A privilege descriptor with system as the grantor is entered into the descriptors table.

63 Authorization Graphs Nodes are users. Arcs indicate how privileges are passed. GRANT SELECT ON Sailors TO Art WITH GRANT OPTION (executed by Joe) GRANT SELECT ON Sailors TO Bob WITH GRANT OPTION (executed by Art) GRANT SELECT ON Sailors TO Art WITH GRANT OPTION (executed by Bob) GRANT SELECT ON Sailors TO Cal WITH GRANT OPTION (executed by Joe) GRANT SELECT ON Sailors TO Bob WITH GRANT OPTION (executed by Cal)

64 14-64 JDBC JDBC is an alternative to ODBC that provides database access to programs written in Java. JDBC is not an acronym — it doesn’t stand for anything! JDBC drivers are available for most DBMS products: –http://java.sun.com/products/jdbchttp://java.sun.com/products/jdbc

65 14-65 JDBC Driver Types

66 14-66 JDBC Components

67 14-67 Using JDBC 1. Load the driver: –The driver class libraries need to be in the CLASSPATH for the Java compiler and for the Java virtual machine. –The most reliable way to load the driver into the program is: Class.forName(string).newInstance(); 2. Establish a connection to the database: –A connection string includes the literal jdbc:, followed by the name of the driver and a URL to the database. Connection conn = DriverManager.getConnection(string);

68 14-68 Using JDBC (Continued) 3. Create a statement: Statement stmt = conn.createStatement(); 4. Process a the statement: Example statements: ResultSet rs = stmt.executeQuery(querystring); int result = stmt.executeUpdate(updatestring); ResultSetMetaData rsMeta = rs.getMetaData(); Both compiled queries and stored procedures can be processed via JDBC using PreparedStatement and CallableStatement objects.

69 Import java.sql.*; Public class type_one { public static void main (String[] args) { try { class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”)//load driver Connection con=DriverManager.getConnection(“jdbc:odbc:HOD_DATA ”) //create connection with datasource Statement s = con.createStatement(); //create statement

70 String query = “select * from Data”; //create query S.execute(query); Resultset rs = s.getResultSet(); //return data from state While (rs.next() ) //retrieve data from ResultSet { System.out.println(“serial number “+rs.getString(1)); System.out.println(“, name “+rs.getString(2)); System.out.println(“ city “+rs.getString(3)); System.out.println(“ and Age “+rs.getString(4)); } s.close(); con.close(); } catch (Exception e) { System.out.println(“Exception”+e); } } }

71 Grading Scheme: Final Exam (60 points): 6 questions and you will answer FIVE ONLY Year Work: (20 points) Quiz: 6 Attendance: 4 Midterm Exam: 10 Lab: (20 points) –Project : 12 points –Practical test: 8 points

72 Your final exam Project discussions: Wednesday, May 14, 2014: 9-11 Thursday, May 15, 2014: 9-1 Saturday, May 17, 2014: 8-11 sections are shifted to Sunday 11-2, the rest are from 1-5 Sunday, May 18, 2014: 8-11 (sections), 2-5 (sections) are the same Monday, May 19, 2014: 11-2 (sections), 2-5 (sections)


Download ppt "Lecture 10: Dr. Taysir Hassan Abdel Hamid May 11, 2014."

Similar presentations


Ads by Google