Presentation is loading. Please wait.

Presentation is loading. Please wait.

Database Management 4. course. Reminder Relational algebra – Operators – Join Relational calculus – Formulas SQL – DDL.

Similar presentations


Presentation on theme: "Database Management 4. course. Reminder Relational algebra – Operators – Join Relational calculus – Formulas SQL – DDL."— Presentation transcript:

1 Database Management 4. course

2 Reminder Relational algebra – Operators – Join Relational calculus – Formulas SQL – DDL

3 Today DDL – Constraints – Views DML – UPDATE – INSERT – DELETE DCL – GRANT – REVOKE – Commit – Rollback QL – SELECT

4 Table Students CREATE TABLE Students (sid: CHAR(20), name: CHAR(20), login: CHAR(10), age: INTEGER, gpa: REAL) CREATE TABLE Enrolled (sid: CHAR(20), cid: CHAR(20), grade: CHAR(2))

5 Integrity constraints (ICs) Constraints that have to fulfilled by every record in the database, e.g. domain limitations – Given at the schema definition – They are checked when the relation is modified Legal records: they fulfill every IC – Illegal records are not allowed in the DB DBMS has to supervise and block illegal data – Consistent to the goal of the designer and to the world, false data is avoided

6 Primary key Attribute set is key if – Every record pair has different key values (unique) – It is the tightest (cannot be reduced), otherwise superkey – If several keys exist, one is chosen by the administrator as primary key E.g. sid in table Students – Why not name? – Is {sid, name} a superkey? – What about the set {login, age}? What is the difference between primary key and key candidates (secondary keys)?

7 Primary and secondary keys Key candidates can be given by UNIQUE What about this: CREATE TABLE Enrolled (sid CHAR(20) cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid), UNIQUE (cid, grade) ) Students have to get different grades Think over constraints before giving them!

8 Foreign key, referential integrity Foreign key: attribute set in a relation that refers to the key attribute set of another relation – It is a logical pointer E.g. – Enrolled(sid: string, cid: string, grade: string) If every reference is valid in the DB, then referential integrity is fulfilled

9 Example Only those students can be enrolled who exist in table Students CREATE TABLE Enrolled (sid CHAR(20), cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid,cid), FOREIGN KEY (sid) REFERENCES Students (sid) ) Enrolled Students

10 Force referential integrity What happens if I want to insert a non existing sid in table Enrolled? What happens if a referred Student has to be deleted? – Delete all the records in Enrolled that refers to him – Block deleting – Modify the referring records’ sid value to default – Modify the referring records’ sid value to NULL Similar question if a referred sid is modified

11 Referential integrity in SQL SQL/92 and SQL:1999 support all the four options – Default: NO ACTION (deny delete/update) – CASCADE (delete all the refering recods) – SET NULL / SET DEFAULT (modify to NULL/Default in the referring record) CREATE TABLE Enrolled (sid CHAR (20) DEFAULT ’12345’, cid CHAR(20), grade CHAR (2), PRIMARY KEY (sid,cid), FOREIGN KEY (sid) REFERENCES Students (sid) ON DELETE CASCADE ON UPDATE NO ACTION )

12 Practice What kind of referential constraints should be given between tables emp and dept? What other constraint should be given to table emp?

13 Table EMP without constraints CREATE TABLE emp ( empno NUMBER(4), ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), HIREDATE DATE, SAL NUMBER(7,2), COMM NUMBER (7,2), DEPTNO NUMBER(2)); CREATE TABLE dept ( deptno NUMBER(2), dname VARCHAR2(10), loc VARCHAR2(10));

14 Table EMP – primary constraints CREATE TABLE emp ( empno NUMBER(4) NOT NULL, ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), HIREDATE DATE, SAL NUMBER(7,2), COMM NUMBER (7,2), DEPTNO NUMBER(2)); CREATE TABLE dept ( deptno NUMBER(2), dname VARCHAR2(10), loc VARCHAR2(10));

15 Table EMP – keys CREATE TABLE EMP (empno NUMBER(4) NOT NULL, ENAME VARCHAR2(10), …. DEPTNO NUMBER(2) NOT NULL, PRIMARY KEY (empno), FOREIGN KEY (deptno) REFERENCES DEPT (deptno)); EMPDEPT empnoename…deptno 7369SMITH…20 7499ALLEN…30 7844TURNER…30 deptnodnameloc 10ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO

