Presentation is loading. Please wait.

Presentation is loading. Please wait.

Module Coordinator Tan Szu Tak School of Information and Communication Technology, Politeknik Brunei Semester 3 2014.

Similar presentations


Presentation on theme: "Module Coordinator Tan Szu Tak School of Information and Communication Technology, Politeknik Brunei Semester 3 2014."— Presentation transcript:

1 Module Coordinator Tan Szu Tak School of Information and Communication Technology, Politeknik Brunei Semester 3 2014

2 2  NOT operator NOT operator  LIMIT Clause LIMIT Clause  CONCAT Functions CONCAT Functions  Set Operations Set Operations  Advance Domain Type Advance Domain Type  DATE Operation DATE Operation  Aggregate Functions Aggregate Functions *Words with underline can be clicked on

3 3  Group By and Having Group By and Having  Conceptual Evaluation of Group by and Having Conceptual Evaluation of Group by and Having  NESTED Queries NESTED Queries  Modification of the Database Modification of the Database  Insertion Insertion  Deletion Deletion  Updates Updates *Words with underline can be clicked on

4 4  Case Statement Case Statement  Saving Tables Changes Saving Tables Changes  Restoring Table Contents Restoring Table Contents *Words with underline can be clicked on

5 We have learn about Data-definition language (DDL). What is DDL? What can it do? We learn about some domains types such as: char(n), varchar(n), int, smallint, numeric(p,d), real, float(n) Find out what is the difference between char VS varchar and varchar VS varchar2. What is meant by double precision. E.g. -1.79769E+308 5

6 6 CHARVARCHARVARCHAR2 Stores strings of fixed length Stores strings of variable length Length parameter specifies the length of the strings. Length parameter specifies the maximum length of the strings If the string has smaller length it padded with space at the end. It stores up to 2000 bytes of characters. It stores up to 4000 bytes of characters. It will waste a lot of disk space It will occupy space for NULL values It will not occupy space for NULL values. If the string has bigger length, it truncated to the scale number of the string. The total length for strings is defined when database was created. The total length of strings is defined when strings are given.

7 In DDL we have gone through:  CREATE create table r (A 1 D 1, A 2 D 2,..., A n D n, (integrity-constraint 1 ),..., (integrity-constraint k ) ); Primary key, foreign key, not null, CHECK E.g. check (A in (‘male’, ‘female’)) 7

8  drop table r  delete from r  truncate table r  alter table r add A D  alter table r drop A  alter table r modify A - modify the attribute 8

9 We also learn another important part of SQL that is Data-manipulation language (DML).  Query information  Insert tuples  Delete tuples  Update tuples. 9

10 In terms of Query information, we learn that a typical SQL query has the form: select A 1, A 2,..., A n from r 1, r 2,..., r m where P What is distinct? natural join, rename as, String operations %, _, order by asc (default)/desc 10

11 NOT operator is used to invert the query. Example To display a list of employees who are not programmer (including Senior programmers, Multimedia programmers and Programmers). Select f_name, l_name, title from employee_data where title NOT LIKE “%programmer%”; 11

12 Data that will display can be restricted using LIMIT clause. Example - To list the first of five employees: Select f_name from employee_data LIMIT 5; Select f_name from employee_data ORDER BY age DESC LIMIT 5; Select f_name from employee_data ORDER BY age LIMIT 2; 12

13 To put condition, for example to begin data from certain row. Syntax: Select A from r LIMIT ; Select f_name from employee_data LIMIT 3, 2; 13 f_name Ali Abu Siti Mohammad Khairul Arif

14 CONCAT allows value to be combined as one. Example: select CONCAT (f_name, “ “, l_name) from employee_data where title = ‘Programmer’; 14 f_namel_nameJob AliIshakProgrammer AbuHadiDesigner SitiNurProgrammer MohammadShahClerk

15 Once CONCAT, the value can be rename using the as clause. Example: select CONCAT (f_name, “ “, l_name) as name from employee_data where title = ‘Programmer’; 15

