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  History History  Data Definition Language Data Definition Language  Domain Types in SQL Domain Types in SQL  Create Table Construct Create Table Construct  Integrity Constraints in Create Table Integrity Constraints in Create Table  Creating Table Exercise Creating Table Exercise  Drop Table Constructs Drop Table Constructs *Words with underline can be clicked on

3 3  Alter Table Constructs Alter Table Constructs  Data Manipulating Language Data Manipulating Language  The select Clause The select Clause  The where Clause The where Clause  The from Clause The from Clause  Cartesian Product Cartesian Product  The join Clause The join Clause *Words with underline can be clicked on

4 4  Natural Join Natural Join  The Rename Operation The Rename Operation  String Operations String Operations  Ordering the Display of Tuples Ordering the Display of Tuples  Where Clause Predicates Where Clause Predicates  Null Values Null Values  Null Values and Three Valued Logic Null Values and Three Valued Logic *Words with underline can be clicked on

5 What are the fours types of Data Model covered in Lecture 2?  Hierarchical  Network  Relational  Object Oriented (OO) In which data model introduced a powerful and flexible query language? 5

6 In lecture 3 – Relational Data Model, we covered EIGHT relational algebra operators. What are they?  SELECT  PROJECT  UNION  INTERSECT 6  DIFFERENCE  PRODUCT  JOIN  DIVIDE

7 SELECT  Yields values for all rows found in a table that satisfy a given condition. PROJECT  Yields values for all columns for selected attributes. UNION  Combines all rows from two tables, excluding duplicate rows. 7

8 JOIN (Natural Join)  Links tables by selecting rows with common values in common attributes. DIVIDE  Uses one single-column tables as the divisor and one 2-column table as the divident. 8

9 IBM Sequel language was developed as part of the System R project at the IBM San Jose Research Laboratory. Later renamed as Structured Query Language (SQL). ANSI and ISO standard SQL (version): SQL-86, SQL-89, SQL-92, SQL:1999, SQL:2003, SQL:2008 Commercial systems offer most of SQL-92 features plus varying features sets from later standards. 9

10 The SQL data-definition language (DDL) allows the specification of information about relations, including:  The schema for each relation.  The domain of values associated with each attribute.  Integrity constraints  The set of indices to be maintained for each relations.  Security and authorization information for each relations.  The physical storage structure of each relation on disk. 10

11  char(n) – Fixed length character string, with user- specified length n.  varchar(n) – Variable length character strings, with user-specified maximum length n.  int – integer (a finite subset of the integers that is machine-dependent).  smallint – small integer (a machine-dependent subset of the integer domain type). 11

12  numeric(p,d) – Fixed point number, with user- specified precision of p digits, with d digits to the right of decimal point.  real, double precision – Floating point and double- precision floating point numbers, with machine- dependent precision.  float(n) – Floating point number, with user- specified precision of at least n digits. 12

13 A SQL relation is defined using the create table command: create table r (A 1 D 1, A 2 D 2,..., A n D n, (integrity-constraint 1 ),..., (integrity-constraint k ) ); Where:  r is the name of the relation  each A 1 is an attribute name in the schema of relation r.  D 1 is the data type of values in the domain of attribute A 1. 13

14 Example: create table instructor ( IDchar(5), namevarchar(20) not null, dept_namevarchar(20), salarynumeric(8, 2)); insert into instructor values (‘10211’, ’Smith’, ’Biology’, 66000); insert into instructor values (‘10211’, null, ’Biology’, 66000); 14

15  not null ◦ attribute cannot be unknown/empty  primary key (A 1,..., A n ) ◦ primary key declaration on an attribute automatically ensures not null  foreign key (A m,..., A n ) references r 15

16 Example: Declare ID as the primary key for instructor. create table instructor ( IDchar(5), namevarchar(20) not null, dept_namevarchar(20), salarynumeric(8, 2), primary key (ID), foreign key (dept_name) references department); 16

17 How to create a table in SQL with the following criteria? dept_name refers to dept_name in department table. 17 course course_id (primary key)varchar - 8 titlevarchar - 50 dept_name (foreign key)varchar - 20 creditsnumeric – 2 significant, 0 decimal point

18 create table course ( course_id varchar(8) primary key, title varchar(50), dept_name varchar(20), credits numeric(2,0), foreign key (dept_name) references department ); Primary key declaration can be combined with attribute declaration as shown above 18

19  drop table student ◦ Deletes the table and its contents. (rollback disable)  delete from student ◦ Deletes all contents of table, but retains table (rollback enable)  truncate table student ◦ Deletes all contents of table, but retains table (rollback disable) 19

20  alter table ◦ alter table r add A D  where A is the name of the attribute to be added to relation r and D is the domain of A.  All tuples in the relation are assigned null as the value for the new attribute. ◦ alter table r drop A  where A is the name of an attribute of relation r  Dropping of attributes not supported by many databases 20

21 The SQL data-manipulation language (DML) provide the ability to:  Query information  Insert tuples  Delete tuples  Update tuples. 21

22 A typical SQL query has the form: select A 1, A 2,..., A n from r 1, r 2,..., r m where P ◦ A i represents an attribute ◦ R i represents a relation ◦ P is a predicate. The result of an SQL query is a relation. 22

23 The select clause list the attributes desired in the result of a query ◦ corresponds to the projection operation of the relational algebra Example: find the names of all instructors: select name from instructor 23

24 NOTE: SQL names are case insensitive (i.e., you may use upper- or lower-case letters.) ◦ E.g. Name ≡ NAME ≡ name ◦ Some people use upper case wherever we use bold font. SQL allows duplicates in relations as well as in query results. To force the elimination of duplicates, insert the keyword distinct after select. 24

