Chapter 4-1 CSE 4701 Chapter 4 6e & 8 5e: Basic SQL Prof. Steven A. Demurjian, Sr. Computer Science...
-
Upload
piers-owen -
Category
Documents
-
view
240 -
download
2
Transcript of Chapter 4-1 CSE 4701 Chapter 4 6e & 8 5e: Basic SQL Prof. Steven A. Demurjian, Sr. Computer Science...
Chapter 4-1
CSE 4701
Chapter 4 6e & 8 5e: Basic SQL
Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department
The University of Connecticut191 Auditorium Road, Box U-155
Storrs, CT [email protected]
http://www.engr.uconn.edu/~steve(860) 486 - 4818
About one third of these slides are being used with the permission of Dr. Ling Lui, Associate Professor, College of Computing, Georgia Tech.
About one-half of these slides have been adapted from the AWL web site for the textbook.
Chapter 4-2
CSE 4701
Relational Languages
A Relational Language Defines Operations to Manipulate Relations Used to Specify Retrieval Requests (Queries) Query Result is Expressed in the Form of a Relation
Classification Relational Algebra (We’ve Discussed) Relational Calculus
To be Briefly Explored as the Basis of ... Structured Query Language (SQL)
Chapter 4-3
CSE 4701
Based on First-Order Predicate Logic Symbol Alphabet
Logic Symbols (e.g., ¬a Set of Constantsa Set of Variablesa Set of n-ary Predicatesa Set of n-ary FunctionsParentheses
Expressions (called well-formed formulae (wff)) Built from this Symbol Alphabet
Classification: Tuple Relational Calculus Domain Relational Calculus
Relational Calculus
Chapter 4-4
CSE 4701
Tuple Relational Calculus
The Primitive Variable is a Tuple Variable Which Specifies a Tuple of a Relation Ranges Over the Tuples of a Relation
In Tuple Relational Calculus, Queries are Specified as {t | F(t)}where t is a Tuple Variable and F is a Formula Consisting of the Atoms and Operators
Chapter 4-5
CSE 4701
EMP(ENO, ENAME, AGE)
PROJ(PNO, PNAME, LOC, MGR)
WORKS(ENO, PNO, DUR) Find the Names of Employees under age 30 { t[ENAME] | tEMP t[AGE]<30}
Find the Names of Employees working on the CAD/CAM Project
{ t[ENAME] | tEMP u(u WORKS t[ENO]uv(vPROJu[PNO]=v[PNO] v[PNAME]=‘CAD/CAM’))
Example
ENAME
(AGE < 30
(EMP))
ENAME
(PNAME=‘CAD/CAM”
(PROJ) PNO (WORKS ENOEMP))
Chapter 4-6
CSE 4701
A formula F is Composed of Atoms Boolean operators ¬ Existential Qualifier Universal Qualifier
Formation rules: Each Atom is a Formula If F and G are Formulae, so are FG, FG, ¬F, and
¬G If F is a Formula, so is (F) If F is a Formula and t is a Free variable in F, then t(F) and t(F) are also Formulae
Nothing else is a Formula
Tuple Relational Calculus
Chapter 4-7
CSE 4701
The Atoms are the Following :• Tuple variables R.t or R(t)• Conditions
s[A] t where s and t are Tuple Variables and A and B are
Components of s and t, Respectively, and
<><=>=specifies that Component A of s stands in relation to component B of t (e.g., s[SALARY] > t[SALARY])
s[A] c where s, A and are as Defined above and c is a Constant
e.g., s[NAME] = 'Smith'.
Tuple Relational Calculus
Chapter 4-8
CSE 4701
Find the names of Employees who have Worked for a Project for more than Two Years { t[ENAME] | tEMP u(u WORKS t[ENO]u
u[DUR]=‘24’))
Find all Managers who are less than 40 years old? { t[MGR] | tPROG u(u WORKS t[PNO]uPN
v(vEMPu[ENO]=v[ENO] v[AGE]<40))
Example
MGR
(AGE<40
EMP ENO (WORKS PNOPROJ))
ENAME
(DUR=24
(WORKS) ENO EMP)
Chapter 4-9
CSE 4701
SQL is a Partial Example of a Tuple Relational Language Simple Queries are all Declarative More Complex Queries are both Declarative and
Procedural (e.g., joins, nested queries) Find the names of employees working on the CAD/CAM
projectSELECT EMP.ENAMEFROM EMP, WORKS, PROJWHERE (EMP.ENO= WORKS.ENO) AND (WORKS.PNO = PROJ.PNO) AND (PROJ.PNAME = “CAD/CAM”)
Tuple Variables are Implicit
SQL: Tuple Relational Calculus-Based
Chapter 4-10
CSE 4701
PNAME, PNAME1
(PROJ LOC = LOC1 PROJ1)
Let Proj1(PNAME1, LOC1) = PNAME, LOC
(PROJ)
Explicit Tuple Variables
Find the Pairs of all Project Names for those Projects that are Located at the same Place
SELECT (P1.PNAME, P2.PNAME)
FROM PROJ P1, PROJ P2
WHERE P1.LOC = P2.LOC
Chapter 4-11
CSE 4701
SQL Components Data Definition Language (DDL)
For External and Conceptual Schemas Views - DDL for External Schemas
Data Manipulation Language (DML) Interactive DML Against External and Conceptual
Schemas Embedded DML in Host PLs (EQL, JDBC, etc.)
Others Integrity (Allowable Values/Referential) Catalog and Dictionary Facilities Transaction Control (Long-Duration and Batch) Authorization (Who can Do What When)
Chapter 4-12
CSE 4701
SQL DDL and DML
Data Definition Language (DDL) Defining the Relational Schema - Relations,
Attributes, Domains - The Meta-DataCREATE TABLE Student: Name(CHAR(30)), SSN(CHAR(9)), GPA(FLOAT(2))CREATE TABLE Courses: Course#(CHAR(6)), Title(CHAR(20)),
Descrip(CHAR(100)), PCourse#(CHAR(6)) Data Manipulation Language (DML)
Defining the Queries Against the SchemaSELECT Name, SSNFrom Student Where GPA > 3.00
Chapter 4-13
CSE 4701
History of SQL
SQL is based on the Relational Tuple Calculus Evolved from SEQUEL: Structured English QUEry
Language - part of IBM’s SYSTEM R, 1974 SQL2 Supported by
ORACLE, SYBASE, INFORMIX, IBM DB2, SQL SERVER, … MS Access, MySQL, …
SQL2 also called SQL/92 is evolved from SQL/86, SQL/89, all were ANSI & ISO standard
Ongoing work on SQL3 with OO Extensions
Chapter 4-14
CSE 4701
Data Definition Language - DDL
A Pre-Defined set of Primitive Types Numeric Character-string Bit-string Additional Types
Defining Domains Defining Schema Defining Tables Defining Views Note: Each DBMS May have their Own DBMS
Specific Data Types - Is this Good or Bad?
Chapter 4-15
CSE 4701
DDL - Primitive Types
Numeric INTEGER (or INT), SMALLINT REAL, DOUBLE PRECISION FLOAT(N) Floating Point with at Least N Digits DECIMAL(P,D) (DEC(P,D) or NUMERIC(P,D))
have P Total Digits with D to Right of Decimal Note that INTs and REALs are Machine Dependent
(Based on Hardware/OS Platform)
Chapter 4-16
CSE 4701
DDL - Primitive Types
Character-String CHAR(N) or CHARACTER(N) - Fixed VARCHAR(N), CHAR VARYING(N), or
CHARACTER VARYING(N) Variable with at Most N Characters
Bit-Strings BIT(N) Fixed VARBIT(N) or BIT VARYING(N)
Variable with at Most N Bits
Chapter 4-17
CSE 4701
DDL - Primitive Types
These Specialized Primitive Types are Used to: Simplify Modeling Process Include “Popular” Types Reduce Composite Attributes/Programming
DATE : YYYY-MM-DD TIME: HH-MM-SS TIME(I): HH-MM-SS-F....F - I Fraction Seconds TIME WITH TIME ZONE: HH-MM-SS-HH-MM TIME-STAMP:
YYYY-MM-DD-HH-MM-SS-F...F{-HH-MM} NOTE: Different DBMS have Different Date/Time
Chapter 4-18
CSE 4701
DDL - What are Domains?
Domains are Similar in Concepts to Programming Language Type Definitions
A Domain can be Defined as Follows:CREATE DOMAIN CITY CHAR(15) DEFAULT ‘<Storrs>’;
CREATE DOMAIN SSNFORMAT CHAR(9); Advantage of Using Domains
Changing a Domain Definition in One Place Changes it Consistently Everywhere it is Used
Default Values Can Be Defined for Domains Constraints Can Be Defined for Domains
Chapter 4-19
CSE 4701
DDL - Dropping a Domain
A Domain is Dropped As Follows:
DROP DOMAIN CITY RESTRICT;
DROP DOMAIN SSNFORMAT CASCADE; Restrict:
Drop Operation Fails If the Domain is Used in Column Definitions
Cascade: Drop Operation Causes Columns to be Defined
Directly on the Underlying Data Type
Chapter 4-20
CSE 4701
What is a SQL Schema?
A Schema in SQL is the Major Meta-Data Construct Create a DB to Contain Multiple Tables
Supports the Definition of: Relation - Table with Name Attributes - Columns and their Types Identification - Primary Key Constraints - Referential Integrity (FK)
Two Part Definition CREATE Schema - Named Database or
Conceptually Related Tables CREATE Table - Individual Tables of the Schema
Chapter 4-21
CSE 4701
DDL-Create/Drop a Schema
Creating a Schema:CREATE SCHEMA MY_COMPANY AUTHORIZATION Demurjian; Schema MY_COMPANY bas Been Created and is
Owner by the User “Demurjian” Tables can now be Created and Added to Schema
Dropping a Schema:DROP SCHEMA MY_COMPANY RESTRICT;DROP SCHEMA MY_COMPANY CASCADE; Restrict:
Drop Operation Fails If Schema is Not Empty Cascade:
Drop Operation Removes Everything in the Schema
Chapter 4-22
CSE 4701
DDL - Create TablesCREATE TABLE EMPLOYEE
( FNAME VARCHAR(15) NOT NULL ,MINIT CHAR ,LNAME VARCHAR(15) NOT NULL ,SSN CHAR(9) NOT NULL ,BDATE DATEADDRESS VARCHAR(30) ,SEX CHAR ,SALARY DECIMAL(10,2) ,SUPERSSN CHAR(9) ,DNO INT NOT NULL ,PRIMARY KEY (SSN) ,FOREIGN KEY (SUPERSSN)
REFERENCES EMPLOYEE(SSN) ,FOREIGN KEY (DNO)
REFERENCES DEPARTMENT(DNUMBER) ) ;
Chapter 4-23
CSE 4701
DDL - Create Tables (continued)
CREATE TABLE DEPARTMENT ( DNAME VARCHAR(15) NOT NULL ,
DNUMBER INT NOT NULL ,MGRSSN CHAR(9) NOT NULL , MGRSTARTDATE DATE , PRIMARY KEY (DNUMBER) , UNIQUE (DNAME) ,FOREIGN KEY (MGRSSN) REFERENCES EMPLOYEE(SSN) ) ;
CREATE TABLE DEPT_LOCATIONS (DNUMBER INT NOT NULL ,
DLOCATION VARCHAR(15) NOT NULL , PRIMARY KEY (DNUMBER, DLOCATION) ,
FOREIGN KEY (DNUMBER) REFERENCES DEPARTMENT(DNUMBER) ) ;
Chapter 4-24
CSE 4701
DDL - Create Tables (continued)
CREATE TABLE PROJECT (PNAME VARCHAR(15) NOT NULL ,
PNUMBER INT NOT NULL ,PLOCATION VARCHAR(15) , DNUM INT NOT NULL , PRIMARY KEY (PNUMBER) , UNIQUE (PNAME) ,
FOREIGN KEY (DNUM) REFERENCES DEPARTMENT(DNUMBER) ) ;
CREATE TABLE WORKS_ON (ESSN CHAR(9) NOT NULL , PNO INT NOT NULL ,
HOURS DECIMAL(3,1) NOT NULL , PRIMARY KEY (ESSN, PNO) , FOREIGN KEY (ESSN)
REFERENCES EMPLOYEE(SSN) ,FOREIGN KEY (PNO)
REFERENCES PROJECT(PNUMBER) ) ;
Chapter 4-25
CSE 4701
DDL - Create Tables with Constraints
CREATE TABLE EMPLOYEE( . . . ,DNO INT NOT NULL DEFAULT 1,CONSTRAINT EMPPK
PRIMARY KEY (SSN) ,CONSTRAINT EMPSUPERFK
FOREIGN KEY (SUPERSSN) REFERENCES EMPLOYEE(SSN)ON DELETE SET NULLON UPDATE CASCADE ,
CONSTRAINT EMPDEPTFKFOREIGN KEY (DNO) REFERENCES DEPARTMENT(DNUMBER) ON DELETE SET DEFAULT ON UPDATE CASCADE );
Chapter 4-26
CSE 4701
DDL - Create Tables with Constraints
CREATE TABLE DEPARTMENT( . . . ,MGRSSN CHAR(9) NOT NULL
DEFAULT '888665555' ,. . . ,CONSTRAINT DEPTPK
PRIMARY KEY (DNUMBER) ,CONSTRAINT DEPTSK
UNIQUE (DNAME),CONSTRAINT DEPTMGRFK
FOREIGN KEY (MGRSSN) REFERENCES EMPLOYEE(SSN)ON DELETE SET DEFAULTON UPDATE CASCADE );
Chapter 4-27
CSE 4701
CREATE TABLE Supplier_Parts ( S# CHAR(5) NOT NULL, P# CHAR(6) NOT NULL, QTY INTEGER, PRIMARY KEY (S# P#) FOREIGN KEY S# REFERENCE SUPPLIER
ON DELETE CASCADE, REFERENCE PART
ON DELETE RESTRICT);
Create and Drop: Summary Defines Types and Order of Attributes in a Relation May Specify Which Attribute Are Keys and Which
Cannot Be Null Create a New Empty Table May Define DELETION Effect by Cascade/Restricted
Chapter 4-28
CSE 4701
SQL Data Definition
Drop Table A Relation Can Be Dropped at Any Time Drop Will Delete Both Definition and Data All Views, Indexes, and FKs are Dropped
DROP TABLE SUPPLIER; Alter Table
Add New Attributes or PK and FK to the Table All Existing Records are Expanded With Nulls, but
Not Physically Changed.ALTER TABLE SUPPLIERADD DISCOUNT SMALLINT;
Chapter 4-29
CSE 4701
DDL - Drop Tables
Command:
DROP TABLE EMPLOYEE RESTRICT;
DROP TABLE DEPARTMENT CASCADE; Restrict:
Drop Operation fails if the Table is Referenced by View and/or Constraint Definitions
Cascade: Drop Operation Removes Referencing View and
Constraint Definitions
Chapter 4-30
CSE 4701
DDL - Change Table Structure
Add a Column to a Table:
ALTER TABLE EMPLOYEE
ADD JOB VARCHAR(12); No DEFAULT Implies NULL Values for all Tuples
Drop a Column from a tableALTER TABLE EMPLOYEE DROP JOB RESTRICT (or CASCADE);
Restrict: Drop Operation Fails if Column is Referenced
Cascade: Drop Operation Removes Referencing View and Constraint Definitions
Chapter 4-31
CSE 4701
Chinook sql file
Chapter 4-32
CSE 4701
Chinook sql file
Chapter 4-33
CSE 4701
Chinook sql file
Chapter 4-34
CSE 4701
Chinook sql file
Chapter 4-35
CSE 4701
Chinook sql file
Chapter 4-36
CSE 4701
Data Manipulation Language - DML
SQL has the SELECT Statement for Retrieving Info. from a Database (Not Relational Algebra Select)
SQL vs. Formal Relational Model SQL Allows a Table (Relation) to have Two or More
Identical Tuples in All Their Attribute Values Hence, an SQL Table is a Multi-set (Sometimes
Called a Bag) of Tuples; it is Not a Set of Tuples SQL Relations Can Be Constrained to Sets by
PRIMARY KEY or UNIQUE Attributes Using the DISTINCT Option in a Query
Chapter 4-37
CSE 4701
Interactive DML - Main Components
Select-from-where Statement Contains: Select Clause - Chosen Attributes/Columns From Clause - Involved Tables Where Clause - Constrain Tuple Values Tuple Variables - Distinguish Among Same Names
in Different Tables String Matching - Detailed Matching Including
ExactStarts WithNear
Ordering of Rows - Sorting Tuple Results
Chapter 4-38
CSE 4701
Interactive DML - Main Components
Select-from-where Statement Contains: Set Operations - Search to See if a Value is in Set Built-in Functions - Count, Mix, Max, Sum, Avg Nested Subqueries - Queries within Queries Joins - As Discussed for Relational Algebra Recursive Queries (Defer - Part of SQL3) Modification-Based Selects for
Insert - Create a New TupleDelete - Remove Existing Tuple(s)Update - Change Existing Tuple(s)
Chapter 4-39
CSE 4701 SELECT target-list
FROM relation-listWHERE condition or subqueryGROUP BY attribute-listHAVING conditionORDER BY attribute-list
Skeleton Query:
SELECT - relational “project” WHERE - relational “select” and/or “join”
In principle, a SQL query equals to an algebra expression
target-listconditionrelation-list
SQL Data Manipulation
Chapter 4-40
CSE 4701
Format:
Equivalent Algebra Statement:
SELECT Specifies the Columns of the Query Result FROM Specifies the Tables to Be Used in the Query WHERE Specifies the Query Condition
Restriction: Must Refer to Columns of the Tables in the FROM Clause
SELECT A1, A2, ... An
FROM R1 , R2 , ... Rm
WHERE Predicate (Boolean/Set Expression)
p A1 , A2 , ... An ( s P(R1 R 2 R m)) ...
Simple Select-From-Where
Chapter 4-41
CSE 4701
Recall Prior Schema
Chapter 4-42
CSE 4701
…and Corresponding DB Tables
Which Represent Tuples/Instances of Each Relation
1455
ASCnullWBnullnull
Chapter 4-43
CSE 4701
…and Corresponding DB Tables
Chapter 4-44
CSE 4701
Simple SQL Queries
Query 0: Retrieve the Birthdate and Address of the Employee whose Name is 'John B. Smith'.SELECT BDATE, ADDRESSFROM EMPLOYEEWHERE FNAME='John' AND MINIT='B’ AND LNAME='Smith’
Which Row(s) are Selected?
Note: While All of these Next Queries are from Chapter 4, Some are From “Earlier” Edition
BSCnullWB nullnull
Chapter 4-45
CSE 4701
Simple SQL Queries
Query 1: Retrieve Name and Address of all Employees who work for the 'Research' DepartmentSELECT FNAME, MINIT, LNAME, ADDRESS, DNAMEFROM EMPLOYEE, DEPARTMENTWHERE DNAME='Research' AND DNUMBER=DNO
What Action is Being Performed?
Chapter 4-46
CSE 4701
Simple SQL Queries - Result
Theta Join on DNO=DNUMBER
Chapter 4-47
CSE 4701
Simple SQL Queries – Fully Qualified
The Full Table Name with “.” Notation Differentiates Among the Attributes
Query 1: Retrieve Name and Address of all Employees who work for the 'Research' DepartmentSELECT EMPLOYEE.FNAME, EMPLOYEE.MINIT,
EMPLOYEE. LNAME,EMPLOYEE.ADDRESS, DEPARTMENT.DNAMEFROM EMPLOYEE, DEPARTMENTWHERE DEPARTMENT.DNAME='Research' AND
DEPARTMENT.DNUMBER= EMPLOYEE.DNO
Chapter 4-48
CSE 4701
Simple SQL Queries
Query 2: For Every Project in 'Stafford', list the Project Number, the Controlling Dept. Number, and the Dept. Manager's Last Name, Address, and BirthdateSELECT PNUMBER, DNUM, LNAME, BDATE,ADDRESSFROM PROJECT, DEPARTMENT, EMPLOYEEWHERE DNUM=DNUMBER AND MGRSSN=SSN AND
PLOCATION='Stafford' In Q2, there are Two Join Conditions:
The Join Condition DNUM=DNUMBER Relates a Project to its Controlling Department
The Join Condition MGRSSN=SSN Relates the Controlling Department to the Employee who Manages that Department
Chapter 4-49
CSE 4701
Query Results
ASCnullWBnullnull
SELECT PNUMBER, DNUM, LNAME, BDATE,ADDRESSFROM PROJECT, DEPARTMENT, EMPLOYEEWHERE DNUM=DNUMBER AND MGRSSN=SSN AND
PLOCATION='Stafford'
Chapter 4-50
CSE 4701
Qualification of Attributes
In SQL, the Same Name for Two (or More) Attributes is Allowed if Attributes are in Different Relations
In Those Cases, Query Must Qualify by Prefixing the Relation Name to the Attribute Name EMPLOYEE.LNAME, DEPARTMENT.DNAME
Aliases: When Queries Must Refer to the Same Relation Twice Alias is Akin to a Variable in a PL - Reference In These Situations, it is Considered that there are
Two Different Copies of the Same Relation Let’s See Examples of Both Concepts
Chapter 4-51
CSE 4701
Attribute Qualification
Query 8: For Each Employee, Retrieve the Employee's Name, and Name of his or her Immediate SupervisorSELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE E SWHERE E.SUPERSSN=S.SSN
E and S are aliases for the EMPLOYEE relation E Represents Employees in the Role of Supervisees S Represents Employees in the Role of Supervisor
Another Form of Query 8 is:SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAMEFROM EMPLOYEE AS E, EMPLOYEE AS SWHERE E.SUPERSSN=S.SSN
Chapter 4-52
CSE 4701
Query Results
ASCnullWBnullnull
SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAMEFROM EMPLOYEE AS E, EMPLOYEE AS SWHERE E.SUPERSSN=S.SSN
Chapter 4-53
CSE 4701
Unspecified WHERE Clause
A Missing Where-clause Indicates No Condition; All Tuples of Relations in From-clause Are Selected
Query 9: Retrieve the SSN Values for All EmployeesSELECT SSNFROM EMPLOYEE
More Than One Relation and No Join Condition Results in the CARTESIAN PRODUCT of Tuples
Query 10: SELECT SSN, DNAMEFROM EMPLOYEE, DEPARTMENT
Overlooking Selection and Join Conditions in the Where-Clause Likely Yields Incorrect and Very Large Relations May Result
Chapter 4-54
CSE 4701
Use of * and Distinct
When a * is Used, All of the Attributes are ChosenQ1C:SELECT *FROM EMPLOYEEWHERE DNO=5
Q1D:SELECT *FROM EMPLOYEE, DEPARTMENTWHERE DNAME='Research' AND DNO=DNUMBER
SQL Does Not Support Sets so Duplicates are RetrievedQ11: SELECT SALARY FROM EMPLOYEE
Distinct Removes Duplicates Q11A: SELECT DISTINCT SALARY FROM EMPLOYEE
Chapter 4-55
CSE 4701
SELECT * in MySQL WorkBench
Chapter 4-56
CSE 4701
SELECT * in MySQL WorkBench
Chapter 4-57
CSE 4701
Set Operations - Union/Intersection/Minus
Not all DBMS Support Intersection/Minus Union: The two Relations must have Same Attributes
and the Attributes must Appear in the Same Order Query 4: All Project Numbers for Projects with
Employee 'Smith' as a Worker or as a Manager (SELECT PNAMEFROM PROJECT, DEPARTMENT, EMPLOYEEWHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith')UNION(SELECT PNAMEFROM PROJECT, WORKS_ON, EMPLOYEEWHERE PNUMBER=PNO AND ESSN=SSN AND
LNAME='Smith')
Chapter 4-58
CSE 4701
Set Operations - Union/Intersection/Minus
Utilizing the DISTINCT KEYWORD Query 4: Make a list of all project numbers for projects
that involve an employee whose last name is ‘Smith’, either as a worker or as a manager of the department that controls the project.(SELECT DISTINCT PNAMEFROM PROJECT, DEPARTMENT, EMPLOYEEWHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith')UNION(SELECT DISTINCT PNAMEFROM PROJECT, WORKS_ON, EMPLOYEEWHERE PNUMBER=PNO AND ESSN=SSN AND
LNAME='Smith')
Chapter 4-59
CSE 4701
Substring Comparison in SQL Queries
In Regard to Strings, Most DBMSs Support SQL Queries for Exact, Near, and Starts with Matching
LIKE is Used to Compare Partial Strings '%' (or '*') Replaces an Arbitrary # of characters
'_' replaces a single arbitrary character Query 12: Retrieve all Employees whose Address is in
Houston, Texas. SELECT FNAME, LNAMEFROM EMPLOYEEWHERE ADDRESS LIKE '%Houston,TX% '
Houston, TX can be anywhere within the ADDRESS VAR CHAR String
Chapter 4-60
CSE 4701
Substring Comparison in SQL Queries
The LIKE Operator Allows us to get Around the Fact that each Value is Considered Atomic and Indivisible
SQL: Character String Attribute values are not Atomic Query 12A: Retrieve all employees who were born
during the 1950s. SELECT FNAME, LNAMEFROM EMPLOYEEWHERE BDATE LIKE ' __5_______'
There are two “_” before 5 and seven “_” after 5
Chapter 4-61
CSE 4701
Arithmetic Operations in SQL Queries
Standard Arithmetic Operators '+', '-'. '*', and '/' can be Applied to Numeric Values in an SQL Query Result
Query 13: Show the Effect of Giving all Employees who work on the 'ProductX' project a 10% raise.SELECT FNAME, LNAME, 1.1*SALARYFROM EMPLOYEE, WORKS_ON, PROJECTWHERE SSN=ESSN AND PNO=PNUMBER
AND PNAME='ProductX'
Chapter 4-62
CSE 4701
ORDER BY Clause in SQL Queries
ORDER BY used to Sort the Tuples in a Query Result based on the Values of one or More Attribute(s)
Query 15: Retrieve a list of Employees and the Projects each works in, ordered by Dept., and within each Dept., alphabetically by Employee last nameSELECT DNAME, LNAME, FNAME, PNAMEFROM DEPARTMENT, EMPLOYEE,
WORKS_ON, PROJECTWHERE DNUMBER=DNO AND SSN=ESSN
AND PNO=PNUMBERORDER BY DNAME, LNAME
Default is Ascending - Can be ASC/DESC as we’ll see in a Later Example in Chapter 5
Chapter 4-63
CSE 4701
Natural Join Queries
Specially Tells SQL that a Natural Join is Defined Between Tables
SELECT * FROM COUNTRIES NATURAL JOIN CITIES SELECT * FROM COUNTRIES JOIN CITIES USING
(COUNTRY, COUNTRY_ISO_CODE) Note that * Expands the JOIN to:
All the common columns Every column in the first (left) table that is not a
common column Every column in the second (right) table that is not a
common column Natural Join in the FROM LIST
Chapter 4-64
CSE 4701
Homework 3 from Spr 2015 Problem 6.18 from the 6th
edition done in SQL and NOT relational expressions
Chapter 4-65
CSE 4701
Problem 6.18 in 6th edition
a. How many copies of the book titled The Lost Tribe are owned by the library branch whose name is ‘Sharpstown’?
SELECT NoOfCopiesFROM ( (BOOK NATURAL JOIN BOOK_COPIES )
NATURAL JOIN LIBRARY_BRANCH )WHERE Title='The Lost Tribe' AND BranchName='Sharpstown’
Ans = No_Of_Copies( (BranchName=‘Sharpstown’ (LIBRARY-BRANCH)) * BaB)
BranchID
BaB= (BOOKCOPIES *(Title=‘The Lost Tribe’
(BOOK))) )
BookId
Chapter 4-66
CSE 4701
Problem 6.18 in 6th edition
b. How many copies of the book titled The Lost Tribe are owned by eachlibrary branch?
SELECT BranchName, NoOfCopiesFROM ( (BOOK NATURAL JOIN BOOK_COPIES )
NATURAL JOIN LIBRARY_BRANCH )WHERE Title='The Lost Tribe'
Ans = BranchName, No_Of_Copies( (Title=‘The Lost Tribe’ (BOOK)) * CaB)
BookId
CaB = BOOKCOPIES * LIBRARY_BRANCH)BranchId
Chapter 4-67
CSE 4701
Homework 3 from Spr 2015
Problem 4.10 in 6th edition
Chapter 4-68
CSE 4701
Problem 4.10 in 6th edition
Chapter 4-69
CSE 4701
Problem 4.10 in 6th edition
(a) Retrieve the names of employees in department 5 who work more than 10 hours per week on the 'ProductX' project.
SELECT LNAME, FNAMEFROM EMPLOYEE, WORKS_ON, PROJECTWHERE DNO=5 AND SSN=ESSN AND PNO=PNUMBER AND PNAME='ProductX' AND HOURS>10
LNAME FNAMESmith JohnEnglish Joyce
(b) List the names of employees who have a dependent with the same first name as themselves.
SELECT LNAME, FNAMEFROM EMPLOYEE, DEPENDENTWHERE SSN=ESSN AND FNAME=DEPENDENT_NAME
Result (empty):
Chapter 4-70
CSE 4701
Problem 4.10 in 6th edition
(c) Find the names of employees that are directly supervised by 'Franklin Wong'.
SELECT E.LNAME, E.FNAMEFROM EMPLOYEE E, EMPLOYEE SWHERE S.FNAME='Franklin' AND
S.LNAME='Wong' AND E.SUPERSSN=S.SSN
LNAME FNAMESmith JohnNarayan RameshEnglish Joyce
(h) Retrieve the average salary of all female employees.
SELECT AVG (SALARY)FROM EMPLOYEEWHERE SEX='F’
Result:AVG(SALARY)31000
Chapter 4-71
CSE 4701
INSERT SQL Queries
Add one or more Tuples to a Relation, with Attribute values Listed in the order specified in the CREATE
Update 1: INSERT INTO EMPLOYEE
VALUES ('Richard','K','Marini', '653298653', '30-DEC-52', '98 Oak Forest,Katy,TX', 'M',
37000,'987654321', 4 ) Another Form of Update 1:
INSERT INTO EMPLOYEE (FNAME, LNAME, SSN)VALUES ('Richard','K','Marini')
All PK and FK Values must be Provided Nulls are Allowed DDL Constraints are Enforced
Chapter 4-72
CSE 4701
INSERT SQL Queries
More Sophisticated Insert can Involve Query Update 3A:
CREATE TABLE DEPTS_INFO(DEPT_NAME VARCHAR(10),
NO_OF_EMPS INTEGER, TOTAL_SAL INTEGER);
Update 3B: INSERT INTO DEPTS_INFO (DEPT_NAME,
NO_OF_EMPS, TOTAL_SAL)
SELECT DNAME, COUNT (*), SUM (SALARY) FROM DEPARTMENT, EMPLOYEEWHERE DNUMBER=DNOGROUP BY DNAME ;
Chapter 4-73
CSE 4701
Program Level INSERTS
Mass Import into DB Consider Chinook_MySql.sql
Chapter 4-74
CSE 4701
Program Level INSERTS
Importing Excel Directly into MySQL Many Available Tools http://excel2mysql.net/
Importing an XML File directly into MySQL LOAD XML LOCAL INFILE '/pathtofile/file.xml'
INTO TABLE my_tablename SET ID=NULL; Tools such as: http://www.navicat.com/
Likewise – Ability to EXPORT as well SQL Data Export and Import Wizard For MySQL See: https://dev.mysql.com/doc/workbench/en/wb-admin-
export-import-management.html
Chapter 4-75
CSE 4701
DELETE SQL Queries
Sample Deletes IncludeDELETE FROM EMPLOYEEWHERE LNAME='Brown'
DELETE FROM EMPLOYEEWHERE SSN='123456789’
DELETE FROM EMPLOYEEWHERE DNO IN
(SELECT DNUMBER FROM DEPARTMENT
WHERE DNAME='Research')
DELETE FROM EMPLOYEE No. of Tuples Deleted Dependent on WHERE Clause Referential Integrity is Enforced During DELETE
Chapter 4-76
CSE 4701
UPDATE SQL Queries
Used to Modify Attribute Values of One or More Selected Tuples
A Where-clause Selects the Tuples to Be Modified An Additional Set-Clause Specifies the Attributes to Be
Modified and Their New Values Each Command Modifies Tuples in the Same Relation Referential Integrity Must Be Enforced
UPDATE PROJECT SET PLOCATION = 'Bellaire', DNUM = 5
WHERE PNUMBER=10
Chapter 4-77
CSE 4701
UPDATE SQL Queries
Give all Employees in the 'Research' Dept. a 10% raise UPDATE EMPLOYEE
SET SALARY = SALARY *1.1WHERE DNO IN
(SELECT DNUMBER FROM DEPARTMENT WHERE DNAME='Research')
Modified SALARY Value Depends on the Original SALARY Value in each Tuple
SALARY = SALARY *1.1 - Use PL Interpretation
Chapter 4-78
CSE 4701
Concluding Remarks What have we Seen in Chapter 4?
Complete Data Definition in SQLCreating SchemaCreating/Dropping TablesFKs and PKsBasic Data Manipulation in SQLDifferent SelectsAggregate FunctionsInsert, Update, and Delete
Strongly Encouraged to Engage in Practice with your DBMS of Choice for your Project