16 Find courses that ran in Fall 2009 or in Spring 2010 (select course_id from section where sem = ‘Fall’ and year = 2009) union (select course_id from section where sem = ‘Spring’ and year = 2010) Find courses that ran in Fall 2009 and in Spring 2010 (select course_id from section where sem = ‘Fall’ and year = 2009) intersect (select course_id from section where sem = ‘Spring’ and year = 2010) 16

17 Find courses that ran in Fall 2009 But no in in Spring 2010 (select course_id from section where sem = ‘Fall’ and year = 2009) except (select course_id from section where sem = ‘Spring’ and year = 2010) Set Operations above automatically eliminates duplicates. To retain all duplicates use the corresponding multiset versions union all, intersect all and except all. 17

18  date: Dates, containing a (4 digit) year, month and date ◦ Example: date ‘2005-7-27”  time: time of day, in hours, minutes and seconds. ◦ Example: time ‘09:00:30’  timestamp: date plus time of day ◦ Example: timestamp ‘2005-7-27 09:00:30’  interval: period of time ◦ Example: interval ‘1’ day ◦ Subtracting date/time/timestamp yield interval. Can be added to date/time/timestamp. 18

19 Date type column allow operations like sort, condition, etc. Example: select f_name from employee_data where birth_date = ‘1993-12-31’; select f_name from employee_data where birth_date >= ‘1995-01-01’; 19

20 To put a range in the query Example: select e_id, birth_date from employee_per where birth_date between ‘1993-01-01’ AND ‘1997-12-31’ ; select f_name from employee_data where birth_date >= ‘1995-01-01’ AND birth_date <= ‘1997-12-31’ ; 20

21 Using DATE to sort data select e_id, birth_date from employee_per ORDER BY birth_date; To display the data of employees who is born in March. select e_id, birth_date from employee_per where MONTH (birth_date) = 3; 21

22 To display the data of employees who is born in January. select e_id, birth_date from employee_per where MONTHNAME (birth_date) = ‘January’; The name of month is case sensitive. Example: January not JANUARY 22

23 To query by year: select e_id, birth_date from employee_per where year (birth_date) = 1995; To query by day: select e_id, birth_date from employee_per where DAYOFMONTH (birth_date) = 20; 23

24 To query by current month: select e_id, birth_date from employee_per where year (birth_date) = MONTH (CURRENT_DATE); Apply to YEAR, DAYOFMONTH as well. 24

25 These functions operate on the multiset of values of a column of a relation, and return a value:  avg: returns average of values in specified column  min: returns smallest value in specified column  max: returns largest value in specified column  sum: returns sum of values in specified column  count: returns the number of values in the specified column. 25

26 Examples: Find the average salary of instructors in the Computer Science department select avg (salary) from instructor where dept_name = ‘Comp. Sci’; Find the lowest mark of exam in DBMS. select student_ID, MIN (marks) from exam where exam_id = ‘ICE2306’; 26

27 Find the highest mark of exam in DBMS. select student_ID, MAX (marks) from exam where exam_id = ‘ICE2306’; Find the total price on a resit select SUM (price) as Total from sales_order where receipt_no = ‘RI3345’; 27

28 Find the number of tuples in the course relation select count (*) from course; Find the total number of instructors who teach a course in the Spring 2010 semester select count (distinct Instructor_ID) from teaches where semester = ‘Spring’ and year = 2010; 28

29 So far, we have applied aggregate operators to all “qualifying” tuples. Sometimes, we want to apply them to each of several groups of tuples. 29

30 Example: Find the age of the youngest sailor for each rating level. 30

31 Suppose we know that rating values go from 1 to 10; we can write 10 queries that look like this: select MIN (S.age) from sailors S where S.rating = i; i = 1,2,…., 10 But, in general, we don’t know how many rating levels exist, and what the rating values for these level are. 31

32 Find the age of the youngest sailor for each rating level. select MIN (S.age) from sailors S group by S.rating; Find the number of sailors at each rating level that has at least 2 sailors. select S.rating, count (*) from sailors S group by S.rating having count (*) > 1; 32

