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

54
STRUCTURED QUERY LANGUAGE Module Coordinator Tan Szu Tak School of Information and Communication Technology, Politeknik Brunei Semester 3 2014

Transcript of Module Coordinator Tan Szu Tak School of Information and Communication Technology, Politeknik Brunei...

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

STRUCTURED QUERY LANGUAGE

Module Coordinator

Tan Szu TakSchool of Information and Communication Technology, Politeknik Brunei

Semester 3 2014

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

Contents

2

History Data Definition Language Domain Types in SQL Create Table Construct Integrity Constraints in Create Table Creating Table Exercise Drop Table Constructs

*Words with underline can be clicked on

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

Contents

3

Alter Table Constructs Data Manipulating Language The select Clause The where Clause The from Clause Cartesian Product The join Clause

*Words with underline can be clicked on

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

Contents

4

Natural Join The Rename Operation String Operations Ordering the Display of Tuples Where Clause Predicates Null Values Null Values and Three Valued Logic

*Words with underline can be clicked on

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

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?

Recap

5

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

In lecture 3 – Relational Data Model, we covered EIGHT relational algebra operators.

What are they? SELECT PROJECT UNION INTERSECT

Cont. Recap

6

DIFFERENCE PRODUCT JOIN DIVIDE

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

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.

Cont. Recap

7

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

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.

Cont. Recap

8

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

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.

History

9

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

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.

Data Definition Language

10

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

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).

Domain Types in SQL

11

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

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.

Cont. Domain Types in SQL

12

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

A SQL relation is defined using the create table command:

create table r (A1 D1, A2 D2, ..., An Dn ,(integrity-constraint1),...,(integrity-constraintk) );

Where: r is the name of the relation each A1 is an attribute name in the schema of relation r. D1 is the data type of values in the domain of attribute A1.

Create Table Construct

13

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

Example:create table instructor (

ID char(5),name varchar(20) not null,dept_name varchar(20),salary numeric(8, 2));

insert into instructor values (‘10211’, ’Smith’, ’Biology’, 66000);insert into instructor values (‘10211’, null, ’Biology’, 66000);

Cont. Create Table Construct

14

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

not null ◦attribute cannot be unknown/empty

primary key (A1, ..., An )◦primary key declaration on an attribute

automatically ensures not null

foreign key (Am, ..., An ) references r

Integrity Constraints in Create Table

15

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

Example: Declare ID as the primary key for instructor.

create table instructor (ID char(5),name varchar(20) not null,dept_name varchar(20),salary numeric(8, 2),primary key (ID),foreign key (dept_name) references department);

Cont. Integrity Constraints in Create Table

16

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

How to create a table in SQL with the following criteria?

dept_name refers to dept_name in department table.

Creating Table Exercise

17

coursecourse_id (primary key) varchar - 8title varchar - 50dept_name (foreign key) varchar - 20credits numeric – 2 significant, 0

decimal point

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

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

Cont. Creating Table Exercise

18

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

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)

Drop Table Constructs

19

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

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

Alter Table Constructs

20

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

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

Data Manipulation Language

21

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

A typical SQL query has the form:

select A1, A2, ..., An

from r1, r2, ..., rm

where P

◦Ai represents an attribute◦Ri represents a relation◦P is a predicate.

The result of an SQL query is a relation.

Cont. Data Definition Language

22

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

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 namefrom instructor

The select Clause

23

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

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.

Cont. The select Clause

24

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

E.g. Find the names of all departments with instructor, and remove duplicates

select distinct dept_namefrom instructor

The keyword all specifies that duplicates not be removed.

select all dept_namefrom instructor

Cont. The select Clause

25

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

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.

Cont. The select Clause

26

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

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.

Cont. The select Clause

27

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

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 namefrom instructorwhere dept_name = ‘Comp. Sci.' and salary > 80000

The where Clause

28

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

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

Cont. The where Clause

29Visit this link for more operators

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

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

The from Clause

30

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

Cartesian Product: instructor X teaches

31

instructor teaches

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

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

The join Clause

32

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

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.'

Cont. The join Clause

33

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

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;

Natural Join

34

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

List the names of instructors along with the course ID of the courses that they taught.

select name, course_idfrom instructor, teacheswhere instructor.ID = teaches.ID;

select name, course_idfrom instructor natural join teaches;

Cont. Natural Join

35

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

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

Cont. Natural Join

36

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

1. PRODUCT

Cont. Natural Join

37

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

2. SELECT

3. PROJECT

Cont. Natural Join

38

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

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, titlefrom instructor natural join teaches natural join course;

Cont. Natural Join

39

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

Correct versionselect name, titlefrom instructor natural join teaches,

coursewhere teaches.course_id =

course.course_id;

Another correct versionselect name, titlefrom (instructor natural join teaches)

join course using(course_id);

Cont. Natural Join

40

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

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_salaryfrom instructor

The Rename Operation

41

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

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 TKeyword as must be omitted in Oracle

Cont. The Rename Operation

42

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

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.

String Operations

43

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

Example: Find the names of all instructors whose name includes the substring “dar”.

select namefrom instructorwhere name like '%dar%'

Match the string “100 %”like ‘100 \%' escape '\‘

\ is used the escape character.

Cont. String Operations

44

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

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.

Cont. String Operations

45

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

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.

Cont. String Operations

46

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

List in alphabetic order the names of all instructors select distinct name

from instructororder 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 attributesExample: order by dept_name, name

Ordering the Display of Tuples

47

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

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

Where Clause Predicates

48

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

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 nullExample: 5 + null returns null

Null Values

49

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

The predicate is null can be used to check for null values.

Example: Find all instructors whose salary is null.select namefrom instructorwhere salary is null

Any comparison with null returns unknownExample: 5 < null or null <> null or null = null

Cont. Null Values

50

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

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

Null Values and Three Valued Logic

51

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

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

Cont. Null Values and Three Valued Logic

52

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

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 IIAggregate Functions such as: Avg, Min, Max, Sum, Count

Group by, Having, Not Exists

Insert, Delete, Update tuples

Next Lecture

53

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

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