16 CREATE TABLE emp ( empno NUMBER(4) NOT NULL, ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), HIREDATE DATE, SAL NUMBER(7,2), COMM NUMBER (7,2), DEPTNO NUMBER(2) NOT NULL CONSTRAINT emp_prim_key PRIMARY KEY (empno), CONSTRAINT emp_frgn_key FOREIGN KEY (deptno) REFERENCES DEPT (deptno) );

17 Table EMP – internal constraint CREATE TABLE emp ( empno NUMBER(4) NOT NULL, ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4) CONSTRAINT emp_self_key REFERENCES EMP (empno) HIREDATE DATE, SAL NUMBER(7,2), COMM NUMBER (7,2), DEPTNO NUMBER(2) NOT NULL CONSTRAINT emp_prim_key PRIMARY KEY (empno), CONSTRAINT emp_frgn_key FOREIGN KEY (deptno) REFERENCES DEPT (deptno) );

18 Disable/enable constraints If I want to delete employee Blake DELETE FROM emp WHERE UPPER(ename)=’BLAKE’; Error: internal referential constraint is violated – ALTER TABLE emp DISABLE CONSTRAINT emp_self_key; – ALTER TABLE emp ENABLE CONSTRAINT emp_self_key; BUT! We have to give another boss to Mr. Blake’s employees before reenabling the constraint!

19 NULL value Unknown value for an element (not given yet or not defined) Complications – Special operators are needed to check null value: IS NULL, IS NOT NULL – How to evaluate comm>0 if comm is NULL? – What about logical operators AND, OR, and NOT? – Three-valued logic is needed: True, False, Unknown

20 SQL: Kleene’s three-valued logic If compared with NULL, it is usually NULL except when UNION or INTERSECT is used A AND B B TrueUnknownFalse A True UnknownFalse Unknown False A OR B B TrueUnknownFalse A True UnknownTrueUnknown FalseTrueUnknownFalse ANOT A TrueFalse Unknown FalseTrue

21 Other consequences Think over WHERE conditions! New operators: outer joins, (+)

22 CHECK constraint Goal: filter illegal data – E.g. age < 120 – Average of students <= 5.0 Useful for complex constraints that cannot be expressed by keys They can be named They are valid when table is not empty

23 Example CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( rating >= 1 AND rating <= 10 )

