CS370 Chapter8
CS370 Chapter8
Chapter 8
SQL-99
Schema Definition, Constraints, Queries,
and Views
Chapter Outline
2
Database Design
Create
Real-world Conceptual DBMS data Load data
Schema
domain model model (DML)
(DDL)
3
Introduction
4
DDL Statements
The main SQL data definition language statements are: Used to CREATE,
6
SQL Data Definition and Data Type:
The CREATE TABLE command in SQL
7
CREATE TABLE (contd.)
In CREATE TABLE command, we specifying the primary key attributes,
secondary keys, and referential integrity constraints (foreign keys).
Key attributes can be specified via the PRIMARY KEY and UNIQUE
phrases
CREATE TABLE DEPARTMENT (
Dname VARCHAR(10) NOT NULL,
Dnumber INTEGER NOT NULL,
Mgr_ssn CHAR(9),
Mgr_start_date CHAR(9),
PRIMARY KEY (Dnumber),
UNIQUE (Dname),
FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE (Ssn));
8
Identifiers Names
9
SQL Data Definition and Data Type:
Attribute data types and domains in SQL
10
SQL Data Definition and Data Type:
Attribute data types and domains in SQL (contd.)
11
SQL Data Definition and Data Type:
Attribute data types and domains in SQL (contd.)
12
SQL Data Definition and Data Type:
Attribute data types and domains in SQL (contd.)
13
“COMPANY” Relational Database Schema
14
SQL Create Table
data definition
statements for
defining the
COMPANY Schema
15
SQL Create Table
data definition
statements for
defining the
COMPANY Schema
16
Specifying Constraints in SQL:
Specifying attribute constraints and attribute defaults
20
REFERENTIAL INTEGRITY OPTIONS (contd.)
21
Specifying Constraints in SQL:
22
23
Schema Change Statements in SQL
The DROP command
The DROP command can be used to drop the whole schema or drop
table and its definition.
Two drop behavior options:
CASCADE, drops all objects associated with schema
RESTRICT, schema must be empty
DROP SCHEMA COMPANY CASCADE;
If drop table; The relation can no longer be used in queries, updates, or
any other commands since its description no longer exists
DROP TABLE DEPENDENT CASCADE;
The RESTRICT option is chosen the table dropped only if it is not
referenced in any constraints.
The DROP command can also used to drop domains or constraints.
24
Schema Change Statements in SQL
The ALTER command
For base table, the possible alter table action include adding or
dropping a column, changing column definition, and adding or
dropping table constraints.
25
Schema Change Statements in SQL
The ALTER command (contd.)
26
Schema Change Statements in SQL
The ALTER command (contd.)
Create
Real-world Conceptual DBMS data Load data
Schema
domain model model (DML)
(DDL)
28
29
Basic Queries in SQL
30
Retrieval Queries in SQL (contd.)
32
Simple SQL Queries (contd.)
Aliasing:
In SQL, we can use the same name for two (or more) attributes as
long as the attributes are in different relations
A query that refers to two or more attributes with the same name
must qualify the attribute name with the relation name by prefixing the
relation name to the attribute name
Example:
EMPLOYEE.Lname, DEPARTMENT.Dname
35
ALIASES (contd.)
Query 8: For each employee, retrieve the employee's name, and the
name of his or her immediate supervisor.
In Q8, the alternate relation names E and S are called aliases or tuple
variables for the EMPLOYEE relation
We can think of E and S as two different copies of EMPLOYEE; E
represents employees in role of supervisees and S represents
employees in role of supervisors
36
ALIASES (contd.)
37
UNSPECIFIED WHERE-clause
38
JOIN vs. CARTESIAN PRODUCT
Examples:
Q1C: SELECT *
FROM EMPLOYEE
WHERE Dno=5;
Q1D: SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE Dname='Research' AND
Dno=Dnumber;
40
USE OF DISTINCT
SQL does not treat a relation as a set; duplicate tuples can appear
To eliminate duplicate tuples in a query result, the keyword DISTINCT is
used
For example, the result of Q11 may have duplicate SALARY values
whereas Q11A does not have any duplicate values
41
SET OPERATIONS
The set operations apply only to union compatible relations; the two
relations must have the same attributes and the attributes must appear
42
SET OPERATIONS (contd.)
Query 4: Make a list of all project numbers for projects that involve an employee
whose last name is 'Smith' as a worker or as a manager of the department that
controls the project.
UNION
(SELECT Pnumber
FROM WORKS_ON, EMPLOYEE
WHERE Essn=Ssn AND Lname='Smith');
43
SUBSTRING COMPARISON
Example:
Query 25: Retrieve all employees whose address is in Houston, Texas.
Here, the value of the ADDRESS attribute must contain the substring
'Houston,TX‘ in it.
Q25: SELECT Fname, Lname
FROM EMPLOYEE
WHERE Address LIKE '%Houston,TX%‘;
44
SUBSTRING COMPARISON (contd.)
Query 26: Retrieve all employees who were born during the 1950s.
Here, '5' must be the third character of the string (according to our format
for date), so the BDATE value is ‘_ _ 5_ _ _ _ _ _ _ ', with each underscore
as a place holder for a single arbitrary character.
45
ARITHMETIC OPERATIONS
The standard arithmetic operators '+', '-'. '*', and '/' (for addition,
subtraction, multiplication, and division, respectively) can be applied to
numeric values in an SQL query result
Query 27: Show the effect of giving all employees who work on the
'ProductX' project a 10% raise.
46
ARITHMETIC OPERATIONS
Q27: SELECT *
FROM EMPLOYEE
WHERE (Salary BETWEEN 30,000 AND 40,000)
AND Dno=5;
47
Ordering of Query Results
The ORDER BY clause is used to sort the tuples in a query result based
on the values of some attribute.
Query 28: Retrieve a list of employees and the projects each works in,
ordered by the employee's department, and within each department ordered
alphabetically by employee last name, first name.
Q28: SELECT Dname, Lname, Fname, Pname
FROM DEPARTMENT,EMPLOYEE,WORKS_ON,PROJECT
WHERE Dnumber=Dno AND Ssn=Essn AND
Pno=Pnumber
ORDER BY Dname, Lname, Fname;
The default order is in ascending order of values. We can specify the
keyword DESC if we want a descending order; the keyword ASC can be
used to explicitly specify ascending order, even though it is the default
ORDER BY Dname DESC, Lname ASC, Fname ASC;
48
Database Design
Create
Real-world Conceptual DBMS data Load data
Schema
domain model model (DML)
(DDL)
49
50
NULLS in SQL Queries
Query 14: Retrieve the names of all employees who do not have
supervisors.
Q14: SELECT Fname, Lname
FROM EMPLOYEE
WHERE Super_ssn IS NULL;
51
EXPLICIT SETS
Query 13: Retrieve the social security numbers of all employees who
work on project number 1, 2, or 3.
52
AGGREGATE FUNCTIONS
Functions that operate on a single column of a table and return a single value.
Five aggregation functions defined in SQL:
COUNT returns the number of rows in a specified column
SUM returns the sum of the values in a specified column
AVG returns the average of the values in a specified column
MIN returns the smallest value in a specified column
MAX returns the largest value in a specified column
Query 15: Find the maximum salary, the minimum salary, and the
average salary among all employees.
53
AGGREGATE FUNCTIONS (contd.)
Query 16: Find the maximum salary, the minimum salary, and the
average salary among employees who work for the 'Research'
department.
54
AGGREGATE FUNCTIONS (contd.)
55
GROUPING
56
GROUPING (contd.)
Query 20:
For each department, retrieve the department number, the number of
employees in the department, and their average salary.
Query 21:
For each project, retrieve the project number, project name, and
the number of employees who work on that project.
In this case, the grouping and functions are applied after the
joining of the two relations
58
THE HAVING- CLAUSE
59
THE HAVING-CLAUSE (contd.)
Query 22:
For each project on which more than two employees work,
retrieve the project number, project name, and the number of
employees who work on that project.
Q22: SELECT Pnumber, Pname, COUNT(*)
FROM PROJECT, WORKS_ON
WHERE Pnumber=Pno
GROUP BY Pnumber, Pname
HAVING COUNT (*) > 2;
60
NESTING OF QUERIES
62
CORRELATED NESTED QUERIES
If a condition in the WHERE-clause of a nested query references
an attribute of a relation declared in the outer query, the two
queries are said to be correlated
The result of a correlated nested query is different for each tuple (or
combination of tuples) of the relation(s) the outer query
Query 12: Retrieve the name of each employee who has a dependent
with the same first name as the employee.
Q12: SELECT E.Fname, E.Lname
FROM EMPLOYEE AS E
WHERE E.Ssn IN
(SELECT Essn
FROM DEPENDENT
WHERE Essn=E.Ssn AND
E.Fname=Dependent_name);
63
CORRELATED NESTED QUERIES (contd.)
In Q12, the nested query has a different result in the outer query
A query written with nested SELECT... FROM... WHERE...
blocks and using the = or IN comparison operators can always
be expressed as a single block query. For example, Q12 may be
written as in Q12A
Fname=Dependent_name); 65
THE EXISTS FUNCTION (contd.)
Query 6:
Retrieve the names of employees who have no dependents.
Q6: SELECT Fname, Lname
FROM EMPLOYEE
WHERE NOT EXISTS (SELECT *
FROM DEPENDENT
WHERE Ssn=Essn);
67
Different types of JOIN
68
Joined Relations Feature in SQL2 (contd.)
Examples:
Q1: SELECT Fname, Lname, Address
FROM EMPLOYEE, DEPARTMENT
WHERE Dname='Research' AND Dnumber=DNO;
Could be written as:
Q1: SELECT Fname, Lname, Address
FROM (EMPLOYEE JOIN DEPARTMENT ON
Dnumber=Dno)
WHERE Dname='Research’;
OR as:
Q1: SELECT FNAME, LNAME, ADDRESS
FROM (EMPLOYEE NATURAL JOIN
(DEPARTMENT
AS DEPT(Dname, Dno, Mssn, Msdate)))
WHERE Dname='Research’; 69
Joined Relations Feature in Relational Algebra
Left outer join:
List all employee names as well as the name of the departments
they mange if they happen to mange a department if they do not
mange one, we can indicate it with a NULL value.
70
Joined Relations Feature in SQL2 (contd.)
Example: Left outer join:
Q8B:
SELECT Fname AS Employee_name,
Fname AS Supervisor_name
FROM (EMPLOYEE AS E LEFT OUTER JOIN
EMPLOYEE AS S ON
E.Super_ssn = S.Ssn);
71
Joined Relations Feature in SQL2 (contd.)
72
Summary of SQL Queries
73
SELECT[DISTINCT|ALL]{*|column|column_expression[AS new_name][,
…]}
FROM table_name [alias] [, … ]
[WHERE condition]
[GROUP BY column_list]
[HAVING condition]
[ORDER BY column_list [ASC|DESC]]
SELECT specifies which column are to appear in the output
Asterisk (*) means all columns.
column represents a column name
column_expression represents an expression on a column
Order of the clauses in the SELECT statement can not be changed
FROM specifies the table(s) to be used
table_name is the name of an existing database table or view
WHERE filters the rows subject to some condition
GROUP BY forms groups of rows with the same column name
ORDER BY specifies the order of the output
The result of a query is another table 74
Specifying Updates in SQL
INSERT:
In its simplest form, it is used to add one or more tuples to a
relation
Attribute values should be listed in the same order as the
attributes were specified in the CREATE TABLE command
75
INSERT (contd.)
Example:
U1: INSERT INTO EMPLOYEE
VALUES ('Richard','K','Marini', '653298653', '30-
DEC-52','98 Oak Forest,Katy,TX', 'M',
37000,'987654321', 4);
An alternate form of INSERT specifies explicitly the attribute names
that correspond to the values in the new tuple
Attributes with NULL values can be left out.
Example:
Insert a tuple for a new EMPLOYEE for whom we only know the
FNAME, LNAME, and SSN attributes.
U1A: INSERT INTO EMPLOYEE (Fname, Lname, Ssn)
VALUES ('Richard', 'Marini', '653298653');
76
INSERT (contd.)
Example:
77
INSERT (contd.)
78
DELETE
80
UPDATE
81
UPDATE (contd.)
82
UPDATE (contd.)
84
Specification of Views in SQL
85
Specification of Views in SQL (contd.)
WORKS_ON1
Fname Lname Pname Hours
87
Specification of Views in SQL (contd.)
DEPT_INFO
Dept_name No_of_emps Total_sal
88
Specification of Views in SQL (contd.)
Now we can specify SQL queries on view in the same way
we do with base tables.
To retrive the last name and first name of all employees who
work on ‘ProjectX’.
SELECT Fname, Lname
FROM WORKS_ON1
WHERE Pname=‘ProjectX’;
89