33 Group by and Having Syntax: SELECT [DISTINCT] select-list FROM from-list WHERE qualification GROUP BY grouping-list HAVING group-qualification 33

34 1. Compute cross-product of tables in from-list 2. Apply the qualifications in the WHERE clause 3. Eliminate unwanted columns ◦ Only columns in SELECT, GROUP BY, or HAVING are necessary 4. Sort table according to GROUP BY clause 5. Apply group-qualification in the HAVING clause 6. Generate one answer for each remaining group. 34

35 Step 1-4 35

36 Step 5-6 36

37 Nested queries refers to a query in another query. Example: select f_name from employee_data where emp_id = ( select f_name from employee_per where s_name = “betty”); 37

38 Three ways to modify a relation:  Insertion of new tuples into a given relation.  Deletion of tuples from a given relation.  Updating values in some tuples in a given relation. 38

39 Insert allows user to add new tuple in the relation. Add a new tuple to course insert into course values (‘ICE2306’, ‘DBMS’, ‘SICT’, 4); OR insert into course (course_id, title, dept_name, credits) values (‘ICE2306’, ‘DBMS’, ‘SICT’, 4); Add a new tuple with credits set to null insert into course values (‘ICE2306’, ‘DBMS’, ‘SICT’, null); 39

40 Delete allows user to delete the entire or specifics tuples in the relation. Delete all instructors delete from instructor Delete all instructors from the Finance department delete from instructor where dept_name = ‘Finance’: 40

41 Delete all tuples in the instructor relation for those instructors associated with a department located at the Watson building. delete from instructor where dept_name in (select dept_name from department where building = ‘Watson’); 41

42 Delete all instructors whose salary is less than the average salary of instructors. delete from instructor where salary < (select avg (salary) from instructor); Problem: as we delete tuples from instructor, the average salary changes Solution: Compute avg salary first then delete all tuples without recomputing avg. 42

43 Updates allows user to update the existing specified tuples in the relation. Syntax: update r set A 1 = Value1, A 2 = Value2, A n = ValueN, where condition; update student set f_name = ‘Ali’ where student_ID = 0001; 43

44 Exercise: Increase salaries of instructors whose salary is over $100,000 by 3%, and all others receive a 5% raise. update instructor set salary = salary * 1.03 where salary > 100000; update instructor set salary = salary * 1.05 where salary <= 100000; 44

45 The order is important. Assume the updates is done the other way around. update instructor set salary = salary * 1.05 where salary <= 100000; update instructor set salary = salary * 1.03 where salary > 100000; What will happen? 45

46 To prevent the previous problem a case statement can be used. Example: update instructor set salary = case when salary <= 100000 then salary * 1.05 else salary*1.03 end 46

47 Changes made to table contents are not physically saved on disk until:  Database is closed  Program is closed  COMMIT command is used Syntax - commit; Will permanently save any changes made to any table in the database. 47

48 The syntax ROLLBACK;  is used to undoes changes since last COMMIT.  It brings data back to prechange values. COMMIT and ROLLBACK only work with commands to add, modify, or delete table rows. In Oracle, ROLLBACK command undoes changes made by last two UPDATE statements. 48

49 Will cover: Structured Query Language III View & Materialized View Check, Assertions (Not Exists) and Triggers 49

50 Reference: Database System Concepts – 6 th Edition Lecture Slides by Tan Szu Tak, SICT, Politeknik Brunei

51 check (P) where P is a predicate Example: ensure that semester is one of fall, winter, spring or summer: create table section ( course_id varchar (8), sec_id varchar (8), semester varchar (6), year numeric (4,0), building varchar (15), room_number varchar (7), time slot id varchar (4), primary key (course_id, sec_id, semester, year), check (semester in (’Fall’, ’Winter’, ’Spring’, ’Summer’)) ); 51


Download ppt "Module Coordinator Tan Szu Tak School of Information and Communication Technology, Politeknik Brunei Semester 3 2014."

Similar presentations


Ads by Google