24 Example 2 CREATE TABLE Reserves ( sname CHAR(10), bid INTEGER, day DATE, PRIMARY KEY (bid,day), CONSTRAINT noInterlakeRes CHECK (`Interlake’ <> ( SELECT B.bname FROM Boats B WHERE B.bid=bid)))

25 Example 3 Goal: no. of sailors and boats cannot reach 100 CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( ( SELECT COUNT (S.sid) FROM Sailors S) + ( SELECT COUNT (B.bid) FROM Boats B) < 100) Is it good? NO!

26 Good solution Not connected to the table: CREATE ASSERTION smallClub CHECK ( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats B) < 100)

27 What defines the ICs? The modeled world It can be checked whether a DB corresponds to an IC, but I can never say that the IC is valid for the DB – The IC stands for all of the records – We know that ename is not key, but we can only check that whether empno is a key. Primary and foreign keys are widely used, the others are not.

28 Creating tables based on ER models Employees ssn name lot CREATE TABLE Employees (ssn CHAR(11), name CHAR(20), lot INTEGER, PRIMARY KEY (ssn))

29 Creating relationship sets Task: Create Works_In2 based on the diagram

30 Solution The primary keys of the entity sets have to be included as foreign key  superkey CREATE TABLE Works_In( ssn CHAR (11), did INTEGER, since DATE, PRIMARY KEY (ssn, did), FOREIGN KEY (ssn) REFERENCES Employees (ssn), FOREIGN KEY (did) REFERENCES Departments (did))

31 Task What is the key of Manages? Why?

32 Key: did We can combine Department and Manages since every department has one manager CREATE TABLE Manages( ssn CHAR(11), did INTEGER, since DATE, PRIMARY KEY (did), FOREIGN KEY (ssn) REFERENCES Employees (ssn), FOREIGN KEY (did) REFERENCES Departments (did)) CREATE TABLE Dept_Mgr( did INTEGER, dname CHAR(20), budget REAL, mgr CHAR(11), since DATE, PRIMARY KEY (did), FOREIGN KEY (mgr) REFERENCES Employees (ssn))

33 Reminder: participation constraint Does every department have a manager? Every element in the entity set has to be used in at least one of the rows of the relation

34 Participation constraint in SQL We have limited possibilities CREATE TABLE Dept_Mgr( did INTEGER, dname CHAR(20), budget REAL, mgr CHAR(11) NOT NULL, since DATE, PRIMARY KEY (did), FOREIGN KEY (mgr) REFERENCES Employees, ON DELETE NO ACTION )

35 Weak entity sets Attributes of the entity set are not enough to identify the entities, the keys of other entity sets are needed Every element has to be contained by other entity sets

36 CREATE TABLE Unit-of ( Number INTEGER NOT NULL, Studio_name VARCHAR2 NOT NULL, FOREIGN KEY (Studio_name) REFERENCES Studios (name), ON DELETE CASCADE) Delete the weak when strong is deleted

37 ISA

38 General solution 3 relations: Employees, Hourly_Emps, Contract_Emps Hourly_Emps: every employee is in table Employee, but this has additional info Hourly_Emps (hourly_wages, hours_worked, ssn) ON DELETE CASCADE Employees can be queried easily In case of queries of hourly emps join is needed

39 Alternative solution Only 2 relations: Hourly_Emps, Contract_Emps Hourly_Emps (ssn, name, lot, hourly_wages, hours_worked) Contract_Emps (ssn, name, lot, contractid) Every employee is stored in one of the tables All the employees can be queried from the union of the two tables

40 Views Stored in the memory, quicker handling CREATE VIEW View_name AS SELECT … DROP VIEW View_name

41 Data Manipulation Language INSERT INSERT INTO Students (sid, name, login, age, gpa) VALUES (53688, ‘Smith’, ‘smith@ee’, 18, 3.2) INSERT INTO Students VALUES (53688, ‘Smith’, ‘smith@ee’, 18, 3.2) UPDATE UPDATE students SET gpa=3.5 WHERE name = ‘Smith’ DELETE: Delete students called Smith DELETE FROM Students S WHERE S.name = ‘Smith’

42 DCL – Data Control Language Transaction handling – COMMIT – ROLLBACK – LOCK – UNLOCK Handling permissions of users – GRANT … with GRANT options – REVOKE

43 Handling transactions Command block is treated as a unit – To keep the consistency of the DB Default: command-level consistency – keep consistency in every command Transaction-level consistency: – BEGIN WORK – starting point – COMMIT – end point/verification – ROLLBACK – cancel the block

44 Savepoint SAVEPOINT – we can refer to this when we roll back – SAVEPOINT name_of_sp ROLLBACK – Default: roll back till startpoint – Till savepoint: (… TO SAVEPOINT name_of_sp) – Implicitly unlock tables

45 Transaction - example START TRANSACTION; -- depends on DBMS UPDATE Account SET amount=amount-200 WHERE account_number=1234; UPDATE Account SET amount=amount+200 WHERE account_number=2345; IF ERRORS=0 COMMIT; IF ERRORS<>0 ROLLBACK;

46 Rollback COMMIT; SAVEPOINT A1; SAVEPOINT A2; ROLLBACK TO A2; – Rollback till A2 ROLLBACK TO A1; – Rollback till A1, delete savepoint A2, delete table locks ROLLBACK; – till COMMIT, delete every savepoint, unlock everything

47 Handling users CREATE USER DROP USER CREATE USER student IDENTIFIED BY pwd; – student does not have any permission here ALTER USER student IDENTIFIED BY pwd2; DROP USER student;

48 Handling rights (permissions) GRANT rights ON DBname[, tablename] TO username@host [IDENTIFIED BY pwd] [WITH GRANT OPTION];

49 Rights in the system CREATE SESSION – connecting to DB CREATE TABLE – right to create tables CREATE VIEW – right to create views CREATE PROCEDURE – right to create procedures GRANT CREATE SESSION, CREATE TABLE, CREATE VIEW TO student;

50 Role Define roles and give rights to the roles CREATE ROLE role_name GRANT CREATE TABLE, CREATE SESSION TO role_name GRANT role_name TO user1, user2, user3;

51 Rights of object handling ALTER DELETE EXECUTE INDEX REFERENCES SELECT UPDATE

52 Examples GRANT SELECT on Students TO student1; GRANT ALL on Students TO student1; GRANT SELECT on Students TO PUBLIC; GRANT SELECT on Students TO student_role; GRANT SELECT on Students TO student1 WITH GRANT OPTION;

53 Revoke rights REVOKE rights [,WITH GRANT OPTION] ON DBname[, tablename] FROM username@host | role | PUBLIC

54 Query Language

55 QUERY Language One command: SELECT SELECT [DISTINCT] columns FROM tables [WHERE condition] [GROUP BY columns [HAVING having-condition]] [ORDER BY columns]

56 Inner selection SELECT can be inside a WHERE condition WHERE col1 [NOT] IN (SELECT…) WHERE col1 [ANY|ALL] (SELECT…) WHERE col1 [NOT] EXISTS (SELECT…) – EXISTS returns with true if there is at least one row in the inner selection Evaluation goes from inside to outside

57 Example for ANY List those employees the salary of whom is less than one of the averages of the salaries SELECT ename, sal FROM EMP WHERE sal < ANY (SELECT avg(sal) FROM EMP GROUP by deptno);

58 Example for ALL List those employees the salary of whom is less than every average of the salaries SELECT ename, sal FROM EMP WHERE sal < ALL (SELECT avg(sal) FROM EMP GROUP by deptno);

59 Inner selection v. 2 Give all the outcome for every department! SELECT dname, SUM(sal+NVL(comm,0)) FROM emp, (SELECT deptno,dname FROM dept) inner_tab WHERE inner_tab.deptno=EMP.deptno GROUP BY dname ORDER BY dname [DESC];

60 JOIN example SELECT ename, dname FROM emp INNER JOIN dept USING (deptno) SELECT ename, dname FROM emp NATURAL JOIN dept SELECT ename, dname FROM emp, dept WHERE emp.deptno=dept.deptno

61 JOIN example 2 SELECT employee.ename as ”Employee”, boss.ename as ”BOSS” FROM EMP boss INNER JOIN EMP employee ON (boss.empno=employee.mgr) SELECT boss.ename as ”BOSS”, employee.ename as ”Employee” FROM EMP boss, EMP employee WHERE (boss.empno=employee.mgr) 13 rows returned: Mr. King does not have a boss!

62 SELECT boss.ename as ”BOSS”, employee.ename as ”Employee” FROM EMP boss RIGHT JOIN EMP employee ON (boss.empno=employee.mgr) SELECT boss.ename as ”BOSS”, employee.ename as ”Employee” FROM EMP boss, EMP employee WHERE (boss.empno(+)=employee.mgr) 14 rows returned: NULL for Mr. King’s boss!

63 Group functions MIN MAX AVG STDDEV: deviation SUM COUNT ([DISTINCT] col |*): number of (in col1) the not null valued rows| nuber of the rows DISTINCT: gives back only the different rows VARIANCE ROUND

64 String functions UPPER: Capitalize LOWER TO_CHAR(col,format): convert date to string TO_DATE: convert string to date CONCAT: concatenate strings SUBSTR: a szöveg része a kezdet pozíciótól adott hosszban. Hossz nélkül a szöveg végéig. WHERE col1 [NOT] LIKE pattern: where col1 fulfills pattern

65 WHERE col [NOT] LIKE pattern _ one optional character % any string Example: Col1 does not contain string abc: WHERE LOWER(col1) NOT LIKE ’%abc%’ Second letter from back is a in col1: WHERE LOWER(col1) LIKE ’%a_’

66 LENGTH: length of a string INSTR: where to find a substring in a string LPAD: concatenate from left with a string or with spaces RPAD: concatenate from left with a string or with spaces

67 INITCAP: Capitalize the first letter CHR: character from ASCII code ASC: ASCII code of the first letter LTRIM: trim a string from left TRANSLATE: replace substring to another string

68 Thank you for your attention!


Download ppt "Database Management 4. course. Reminder Relational algebra – Operators – Join Relational calculus – Formulas SQL – DDL."

Similar presentations


Ads by Google