8/10/2019 Awesome Dbms
1/182
[email protected]/11/18 1
Database Systems-
Principle andPractice
8/10/2019 Awesome Dbms
2/182
[email protected]/11/18 An Introduction to DatabaseSystem
Relational Algebra
3.1 Relational Algebra(RA)
3.2 Simple and Complex Queries using RA3.3 Structure Query Language(SQL)3.4 Creating SQL Database and Tables3.5 Selecting Data
3.6 Data Insertion Updating and Deletion
Chapter Outline :
8/10/2019 Awesome Dbms
3/182
[email protected]/11/18
What is relational algebra?Relational algebra is a collection ofoperations that are used to manipulate the
entire set of relations. The output of anyrelational algebra operation is always arelation.What are the Operations?
Set operations like union, intersection,difference, and Cartesian product.Selection, Projection, and Joining.
Relational Algebra
8/10/2019 Awesome Dbms
4/182
[email protected]/11/18
Union )
The result of this operation, i.e. R S, is a relation thatincludes all tuples that are either in R or in S or in both.Duplicate tuples will not appear in the output.Formally: R S = { t | t R or t S }
Union Compatibility: Let R and S are two relations withattributes (A1, A2, , An) and (B1, B2, .., Bn)respectively. If R and S are to be union ed, it should satisfythe following two rules:
Rule 1: The relations R and S must have the same degree.
Rule 2: The domain of the ith attribute of R and the domainof the ith attribute of S must be same. dom (Ai) = dom (Bi), where, 1 i n.
8/10/2019 Awesome Dbms
5/182
[email protected]/11/18 An Introduction to DatabaseSystem
Example
8/10/2019 Awesome Dbms
6/182
[email protected]/11/18
Relational Difference (-)
Like union, the relational differenceoperator also requires its operands to beof the same type.Format: R - SFormally: R - S = { t | t R and t S}
Semantics : Given two relations R and Sof the same type, the difference betweenthose two relations, R- S, is the relationcontaining all tuples of R that do notappear in S.
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
7/182
[email protected]/11/18
Example
An Introduction to DatabaseSystem
Notice that Difference has a directionality to it, e.g. R-S and S-R are not the same thing.
8/10/2019 Awesome Dbms
8/182
[email protected]/11/18
Intersection( )
The expression R S returns all tuplesthat appear in both the relations R andS.
Like union and difference, the relationalintersection operator requires itsoperands to be of the same type.
Formally: R S = { t | t R and t S}Derivation from existing operators:R S = R - (R - S) = S (S - R)
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
9/182
[email protected]/11/18
Example
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
10/182
[email protected]/11/18
Cartesian Product ()
The Cartesian product or cross-product is a binaryoperation that is used to combine two relations.Assuming R and S as relations with n and m attributesrespectively, the Cartesian product, R S can bewritten as,
R (A1, A2, , An) S (B1, B2, , Bm) The result of the above set operation is,
Q (A1, A2, , An, B1, B2, , Bm) Where,
Degree (Q) = n + mcount (Q) = Number of tuples in R * Number of tuples in S.
8/10/2019 Awesome Dbms
11/182
[email protected]/11/18
Example
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
12/182
[email protected]/11/18
Special Relational Operations-SampleRelations
An Introduction to DatabaseSystem
SSN SNAME GPA AGE DEPARTMENTID
2007001003 CHENGLICHONG 3.33 20 31
2007001005 ZHONGWEILONG 3.62 20 33
2007001006 WUYUANLANG 4.01 20 33
2006001001 LUOZI 3.12 20 34
2006001002 GUOHUAXIAN 3.21 21 34
2006001004 LELINGBING 3.75 21
2007002001 ZHUJIANGUO 3.05 19
Figure 3.5 Student
8/10/2019 Awesome Dbms
13/182
[email protected]/11/18 An Introduction to DatabaseSystem
Figure 3.11 SC
SSN CNO GRADE
2007001003 001 78
2007001003 002 67
2007001003 003 89
2007001003 004 65
2007001005 001 75
2007001005 002 90
2007001006 002 80
2006001001 002 70
2006001001 004 90
8/10/2019 Awesome Dbms
14/182
[email protected]/11/18
The SELECT operation ( )
The select operation retrieves a subset of tuples in arelation that satisfy a selection condition.
(Relation)
Query-1: Find the students whose age is 19.
The new relation created as the result of this operation consists of one tuple:
SSN SNAME GPA AGE DEPARTMENTID
2007002001 ZHUJIANGUO 3.05 19
8/10/2019 Awesome Dbms
15/182
[email protected]/11/18
The SELECT operation ( )
Query-2: Select tuples (rows) of thestudent relation where the AGE is 20and Name is ZHONGWEILONG, we could
write:
An Introduction to DatabaseSystem
)(''20
student NG ZHONGWEILOSNAME AGE
8/10/2019 Awesome Dbms
16/182
[email protected]/11/18
One of the interesting properties of theselection operation is that it iscommutative. Therefore, all theexpressions shown below are equivalent,
condition-1 ( condition-2 (R))
(condition-1 AND condition-2) (R)
condition-2 ( condition-1 (R))
8/10/2019 Awesome Dbms
17/182
[email protected]/11/18
The Projection Operation ( )
The projection operation is used to select only fewcolumns from a relation.
(Relation)
Query-3: List the age of all the students. age (student)
AGE
20
21
19
8/10/2019 Awesome Dbms
18/182
[email protected]/11/18
Select and Project
We can perform these operations onthe relations resulting from otheroperations. To get the names ofstudents having the AGE as 20, wewrite:
An Introduction to DatabaseSystem
))(( 20 student AGE SNAME
8/10/2019 Awesome Dbms
19/182
[email protected]/11/18
Join )
Join ( )EquiJoin
Natural JoinLeft Outer JoinRight Outer JoinFull Outer Join
Theta Join
8/10/2019 Awesome Dbms
20/182
[email protected]/11/18
Join )
Format: R join-condition SSemantics: Return all tuples in R S whichsatisfy the join condition.
Derivation from existing operators:R join-condition S = join-condition (R S)Format of join condition:
R.A op S.BR.A1 op S.B1 and R.A2 op S.B2 . . .
8/10/2019 Awesome Dbms
21/182
[email protected]/11/18
Equijoin )
A join is called an equijoin if onlyequality operator is used in all joinconditions.
The general form for this kind of join is,
must always have = operator
21 R R y x
8/10/2019 Awesome Dbms
22/182
[email protected]/11/18
Equijoin
R S R R.B = S.B SA B B C A R.B S.B C
a b b c a b b cd b c d d b b cb c a d b c c d
Most joins in practice are equijoins.
8/10/2019 Awesome Dbms
23/182
[email protected]/11/18
Example
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
24/182
[email protected]/11/18
Natural Join *)
When we omit the condition during joiningof two relations, then it is called asnatural join ( *) :
Let relations R1 has attributes(x1,x2,x3,M) andR2 has attributes(y1,y2,y3,y4,y5,M)respectively. That is ,the M attribute iscommon to the two relations. Then the natural
join of R1 and R2 is a relation withheading(x1,x2,x3,M, y1,y2,y3,y4,y5) and bodyconsisting of all tuples that the duplicatedattributed M are removed.
8/10/2019 Awesome Dbms
25/182
[email protected]/11/18
Example
A B C
a 1 b 1 5
a 1 b 2 6
a 2 b 3 8
a 2 b 4 12
B E
b 1 3
b 2 7
b 3 10
b 3 2 b
5 2
R S
8/10/2019 Awesome Dbms
26/182
[email protected]/11/18
Natural Join
R S
A B C E
a 1 b 1 5 3
a 1 b 2 6 7
a 2 b 3 8 10
a 2 b 3 8 2
8/10/2019 Awesome Dbms
27/182
[email protected]/11/18
Theta Join ) or NonEqui Join
Let R and S are two relations. Consideran attribute x in R, and an attribute y inS. The theta join of these two relations
can be written as,
where indicates any valid relationaloperator other than =.
21 R R y x
8/10/2019 Awesome Dbms
28/182
[email protected]/11/18
Theta Join
R S
A R.B C S.B E
a 1 b 1 5 b 2 7
a 1 b 1 5 b 3 10
a 1
b 2
6
b 2
7
a 1 b 2 6 b 3 10
a 2 b 3 8 b 3 10
C E
8/10/2019 Awesome Dbms
29/182
[email protected]/11/18
To find all students name and selectedcourses NO, we need student and SCrelations
1.
2. We can rewrite the previous query as:
An Introduction to DatabaseSystem
))(( .., SC STUDENT SSN SC SSN STUDENT CNOSNAME
)(, SC STUDENT CNOSNAME
Example
8/10/2019 Awesome Dbms
30/182
[email protected]/11/18
Outer Joins Special Case of EquiJoin)
Usually, only a subset of tuples of each relationwill actually participate in a join, i.e. only tuplesthat match with the joining attributes. Tuples of arelation not participating in a join are calleddangling tuples .How do we keep dangling tuples in the result of a
join? Use null values to indicate a no-join situation.There are three types of outer joins
- left outer join
- right outer join and
- full outer join.
8/10/2019 Awesome Dbms
31/182
[email protected]/11/18
Left outer-join R1 R2 is similar to a natural join but keep alldangling tuples of R1.Right Outer-Join R1 R2 is similar to a natural join but keep alldangling tuples of R2. Outer Join (full outer-join) R1 R2 is similar to a natural join but keep alldangling tuples of both R1 and R2.The advantages of outer join is to take the union oftuples from two relations that are not unioncompatible.
8/10/2019 Awesome Dbms
32/182
[email protected]/11/18
Example:LEFT OUTER JOIN, RIGHT,OUTER JOIN
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
33/182
[email protected]/11/18
Example:FULL OUTER JOIN
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
34/182
[email protected]/11/18
Division
Not supported as a primitive operator, butuseful for expressing queries like:
Find students who have taken all courses .
Precondition: in A/B, the attributes in B mustbe included in the schema for A. Also, theresult has attributes A-B..
8/10/2019 Awesome Dbms
35/182
[email protected]/11/18
R
S
8/10/2019 Awesome Dbms
36/182
[email protected]/11/18
Examples of Division A/B
sno pnos1 p1s1 p2
s1 p3s1 p4s2 p1s2 p2
s3 p2s4 p2s4 p4
pnop2
pnop2p4
pnop1p2
p4
snos1
s2s3s4
snos1s4
snos1
A
B1B2
B3
A/B1 A/B2 A/B3
8/10/2019 Awesome Dbms
37/182
[email protected]/11/18
Another Example
Another example is: Suppose we want to find all thestudents who have selected all courses (See Figure 3.19Course Table ) provided by the school.
An Introduction to DatabaseSystem
CNO CNAME CREDIT
001 Math 3
002 Multimedia 3
003 Computer network 4
004 Software engineering 4
005 Bioinformatics 3
8/10/2019 Awesome Dbms
38/182
[email protected]/11/18
We can think of it as three steps:1.We can obtain the NO. of all courses provided
by the school by:
2.We can also find all SSN, cno pairs for whichthe student has selected courses by:
3.Now we need to find all students who selectedall the courses. The divide operation providesexactly those students:
An Introduction to DatabaseSystem
)(coursecno
)(, sccnoSSN
)()(, course sc cnocnoSSN
8/10/2019 Awesome Dbms
39/182
[email protected]/11/18
3.2 Simple and Complex queries using RA
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
40/182
[email protected]/11/18
Example
Example 1: Get supplier names forsuppliers who supply part P2:
An Introduction to DatabaseSystem
)('2'# SP S
p pSNAME
Example 2:Get supplier names forsuppliers who supply at least one red
part:)('' P SP S read color SNAME
8/10/2019 Awesome Dbms
41/182
[email protected]/11/18
CON
Example 3 :Get supplier names forsuppliers who supply all parts:
Example 4: Get supplier numbers forsuppliers who supply at least all those
parts supplied by supplier S2:
An Introduction to DatabaseSystem
)))(((#,#
S P SP p s sname
)()( '2'##,# SP SP s s p s
8/10/2019 Awesome Dbms
42/182
[email protected]/11/18
3.3 Structure Query Language SQL)
Full name of SQL --- Structural QueryLanguageOld name --- SEQUEL (Structural EnglishQUEry Language)First developed at IBM's San Jose (nowAlmaden) Research Lab. in 1974.Over 100 SQL-based products in the market.
E.g.: Oracle, Sybase, Ingres, Informix, DB2.
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
43/182
[email protected]/11/18
Cont
The first SQL standard (SQL-86) waspublished in 1986 by ANSI. (about 100pages).SQL1 was also adopted by ISO in 1987.A major revision made in 1989 (SQL-89).The second SQL standard (SQL2) wasannounced in 1992. It has about 600
pages.The third SQL standard (SQL3) is underdiscussion. Expected release time: 20??
8/10/2019 Awesome Dbms
44/182
[email protected]/11/18
Major Components of SQL
DDL --- Data Definition Language used to define tables.DML --- Data Manipulation Language (Interactive DML,ISQL) used to manipulate data directly.Embedded DML (Embedded SQL) which supports themanipulation of data from a program in a high-level
programming language.View Definition used to create different ways to look at adatabase.Authorization (DCL).Integrity Constraints which defines various constraints onthe data.
Transaction Definition which defines which group ofcommands should be treated as an atomic command.
8/10/2019 Awesome Dbms
45/182
[email protected]/11/18
3.4.1 Defining Database
CREATE DATABASE
The SQL CREATE DATABASE statementis the SQL command that adds a newdatabase.A database is the outer container for
other SQL objects: tables, columns,views, indexes, etc.
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
46/182
[email protected]/11/18
CON
The SQL CREATE DATABASE statement isused as follows:
CREATE DATABASE
Example: creates a new database namedSTUDENT_DB.
CREATE DATABASE STUDENT_DB
The CREATE DATABASE implementation and syntaxvaries substantially between different RDBMSimplementations.
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
47/182
[email protected]/11/18
DROP DATABASE
The SQL DROP DATABASE statement isthe SQL command that removes anexisting database.
The SQL DROP DATABASE statement is usedas follows:
DROP DATABASE
The following example drops an existingdatabase named STUDENT_DB.
DROP DATABASE STUDENT_DB
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
48/182
[email protected]/11/18
3.4.2 Defining tables and views
CREATECreate new objects (tables, views, etc.) in the
database
ALTERChange the structure of an existing object
DROPRemove the object from the database, (all its data
plus any reference to it in the data dictionary)
8/10/2019 Awesome Dbms
49/182
[email protected]/11/18
CREATE TABLE
The CREATE TABLE statement is usedto create tables to store data. Integrity Constraints like primary key,unique key, foreign key can be definedfor the columns while creating the table.
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
50/182
[email protected]/11/18
CON...
The create table statement does exactly that:
CREATE TABLE ( ,
... );
The data types that you will use most frequently areVARCHAR or CHAR for variable or fixed length strings;numeric types such as NUMBER or INTEGER; and DATEor related types. Data type syntax is variable fromsystem to system.
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
51/182
[email protected]/11/18
Example
If we have a table for recording students information,then the columns may include information such asstudents number(SSN), name(SNAME), birthdate(BirthDate), depart number(DEPTNO).
CREATE TABLE student(SSN NUMBER NOT NULL,SNAME CHAR(10) ,BirthDate DATE ,
DEPTNO NUMBER);Note that: The NOT NULL constraint enforces the
field of SSN to always contain a value.
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
52/182
[email protected]/11/18
ALTER TABLE
The SQL ALTER TABLE command is usedto modify the definition (structure) of atable by modifying the definition of itscolumns. The ALTER command is usedto perform the following functions.
1) Add, drop, modify table columns2) Add and drop constraints3) Enable and Disable constraints
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
53/182
[email protected]/11/18
ADD COLUMN
To add a new columnALTER TABLE
ADD (column_name datatype);
For Example: To add a column"Address" to the student table:
ALTER TABLE student ADD Address CHAR(30);
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
54/182
[email protected]/11/18
DROP COLUMN
To drop a columnALTER TABLE table_name DROP column_name;
For Example: To drop the column"Address" from the student table:
ALTER TABLE student DROP Address;
An Introduction to DatabaseSystem
8/10/2019 Awesome Dbms
55/182
[email protected]/11/18
MODIFY COLUMN
To modify a column
ALTER TABLE table_name MODIFYcolumn_name datatype;
For Example: To modify the columnAddress in the student table:
ALTER TABLE student
MODIFY Address CHAR(50); An Introduction to Database
System
8/10/2019 Awesome Dbms
56/182
[email protected]/11/18
DROP TABLE
The DROP TABLE command allows youto destroy an existing table.
If we want to permanently remove thestudent table that we created:
DROP TABLE student
An Introduction to DatabaseSystem
U i d D fi i Vi
8/10/2019 Awesome Dbms
57/182
[email protected]/11/18
Using and Defining Views
Views provide users controlled access to tablesBase Table table containing the raw dataDynamic View
A virtual table created dynamically upon request by a userNo data actually stored; instead data from base table madeavailable to userBased on SQL SELECT statement on base tables or otherviews
8/10/2019 Awesome Dbms
58/182
[email protected]/11/18
CREATE VIEW
The Syntax to create a view is
CREATE VIEW view_name ASSELECT column_listFROM table_name [WHERE condition];
The SELECT statement is used to define the columns androws that you want to display in the view
8/10/2019 Awesome Dbms
59/182
[email protected]/11/18
Example
To create a view on the student table theSQL statement would be like:CREATE VIEW view_student
AS
SELECT SSN, SNAMEFROM student;Where SNAME LIKE ZHANG% With CHECK_OPTION
View has a name CHECK_OPTION works only for updateableviews and prevents updates that wouldcreate rows not included in the view
8/10/2019 Awesome Dbms
60/182
[email protected]/11/18
ALTER VIEW
By the ALTER VIEW Statement we canchange the definition of a view. Thisstatement is useful to modify a view
without dropping it.
The general syntax of ALTER VIEWStatement is :
ALTER VIEW view_name [(column_list)] [WITHENCRYPTION] AS select_statement [WITH CHECKOPTION]
8/10/2019 Awesome Dbms
61/182
[email protected]/11/18
Example
A one more column by the name ofAddress of student table.
ALTER VIEW view_student
ASSELECT sno, sname,AddressFROM student;
8/10/2019 Awesome Dbms
62/182
[email protected]/11/18
DROP VIEW
For dropping a view you can use theDROP VIEW Statement.
The general syntax of DROP VIEWStatement is :
DROP VIEW view_name;
When view is dropped but it has no effect on the underlyingtables.
After dropping a view if you issue any query that reference adropped view then you get an error message.But dropping a table that reference any view does not dropthe view automatically. You have to dropt the view explicitly.
8/10/2019 Awesome Dbms
63/182
[email protected]/11/18
Advantages of Views
Simplify query commandsAssist with data security (but don't rely on viewsfor security, there are more important securitymeasures)
Enhance programming productivityContain most current base table dataUse little storage spaceProvide customized view for user
Establish physical data independence
8/10/2019 Awesome Dbms
64/182
[email protected]/11/18
Disadvantages of Views
Use processing time each time view isreferencedMay or may not be directly updateable
8/10/2019 Awesome Dbms
65/182
[email protected]/11/18
Specifying constraints
Constraints offer the advantages of definingcontrols in one step during the table creationprocess (as defined by the SQL standards) andof simplifying the process to create thoseintegrity controls.
Constraints can be specified when a table iscreated
CREATE TABLE statement ALTER TABLE statement
8/10/2019 Awesome Dbms
66/182
[email protected]/11/18
NOT NULL Constraint
The NOT NULL constraint enforces afield to always contain a value. Thismeans that you cannot insert a newrecord, or update a record without
adding a value to this field.The following SQL enforces the "SSN"column and the "SNAME" column to notaccept NULL values:
CREATE TABLE student(SSN NUMBER NOT NULL,SNAME CHAR(10) NOT NULL ,BirthDate DATE ,DEPTNO NUMBER);
8/10/2019 Awesome Dbms
67/182
[email protected]/11/18
UNIQUE Constraint
The UNIQUE constraint uniquely identifies each record ina database table.
The following SQL creates a UNIQUE constraint on the"SSN" column when the "student" table is created:
CREATE TABLE student(SSN NUMBER NOT NULL UNIQUE,SNAME CHAR(10) NOT NULL ,BirthDate DATE ,
DEPTNO NUMBER);Note that you can have many UNIQUE constraints
per table, but only one PRIMARY KEY constraintper table.
8/10/2019 Awesome Dbms
68/182
[email protected]/11/18
PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquelyidentifies each record in a databasetable.
A primary key must contain uniquevalues and cannot contain NULLvalues .Each table should have a primary key,and each table can have only ONEprimary key
8/10/2019 Awesome Dbms
69/182
[email protected]/11/18
CON
The following SQL creates a PRIMARY KEYon the " SSN " column when the "student " table is created:
CREATE TABLE student(SSN NUMBER PRIMARY KEY,SNAME CHAR(10) NOT NULL ,BirthDate DATE ,
DEPTNO NUMBER);
8/10/2019 Awesome Dbms
70/182
[email protected]/11/18
CON
To allow naming of a PRIMARY KEYconstraint, and for defining a PRIMARYKEY constraint on multiple columns, usethe following SQL syntax:
CREATE TABLE student(SSN NUMBER NOT NULL,SNAME CHAR(10) NOT NULL ,BirthDate DATE ,DEPTNO NUMBER,
CONSTRAINT pk_studentNo PRIMARY KEY (SSN,SNAME)
);
8/10/2019 Awesome Dbms
71/182
[email protected]/11/18
FOREIGN KEY Constraint
A foreign key is a referential constraint betweentwo tables. The foreign key identifies a columnor a set of columns in one (referencing) tablethat refers to a set of columns in another(referenced) table.The columns in the referencing table must bethe primary key or other candidate key in thereferenced table.The values in one row of the referencingcolumns must occur in a single row in thereferenced table.A row in the referencing table cannot containvalues that don't exist in the referenced table
8/10/2019 Awesome Dbms
72/182
8/10/2019 Awesome Dbms
73/182
[email protected]/11/18
CHECK Constraint
The CHECK constraint is used to limitthe value range that can be placed in acolumn.
CREATE TABLE student(SSN NUMBER PRIMARY KEY CHECK (SSN >0),SNAME CHAR(10) NOT NULL ,BirthDate DATE ,
DEPTNO NUMBER);
8/10/2019 Awesome Dbms
74/182
[email protected]/11/18
DEFAULT Constraint
The DEFAULT constraint is used to inserta default value into a column. Thedefault value will be added to all new
records, if no other value is specified.CREATE TABLE student(SSN NUMBER PRIMARY KEY CHECK(sno >0),SNAME CHAR(20) NOT NULL ,BirthDate DATE ,DEPTNO NUMBER DEFAULT 00);
8/10/2019 Awesome Dbms
75/182
[email protected]/11/18
CON
The DEFAULT constraint can also be used toinsert system values, by using functions likeGETDATE():
CREATE TABLE SC
(CNO NUMBER NOT NULL,SSN NUMBER NOT NULL,GRADE NUMBER,TakeCourseDate date DEFAULT GETDATE(),
PRIMARKY KEY(SSN,CNO)FOREIGN KEY (SSN) REFERENCES student(SSN))
8/10/2019 Awesome Dbms
76/182
[email protected]/11/18
Creating indexes
Indexes can be created against a table tomake searches more efficient.A book index allows you to find
information without having to readthrough the whole book.A database index enables the databaseapplication to find data quickly withouthaving to scan the whole table.
8/10/2019 Awesome Dbms
77/182
[email protected]/11/18
CON
For example, if users of your application oftensearch against the name field then that field isa great candidate for an index.the CREATE INDEX command:
CREATE INDEX index_nameON table_name (column_name)
ExampleCREATE INDEX StudentIndexON student (SNAME)
8/10/2019 Awesome Dbms
78/182
[email protected]/11/18
3.5 Selecting Data
Figure 3.5:student
SSN SNAME GPA AGE DEPTNO2007001003 CHENGLICHONG 3.33 20 31 2007001005 ZHONGWEILONG 3.62 20 33
2007001006 WUYUANLANG 4.01 20 33 2006001001 LUOZI 3.12 20 342006001002 GUOHUAXIAN 3.21 21 34
2006001004 LELINGBING 3.75 212007002001 ZHUJIANGUO 3.05 19
8/10/2019 Awesome Dbms
79/182
[email protected]/11/18
Figure 3.19 Course
CNO CNAME CREDIT
001 Math 3002 Multimedia 3
003 Computer network 4
004 Software engineering 4
005 Bioinformatics 3
8/10/2019 Awesome Dbms
80/182
[email protected]/11/18
Figure 3.11 SC
SSN CNO GRADE
2007001003 001 78
2007001003 002 67
2007001003 003 892007001003 004 65
2007001005 001 75
2007001005 002 90
2007001006 002 80
2006001001 002 702006001001 004 90
8/10/2019 Awesome Dbms
81/182
[email protected]/11/18
Queries: SELECT Statement
The basic SELECT statement has three clauses:SELECT ,FROM and WHERE.SELECT: Specify the table columns that areretrievedFROM : Specify the tables accessed.WHERE: Specify which table rows are used.
The WHERE clause is optional; if missing, alltable rows are used. An asterisk ("*") can alsobe used to specify that the query should returnall columns of the queried tables.
8/10/2019 Awesome Dbms
82/182
[email protected]/11/18
CON
The full syntax of the SELECT statement iscomplex as follows:
SELECT select_list
FROM table_source[ WHERE search_condition ][ GROUP BY group_by_expression ][ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]
8/10/2019 Awesome Dbms
83/182
8/10/2019 Awesome Dbms
84/182
[email protected]/11/18
Single Table
1) Retrieve specific columns, all rows(1)Retrieve specific columns
The query retrieves a subset of columns and
all rows from a table.
[Example 1]Find the SSN, SName and GPA of all studentsselect SSN, SName, GPAfrom Student
8/10/2019 Awesome Dbms
85/182
8/10/2019 Awesome Dbms
86/182
[email protected]/11/18
CON
(3)Retrieve calculated columnsThe query retrieves some columns by
computing.
[Example 3]Query the name and the birthday of
students.
Select SName,2011-AGEFrom Student
8/10/2019 Awesome Dbms
87/182
[email protected]/11/18
CON
The results will be shown in Fig.21:Figure 21 Query Result of Example 3
SName (No Name)CHENGLICHONG 1990
ZHANGWEILONG 1990
Ali
8/10/2019 Awesome Dbms
88/182
[email protected]/11/18
Alias
[Example 4]Select SName,2011-AGE as BirthdateFrom Student
The results will be shown in Fig.21:
SName Birthdate
CHENGLICHONG 1990
ZHANGWEILONG 1990
CON
8/10/2019 Awesome Dbms
89/182
[email protected]/11/18
CON
(4)Use of DistinctThe DISTINCT keyword can be used to
return only distinct (different) values.
[Example 5]If we list the AGE of all students from the above
table.Select AGE
From Student
AGE
20
2020
20
21
21
19
CON
8/10/2019 Awesome Dbms
90/182
[email protected]/11/18
CON
[Example 6]Rewriting the query as:
SELECT DISTINCT AGEFrom Students
We get the result table shown in Fig.23 with theduplicates eliminated.
AGE
20
21
19
8/10/2019 Awesome Dbms
91/182
[email protected]/11/18
2). Row selection (where clause)The SQL WHERE clause is used to select data
conditionally, by adding it to already existingSQL SELECT query.
There are six basic search conditions as follows:ComparisonRangeSet membership
Pattern matchNullCompound comparison
C i h di i
8/10/2019 Awesome Dbms
92/182
[email protected]/11/18
Comparison search condition
[Example 7]If we want to select all students from our
database table, having AGE 20 we need touse the following SQL syntax:
Select * from Student where AGE=20
SSN SNAME GPA AGE DEPTNO
2007001003 CHENGLICHONG 3.33 20 31
2007001005 ZHONGWEILONG 3.62 20 33 2007001006 WUYUANLANG 4.01 20 33 2006001001 LUOZI 3.12 20 34
8/10/2019 Awesome Dbms
93/182
8/10/2019 Awesome Dbms
94/182
[email protected]/11/18
[Example 9]We would use the negated version to
retrieve any members of students with a
GPA outside between 3 and 3.5 as:Select *From studentWhere GPA NOT BETWEEN 3 AND 3.5
Set membership search
8/10/2019 Awesome Dbms
95/182
[email protected]/11/18
pcondition(IN/NOT IN)
The set membership search condition IN allowsyou to specify multiple values in a WHEREclause.It tests whether a data value matches one of a
list values.
[Example 10]We want to select the students with an AGE
equal to 19 or 20 in the table above.Select * from studentWhere AGE IN (19, 20)
8/10/2019 Awesome Dbms
96/182
[email protected]/11/18
SSN SNAME GPA AGE DEPTNO
2007001003 CHENGLICHONG 3.33 20 31
2007001005 ZHONGWEILONG 3.62 2033
2007001006 WUYUANLANG 4.01 20 33
2006001001 LUOZI 3.12 20 34
2007002001 ZHUJIANGUO 3.05 19
The operator NOT IN can be used to check for datavalues that dont lie in a specific list of values.
Figure 25 Query Result of Example 10
Pattern match search
8/10/2019 Awesome Dbms
97/182
[email protected]/11/18
condition(LIKE/NOT LIKE)
The LIKE operator allows you create aSQL query that performs inexact patternmatching through the use of wildcard
characters.The % wildcard matches zero or morecharacters of any type.The _ wildcard matches exactly onecharacter of any type.
8/10/2019 Awesome Dbms
98/182
CON
8/10/2019 Awesome Dbms
99/182
[email protected]/11/18
CON...
[Example 12]To match all strings that end with
'ZHANG', the pattern would look like:
'%zhang':SELECT SNAMEFROM STUDENTWHERE SNAME LIKE '%zhang';
CON
8/10/2019 Awesome Dbms
100/182
[email protected]/11/18
CON...
[Example 13]To match all strings where the word
'zhang' occurs somewhere: '%zhang%':
SELECT SNAMEFROM STUDENTWHERE SNAME LIKE '%zhang%';
CON
8/10/2019 Awesome Dbms
101/182
[email protected]/11/18
CON...
[Example 14]To match strings with that begin with
zhang consisting of exactly eight
characters zhang _ _ _ SELECT SNAMEFROM STUDENTWHERE SNAME LIKE 'zhang _ _ _;
CON
8/10/2019 Awesome Dbms
102/182
[email protected]/11/18
CON...
[Example 15]To match strings that there are must be
exactly four characters in the string, the
END of which must be an _ _ _ g SELECT SNAMEFROM STUDENTWHERE SNAME LIKE ' _ _ _g;
CON
8/10/2019 Awesome Dbms
103/182
[email protected]/11/18
CON...
[Example 16]To match strings that there are at least one
character between 'a' and 'c' a_%c SELECT SNAMEFROM STUDENTWHERE SNAME LIKE 'a_%c';
If the search strings can include thewildcards(%,_) itself, we can use an escapecharacter to represent the wildcards.
For example, to match the string 20%, we canuse :
Like 20#% ESCAPE #
NULL search condition
8/10/2019 Awesome Dbms
104/182
[email protected]/11/18
NULL search condition
The operator NULL means the data valuefor the column is unknown or notavailable.
NULL is not synonymous withzero (numeric or binary value)a zero-length string,
blank (character value)
CON
8/10/2019 Awesome Dbms
105/182
[email protected]/11/18
CON...
Suppose that the "DEPTNO" column in the"STUDENT" table is optional. This means that ifwe insert a record with no value for the "DEPTNO " column, the " DEPTNO " column willbe saved with a NULL value.
We can select only the records with NULLvalues in the " DEPTNO " column by using theIS NULL operator:
[Example 17]SELECT * FROM studentWHERE DEPTNO IS NULL
CON
8/10/2019 Awesome Dbms
106/182
[email protected]/11/18
CON...
[Example 18]If we select only the records with no NULL
values in the " DEPTNO " column, we
will have to use the IS NOT NULLoperator:SELECT * FROM studentWHERE DEPTNO IS NOT NULL
Compound search condition
8/10/2019 Awesome Dbms
107/182
[email protected]/11/18
Compound search condition
The AND & OR operators are used to filterrecords based on more than onecondition.
The AND operator displays a record ifboth the first condition and the secondcondition is true.The OR operator displays a record ifeither the first condition or the secondcondition is true.
CON
8/10/2019 Awesome Dbms
108/182
[email protected]/11/18
CON...
[Example 19]If we want to select only the persons with
AGE equal to "20" AND GPA greater
than "3", we use the following SELECTstatement:SELECT *FROM student
WHERE AGE=20 AND GPA>3.5
Sorting Results (Order by Clause )
8/10/2019 Awesome Dbms
109/182
[email protected]/11/18
Sorting Results (Order by Clause )
SQL ORDER BY clause is used to sort the result-set by aspecified column or more columns.
[Example 20]If we want to sort our Users table by the GPA column, we
have to use the following ORDER BY SQL statement:SELECT * FROM studentORDER BY GPA
If you want to sort the records in a descending
order, you can use the DESC keyword.
CON
8/10/2019 Awesome Dbms
110/182
[email protected]/11/18
CON...
[Example 21]Now we want to select all the persons
from the table above, however, we want
to sort the AGE descending by their lastname.SELECT *FROM studentORDER BY AGE DESC
8/10/2019 Awesome Dbms
111/182
COUNT function
8/10/2019 Awesome Dbms
112/182
[email protected]/11/18
COUNT function
The COUNT function counts the number of rowsin a table, or the number of distinct values fora given column. It can operate, therefore, atthe column or row level.
[Example 22]To count the number of students names in the
Student table :SELECT COUNT(SNAME)FROM Student
CON
8/10/2019 Awesome Dbms
113/182
[email protected]/11/18
CON...
[Example 23]To count the number of distinct students names
represented in the students table, issue the following:SELECT COUNT(DISTINCT SNAME)FROM Student
The keyword DISTINCT is not considered an argument ofthe function. It simply specifies an operation to beperformed before the function is applied. WhenDISTINCT is coded, duplicate values are eliminated.If DISTINCT is not specified, then ALL is implicitlyspecified. ALL also can be explicitly specified in theCOUNT function. When ALL is specified, duplicate valuesare not eliminated.
AVG function
8/10/2019 Awesome Dbms
114/182
[email protected]/11/18
AVG function
The AVG function computes the averageof the values for the column orexpression specified as an argument.This function operates only on numericarguments.
[Example 24]The following example calculates the
average GPA of the students table:SELECT AVG(GPA)FROM Student
CON
8/10/2019 Awesome Dbms
115/182
[email protected]/11/18
CON...
[Example 25]If you want to get the average GPA for a
particular set Students you can do it this
way:SELECT AVG(GPA)FROM StudentWHERE DEPTNO=33
8/10/2019 Awesome Dbms
116/182
CON
8/10/2019 Awesome Dbms
117/182
[email protected]/11/18
CON...
The MAX function returns the largestvalue in the specified column orexpression.
[Example 27]The following SQL statement determines
the largest GPA :SELECT MAX(GPA)FROM Student
CON...
8/10/2019 Awesome Dbms
118/182
[email protected]/11/18
CON...
[Example 28]It returns the highest GPA belongs to a
student in DEPTNO 32:
SELECT MAX(GPA)FROM studentWHERE DEPTNO=32
SUM function
8/10/2019 Awesome Dbms
119/182
[email protected]/11/18
SUM function
The accumulated total of all values in thespecified column or expression arereturned by the SUM column function.
[Example 29]For example, the following SQL statement
calculates the total GPA for thestudents:
SELECT SUM(GPA)FROM Student
GROUP BY
8/10/2019 Awesome Dbms
120/182
[email protected]/11/18
GROUP BY
The GROUP BY statement is used inconjunction with the aggregatefunctions to group the result-set by oneor more columns.SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name)FROM table_name
WHERE column_name operator valueGROUP BY column_name
CON...
8/10/2019 Awesome Dbms
121/182
[email protected]/11/18
CON...
[Example 30]Want to find the average grade of each
student.
SELECT Avg(grade)FROM SCGROUP BY SSN
HAVING Clause
8/10/2019 Awesome Dbms
122/182
[email protected]/11/18
HAVING Clause
The HAVING clause was added to SQLbecause the WHERE keyword could notbe used with aggregate functions.
SQL HAVING Syntax:
SELECT column_name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_nameHAVING aggregate_function(column_name) operator value
CON...
8/10/2019 Awesome Dbms
123/182
[email protected]/11/18
CON...
[Example 31]Now we want to find if any of the
students have an average grade of
more than 81.
SELECT Avg(grade)FROM student
GROUP BY SSNHAVING Avg(grade)>80
CON...
8/10/2019 Awesome Dbms
124/182
[email protected]/11/18
CON...
[Example 32]Now we want to find if the students
"2007001006" or "2006001001" have
an average grade of less than 81.
SELECT SSN,Avg(grade)FROM student
WHERE SSN='2007001006' OR SSN =2006001001GROUP BY SSNHAVING Avg(grade)
8/10/2019 Awesome Dbms
125/182
[email protected]/11/18
functions1). Aggregate functions can be executed only in SELECT
statements.2). An aggregate function must be specified for an
explicitly named column or expression.3). Each aggregate function returns only one value for the
set of selected rows.4). If you apply an aggregate function to one column in a
SELECT statement, you must apply column functions toany other columns specified in the same SELECTstatement, unless you also use the GROUP BY clause.
5). Use GROUP BY to apply an aggregate function to agroup of named columns. Any other column named inthe SELECT statement must be operated on by anaggregate function.
CON...
8/10/2019 Awesome Dbms
126/182
[email protected]/11/18
CO ...
6). When using the AVG, MAX, MIN and SUM functions onnullable columns, all occurrences of NULL are eliminatedbefore applying the function.
7). You can use the DISTINCT keyword with all aggregatefunctions to eliminate duplicates before applying the
given function. DISTINCT has no effect, however, on theMAX and MIN functions.
8). You can use the ALL keyword to indicate that duplicatesshould not be eliminated. ALL is the default.
9). An aggregate function can be specified in a WHEREclause only if that clause is part of a sub query of aHAVING clause. Additionally, every column namespecified in the expression of the aggregate functionmust be a correlated reference to the same group.
Multiple Tables
8/10/2019 Awesome Dbms
127/182
[email protected]/11/18
p
SQL allows us to query multiple tables inone SELECT-FROM-WHERE statement.The SELECT and WHERE can refer to the
attributes of any of the tables once welist each table in the FROM clause.ANSI standard SQL specifies four typesof JOINs: INNER, OUTER, LEFT, andRIGHT.a table (base table, view, or joinedtable) can JOIN to itself in a self-join.
CON...
8/10/2019 Awesome Dbms
128/182
[email protected]/11/18
SSN SNAME GPA AGE DEPTNO
2007001003 CHENGLICHONG 20 31
2007001005 ZHONGWEILONG 20 33
2007001006 WUYUANLANG 4.01 20 33
2006001001 LUOZI 3.12 20 34
2006001001 GUOHUAXIAN 3.21 21 34
2007002001 ZHUJIANGUO 19
CON...
8/10/2019 Awesome Dbms
129/182
[email protected]/11/18
Note: The " Life Science " Department currentlyhas no listed students. Also, student "ZHUJIANGUO " has not been assigned to anyDepartment yet.
DEPTNO DEPTNAME
31 Computer Science
33 Information Engineering
34 Civil Engineering
35 Life Science
INNER JOIN
8/10/2019 Awesome Dbms
130/182
[email protected]/11/18
Inner join creates a new result table bycombining column values of two tables(A and B) based upon the join-predicate. The query compares each row of A with eachrow of B to find all pairs of rows which satisfythe join-predicate.When the join-predicate is satisfied, columnvalues for each matched pair of rows of A andB are combined into a result row.
CON...
8/10/2019 Awesome Dbms
131/182
[email protected]/11/18
The "implicit join notation" simply liststhe tables for joining (in the FROMclause of the SELECT statement), usingcommas to separate them.It specifies a cross-join, and the WHEREclause may apply additional filter-predicates (which function comparably
to the join-predicates in the explicitnotation).
CON...
8/10/2019 Awesome Dbms
132/182
[email protected]/11/18
[Example 33]The following example shows a query
using the inner join statement:
SELECT *FROM student, departmentWHERE student.DeptID =
department.DeptID
CON...
8/10/2019 Awesome Dbms
133/182
[email protected]/11/18
Student.
SSN
Student.SNA
ME
Student.
GPA
Student.
AGE
Student.D
EPTID
Department.D
EPTID
Department.DEP
TNAME2007001003
CHENGLICHONG
20 31 31 ComputerScience
2007001005
ZHONGWEILONG
20 33 33 InformationEngineering
2007001006
WUYUANLANG
4.01 20 33 33 InformationEngineering
2006001001
LUOZI 3.12 20 34 34 CivilEngineering
200600
1001
GUOHUAXI
AN
3.21 21 34 34 Civil
Engineering
OUTER JOIN
8/10/2019 Awesome Dbms
134/182
[email protected]/11/18
The OUTER JOIN clause differs from thestandard JOIN clause (also known asthe INNER JOIN clause) in that rows arereturned even when there are nomatches through the JOIN critieria.LEFT OUTER JOINRIGHT OUTER JOINFULL OUTER JOIN
LEFT OUTER JOIN
8/10/2019 Awesome Dbms
135/182
[email protected]/11/18
Select all the rows from the first tablelisted after the FROM clause, no matterif they have matches in the secondtable.
[Example 33]If we slightly modify our last SQL statement to:
SELECT *
FROM student LEFT OUTER JOIN departmentON student.DEPTID = department.DEPTID
CON...
8/10/2019 Awesome Dbms
136/182
[email protected]/11/18
Student.
SSN
Student.SNA
ME
Student.
GPA
Student.
AGE
Student.D
EPTID
Department.D
EPTID
Department.DEP
TNAME
200700
1003
CHENGLIC
HONG
20 31 31 Computer
Science
200700
1005
ZHONGWEI
LONG
20 33 33 Information
Engineering200700
1006
WUYUANL
ANG
4.01 20 33 33 Information
Engineering
200600
1001
LUOZI 3.12 20 34 34 Civil
Engineering200600
1001
GUOHUAXI
AN
3.21 21 34 34 Civil
Engineering
200700
2001
ZHUJIANG
UO
19
RIGHT OUTER JOIN
8/10/2019 Awesome Dbms
137/182
[email protected]/11/18
The RIGHT OUTER JOIN returns all rowsfrom the second table.
[Example 34]For example, this allows us to find each student and his or
her department, but still show departments that have nostudent.
SELECT *FROM student RIGHT OUTER JOIN department
ON student.DEPTID = department. DEPTID;
CON...
8/10/2019 Awesome Dbms
138/182
[email protected]/11/18
Student.SSN
Student.SNAME
Student.GPA
Student.AGE
Student.DEPTID
Department.DEPTID
Department.DEPT NAME
2007001003
CHENGLICHONG
20 31 31 Computer Science
2007001005
ZHONGWEILONG
20 33 33 InformationEngineering
2007001006
WUYUANLA NG
4.01 20 33 33 InformationEngineering
2006001001
LUOZI 3.12 20 34 34 Civil Engineering
2006001001
GUOHUAXIA N
3.21 21 34 34 Civil Engineering
35 Life Science
8/10/2019 Awesome Dbms
139/182
Student.S Student.SNAM Student.G Student.A Stude Departm Department.DEPT
8/10/2019 Awesome Dbms
140/182
[email protected]/11/18
SN E PA GE nt.
DEPT
ID
ent.
DEPTID
NAME
20070010
03
CHENGLICH
ONG
20 31 31 Computer Science
20070010
05
ZHONGWEIL
ONG
20 33 33 Information
Engineering20070010
06
WUYUANLA
NG
4.01 20 33 33 Information
Engineering
20060010
01
LUOZI 3.12 20 34 34 Civil Engineering
20060010
01
GUOHUAXIA
N
3.21 21 34 34 Civil Engineering
35 Life Science
20070020
01
ZHUJIANGU
O
19
8/10/2019 Awesome Dbms
141/182
Cont
8/10/2019 Awesome Dbms
142/182
[email protected]/11/18
[Example 37] : Find all pairs of studentswho have the same GPA.
select s1.SID, s2.SID
from Students s1, Students s2where s1.GPA = s2.GPA
and s1.SID < s2.SID
JOIN A TABLE TO ITSELF
8/10/2019 Awesome Dbms
143/182
[email protected]/11/18
[Example 38] : Find the names of allstudents whose GPA is higher thanCHENSHI 's GPA.
select s1.SNamefrom Student s1, Student s2where s2.SName = 'CHENGSHI'
and s1.GPA > s2.GPA
Cont
8/10/2019 Awesome Dbms
144/182
[email protected]/11/18
[Example 39] Find the names and GPAs of allstudents who take database systems.
select SName, GPA from Student, sc, Course
where cname= `DBS and Student.ssn = sc.ssnand sc.cno= Course.cn
Set Operation :Union Intersect& Minus
8/10/2019 Awesome Dbms
145/182
[email protected]/11/18
& Minus
SQL supports three set operations:union, intersect, minusUnion compatibility is required.
Consider the following two relations:G_Students(ssn, Name, GPA, GRE, Dept_Name)Instructors(ssn, Name, Office, Salary, Dept_Name)
Union
8/10/2019 Awesome Dbms
146/182
[email protected]/11/18
[Example 40]: Find the names of thosepeople who are either select lesson21001001 or lesson 22003002
(select SName from studentwhere ssn=any (select ssn from scwhere cno=21001001) )
union(select SName from students
where ssn=any (select ssn from scwhere cno=22003002) )
Cont
8/10/2019 Awesome Dbms
147/182
[email protected]/11/18
union removes duplicate rows.union all keeps duplicate rows.
Set Operation: Intersect
8/10/2019 Awesome Dbms
148/182
[email protected]/11/18
[Example 41] : Find the names of thosepeople who a select lesson21001001 and lesson 22003002 (select SName from student
where ssn=any (select ssn from scwhere cno=21001001) )
intersect(select SName from student
where ssn=any (select ssn from scwhere cno=22003002) )
Set Operation: Minus
8/10/2019 Awesome Dbms
149/182
[email protected]/11/18
[Example 42]: : Find the names of thosewho select lesson 21001001 but hasnot select the lesson 22003002
(select SName from studentwhere ssn=any (select ssn from sc
where cno=21001001) )minus(select SName from student
where ssn=any (select ssn from scwhere cno=22003002) )
Set Operation: IN & NOT IN
8/10/2019 Awesome Dbms
150/182
[email protected]/11/18
[Example 43]: : Find all students whoare 20, 21, or 19 years old.
select * from Student
where Age in (19, 20, 21)
NOT IN is the opposite of IN.
Sub queries
8/10/2019 Awesome Dbms
151/182
[email protected]/11/18
A subquery is a SELECT statement that isnested within another SQL statement.Return any number of values
Can be found in, the column list of aSELECT statement, a FROM, GROUP BY,HAVING, and/or ORDER BY clauses of aSQL statement.
CON
8/10/2019 Awesome Dbms
152/182
[email protected]/11/18
[Example 48]To find the names of every student who studies in the
same department as a person called Jones .
SELECT SNAMEFROM studentWHERE DEPTNO =
(SELECT DEPTNOFROM student
WHERE SNAME = 'JONES')
CON
8/10/2019 Awesome Dbms
153/182
[email protected]/11/18
Or as a join statement, like this:
SELECT e1. SNAME
FROM student e1,student e2WHERE e1. DEPTNO = e2. DEPTNO
AND e2. SNAME = 'JONES'
CON
8/10/2019 Awesome Dbms
154/182
[email protected]/11/18
[Example 49]: Find the names of allstudents who take at least onecourse titled multimedia.select sNamefrom Student s, SC ewhere s.ssn = e.ssn and e.cno in
(select cno from Coursewhere Cname = ' multimedia')
Nesting levels
8/10/2019 Awesome Dbms
155/182
[email protected]/11/18
SELECT select-listFROM .........WHERE (select-field1, select-
field2,.........)comparison operator
(SELECT select-list2
FROM........WHERE (..........))
comparison-operator:
8/10/2019 Awesome Dbms
156/182
[email protected]/11/18
ALL -- the comparison must be true forall returned values.ANY -- The comparison need only betrue for one returned value.IN may be used in place of = ANY.NOT IN may be used in place of !=ALL.
Cont
8/10/2019 Awesome Dbms
157/182
[email protected]/11/18
The previous query is a nestedquery.The query outside is an outer queryand the query nested under theouter query is an inner query.Multiple nesting's are allowed.The semantics of the above query isto evaluate the inner query first andevaluate the outer query last.Many nested queries haveequivalent non-nested versions.
Non Nested Equivalent
8/10/2019 Awesome Dbms
158/182
[email protected]/11/18
The previous query is equivalent to: (1)
select SName
from Student s, sc e, Course cwhere s.ssn = e.ssnand e.cno= c.cno and c.cname =multimedia'
Cont
8/10/2019 Awesome Dbms
159/182
[email protected]/11/18
(2)select SNamefrom Student where ssn in
(select ssn from scwhere Cno in(select Cno from Course
where cname = multimidea'))
Correlated Query
8/10/2019 Awesome Dbms
160/182
[email protected]/11/18
Definition: If some attributes of arelation declared in the from clause ofan outer query are referenced in thewhere clause of an inner query, then thetwo queries are said to be correlated,and the inner query is called acorrelated inner query.
CON
8/10/2019 Awesome Dbms
161/182
[email protected]/11/18
[Example 50]:Find the names of all students who has NOT select a
Course with CNO=1.
SELECT Sname
FROMStudentWHERE NOT EXISTS
(SELECT *
FROM SC
WHERE SSN =Student.SSN AND Cno=1)
Cont
8/10/2019 Awesome Dbms
162/182
[email protected]/11/18
Evaluation of correlated queries: for eachtuple in the outer query, evaluate theinner query once.
The scoping rule of attribute names:select ... from R1, ..., Rk where ...
(select ... from S1, ..., Smwhere S1.A = R2.B and C = D and ... )(1) If attribute C is not an attribute in S1,
..., Sm, and C is an attribute in some Ri,then C = Ri.C.
(2) If C is in both Sj and Ri, then C = Sj.C.
Cont
8/10/2019 Awesome Dbms
163/182
[email protected]/11/18
[Example 51]: : Find the names of thosestudents who are 18 or younger andwhose GPA is higher than the GPA ofsome students who are 20 or older.
select sName from Studentwhere Age some(select GPA from Studentwhere Age >= 20)
Other set comparison operators:
8/10/2019 Awesome Dbms
164/182
[email protected]/11/18
any, all,
8/10/2019 Awesome Dbms
165/182
[email protected]/11/18
[Example 52]: Find all students whotake at least one course.
select * from Student s where exists
(select * from scWhere ssn= s.ssn)
8/10/2019 Awesome Dbms
166/182
Cont
8/10/2019 Awesome Dbms
167/182
[email protected]/11/18
The previous query is equivalent to: (1) select s.*
from Student s, sc e
where s.SID = e.SID(2) select * from Student where ssn in
(select ssn from sc)
Cont
8/10/2019 Awesome Dbms
168/182
[email protected]/11/18
[Example 53]: Find all students who donot take 21003001 .
select * from Student s where not exists(select * from scwhere ssn= s.ssnand Cno = '21003001.')This query is equivalent to:
select * from Student where ssn not in(select ssn from scwhere Cno = '21003001.')
8/10/2019 Awesome Dbms
169/182
[email protected]/11/18
8/10/2019 Awesome Dbms
170/182
[email protected]/11/18
[Example 54]:Find the names of all students who study in thesame department with a student with sname=liucheng . SELECT ssn Sname DEPTNO
FROM Student S1WHERE EXISTS
SELECT *FROM Student S2WHERE S2.DEPTNO = S1.DEPTNO AND
S2.Sname = liucheng '
Cont
8/10/2019 Awesome Dbms
171/182
[email protected]/11/18
[Example 55]: Find all the students whotake all courses select * from Student swhere not exists
(select * from Course cwhere not exists
(select * from sc
where ssn= s.ssnand Cno = c.Cno))
Cont
8/10/2019 Awesome Dbms
172/182
[email protected]/11/18
[Example 56] : Find the names and GPAs ofthose students who take all courses takenby a student with SID = 2006002001.
select Name, GPA from Student swhere not exists
(select * from Course cwhere Cno in(select Cno from scwhere ssn= 2006002001) and not exists
(select * from sc ewhere ssn=e.ssn and Cno =
c.Cno))
Scalar Functions of DB2
8/10/2019 Awesome Dbms
173/182
[email protected]/11/18
Scalar functions are applied to a columnor expression and operate on a singlevalue.The result of a scalar function is a transformedversion of the column or expression beingoperated on.The transformation of the value is based onthe scalar function being applied and the value
itself.
Cont
8/10/2019 Awesome Dbms
174/182
[email protected]/11/18
TRUNCATE or TRUNC Converts the first numeric argument by truncating it to the
right of the decimal place by the integer numberspecified in the second numeric argument.
[Example 34]
SELECT TRUNC(3.014015,2)FROM SYSIBM.SYSDUMMY1;
This SQL statement returns the number 3.010000, becausethe second argument specified that only 2 significantdigits are required. The rest was truncated.
Cont
8/10/2019 Awesome Dbms
175/182
[email protected]/11/18
ROUNDRounds the first numeric argument to the
number of places specified in the secondargument.
UPPER or UCASEConverts a character string into all uppercase
characters LOWER or LCASE
Converts a character string into all lowercasecharacters.
Cont
8/10/2019 Awesome Dbms
176/182
[email protected]/11/18
SUBSTRReturns the specified portion of a character column from
any starting point to any ending point.[Example 45]SNAME is a CHAR(20) column in sample table STUDENT.
When SNAME has the value ZHONGWEILONG: Function: Returns:
-----------------------------------SUBSTR(SNAME,2,3) -- 'HON'SUBSTR(SNAME,2) -- ' HONGWEILONG'
SUBSTR(SNAME,2,12) -- ' HONGWEILONG ' followed by one blankSUBSTR(SNAME,13) -- a zero-length stringSUBSTR(SNAME,13,4) -- four blanks
Cont
8/10/2019 Awesome Dbms
177/182
[email protected]/11/18
LTRIMThe LTRIM function removes blanks or
hexadecimal zeros from the beginning ofa string expression.
RTRIMThe RTRIM function removes blanks or
hexadecimal zeros from the end of astring expression.
Cont
8/10/2019 Awesome Dbms
178/182
[email protected]/11/18
CHARThe CHAR function returns a fixed-length
character string representation of theargument .
[Example 46]SELECT CHAR(CURRENT DATE)
CURRENT DATE is a DATE type which displays current datetime of the system server. When it represents the date15 March 2011, the example returns the string value'3/15/2011 in character string .
Cont
8/10/2019 Awesome Dbms
179/182
[email protected]/11/18
CONCATThe CONCAT function combines two compatible
string arguments.[Example 47]Using sample table DSN8910.EMP, concatenate
column FIRSTNME with column LASTNAME.Both columns are defined as varying-lengthcharacter strings.
SELECT CONCAT(FIRSTNME, LASTNAME)FROM DSN8910.EMP;
Cont
8/10/2019 Awesome Dbms
180/182
[email protected]/11/18
WEEK The WEEK function returns an integer in the
range of 1 to 54 that represents the week ofthe year. The week starts with Sunday, and
January 1 is always in the first week. DAY
The DAY function returns the day part of a value.If the argument is a date, timestamp, or string
representation of either, the result is the daypart of the value, which is an integer between1 and 31
Cont
8/10/2019 Awesome Dbms
181/182
[email protected]/11/18
DATEThe DATE function converts a value representing
a date to a DB2 date. The value to beconverted can be a DB2 timestamp, a DB2
date, a positive integer, or a character string.MONTH
The MONTH function returns the month part of avalue. If the argument is a date, timestamp, or
string representation of either, the result is themonth part of the value, which is an integerbetween 1 and 12.
Cont
8/10/2019 Awesome Dbms
182/182
TIMEThe TIME function Converts a value representing
a valid time to a DB2 time. The value to beconverted can be a DB2 timestamp, a DB2
time, or a character string.
YEAR The YEAR function returns the year part of a
l th t i h t g hi t i g Th