25 E.g. Find the names of all departments with instructor, and remove duplicates select distinct dept_name from instructor The keyword all specifies that duplicates not be removed. select all dept_name from instructor 25

26 An asterisk in the select clause denotes “all attributes” select * from instructor The select clause can contain arithmetic expressions involving the operation, +, –, *, and /, and operating on constants or attributes of tuples. 26

27 The query: select ID, name, salary/12 from instructor would return a relation that is the same as the instructor relation, except that the value of the attribute salary is divided by 12. 27

28 The where clause specifies conditions that the result must satisfy ◦ Corresponds to the selection predicate of the relational algebra. E.g. To find all instructors in Comp. Sci. dept with salary > 80000 select name from instructor where dept_name = ‘Comp. Sci.' and salary > 80000 28

29 Comparison results can be combined using the logical connectives and, or, and not. where dept_name = ‘Comp. Sci.' or salary > 80000 Comparisons can be applied to results of arithmetic expressions. where salary/12 > 500 29 Visit this link for more operators

30 The from clause lists the relations involved in the query ◦ Corresponds to the Cartesian product operation of the relational algebra. Find the Cartesian product instructor X teaches select * from instructor, teaches ◦ generates every possible instructor – teaches pair, with all attributes from both relations Cartesian product not very useful directly, but useful combined with where-clause condition 30

31 31 instructor teaches

32 Join clause is used to combine rows from two or more tables, based on a common field between them. Example: For all instructors who have taught some course, find their names and the course ID of the courses they taught. select name, course_id from instructor, teaches where instructor.ID = teaches.ID 32

33 Example: Find the course ID, semester, year and title of each course offered by the Comp. Sci. department select section.course_id, semester, year, title from section, course where section.course_id = course.course_id and dept_name = ‘Comp. Sci.' 33

34 Natural join matches tuples with the same values for all common attributes, and retains only one copy of each common column select * from instructor natural join teaches; 34

35 List the names of instructors along with the course ID of the courses that they taught. select name, course_id from instructor, teaches where instructor.ID = teaches.ID; select name, course_id from instructor natural join teaches; 35

36 Tables below will be used as an example to describe natural join. 36

37 1. PRODUCT 37

38 2. SELECT 3. PROJECT 38

39 Danger in natural join: beware of unrelated attributes with same name which get equated incorrectly. List the names of instructors along with the titles of courses that they teach  Incorrect version (makes course.dept_name = instructor.dept_name) select name, title from instructor natural join teaches natural join course; 39

40  Correct version select name, title from instructor natural join teaches, course where teaches.course_id = course.course_id;  Another correct version select name, title from (instructor natural join teaches) join course using(course_id); 40

41 The SQL allows renaming relations and attributes using the as clause: old-name as new-name E.g. select ID, name, salary/12 as monthly_salary from instructor 41

42 Find the names of all instructors who have a higher salary than some instructor in ‘Comp. Sci’. select distinct T. name from instructor as T, employee as S where T.salary > S.salary and S.dept_name = ‘Comp. Sci.’ Keyword as is optional and may be omitted instructor as T ≡ instructor T Keyword as must be omitted in Oracle 42

43 SQL includes a string-matching operator for comparisons on character strings. The operator “like” uses patterns that are described using two special characters: ◦ percent (%) - The % character matches any substring. ◦ underscore (_) - The _ character matches any character. 43

44 Example: Find the names of all instructors whose name includes the substring “dar”. select name from instructor where name like '%dar%' Match the string “100 %” like ‘100 \%' escape '\‘ \ is used the escape character. 44

45 Patterns are case sensitive. Pattern matching examples:  ‘Intro%’ matches any string beginning with “Intro”.  ‘%Comp%’ matches any string containing “Comp” as a substring.  ‘_ _ _’ matches any string of exactly three characters.  ‘_ _ _ %’ matches any string of at least three characters. 45

46 SQL supports a variety of string operations such as  converting from upper to lower case (and vice versa) E.g. SELECT UCASE(CustomerName) AS Customer, City FROM Customers;  finding string length, extracting substrings, etc. 46

47 List in alphabetic order the names of all instructors select distinct name from instructor order by name We may specify desc for descending order or asc for ascending order, for each attribute; ascending order is the default. Example: order by name desc Can sort on multiple attributes Example: order by dept_name, name 47

48 SQL includes a between comparison operator Example: Find the names of all instructors with salary between $90,000 and $100,000 (that is, > $90,000 and < $100,000) select name from instructor where salary between 90000 and 100000 48

49 It is possible for tuples to have a null value, denoted by null, for some of their attributes null signifies an unknown value or that a value does not exist. The result of any arithmetic expression involving null is null Example: 5 + null returns null 49

50 The predicate is null can be used to check for null values. Example: Find all instructors whose salary is null. select name from instructor where salary is null Any comparison with null returns unknown Example: 5 null or null = null 50

51 Three-valued logic using the truth value unknown:  OR: (unknown or true) = true, (unknown or false) = unknown (unknown or unknown) = unknown  AND: (true and unknown) = unknown, (false and unknown) = false, (unknown and unknown) = unknown 51

52  NOT: (not unknown) = unknown ◦ “P is unknown” evaluates to true if predicate P evaluates to unknown Result of where clause predicate is treated as false if it evaluates to unknown 52

53 Find out what is the difference between char VS varchar and varchar VS varchar2. Find out does double precision mean. Will cover: Structured Query Language II Aggregate Functions such as: Avg, Min, Max, Sum, Count Group by, Having, Not Exists Insert, Delete, Update tuples 53

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


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

Similar presentations


Ads by Google