0% found this document useful (0 votes)
14 views

CS370 Chapter8

This document provides an outline of Chapter 8 from a textbook on SQL and databases. It covers SQL data definition and data types, specifying constraints in SQL like primary keys and foreign keys, and schema change statements. It also provides examples of creating tables and defining schemas for a sample "COMPANY" database.

Uploaded by

Heba Rainbow
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

CS370 Chapter8

This document provides an outline of Chapter 8 from a textbook on SQL and databases. It covers SQL data definition and data types, specifying constraints in SQL like primary keys and foreign keys, and schema change statements. It also provides examples of creating tables and defining schemas for a sample "COMPANY" database.

Uploaded by

Heba Rainbow
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 89

Al-Imam Mohammad Ibn Saud Islamic University

College of Computer and Information Sciences


Computer Science Department
CS370: Introduction to databases

Chapter 8
SQL-99
Schema Definition, Constraints, Queries,
and Views
Chapter Outline

 SQL Data Definition and Data Type


 Schema and catalog concepts in SQL
 The CREATE TABLE command in SQL
 Attribute data types and domains in SQL
 Specifying Constraints in SQL
 Specifying attribute constraints and attribute defaults
 Specifying key and referential integrity constraints
 Giving names to constraints
 Specifying constraints on tuples using CHECK
 Schema Change Statements in SQL
 The DROP command
 The ALTER command

2
Database Design

Steps in building a database for an application:

Create
Real-world Conceptual DBMS data Load data
Schema
domain model model (DML)
(DDL)

3
Introduction

 SQL (Structured Query Language)


 SQL was called SEQUEL (Structured English QUEry Language)
was designed and implemented by IBM
 SQL is now the stander language for commercial relational DBMSs.
 SQL was standardized first by the ANSI and ISO. called SQL1 or
SQL-86
 Much expanded standard called SQL2 or SQL-92
 The next standard that is well-recognized is SQL-99 or SQL3

4
DDL Statements

The main SQL data definition language statements are: Used to CREATE,

DROP, and ALTER the descriptions of the tables (relations) of a database

CREATE SCHEMA DROP SCHEMA

CREATE DOMAIN ALTER DOMAIN DROP DOMAIN

CREATE TABLE ALTER TABLE DROP TABLE

CREATE VIEW DROP VIEW

CREATE INDEX DROP INDEX


5
SQL Data Definition and Data Type:
Schema and catalog concepts in SQL

 Specifies a new database schema by giving it a name.


 An SQL schema is identified by a schema name and includes an
authorization identifier to indicate the user or account who owns the
schema.
CREATE SCHEMA COMPANY AUTHORIZATION Jsmith;

6
SQL Data Definition and Data Type:
The CREATE TABLE command in SQL

 Specifies a new base relation by giving it a name, and specifying each


of its attributes and their data types (INTEGER, FLOAT, DECIMAL(i,j),
CHAR(n), VARCHAR(n))
 A constraint NOT NULL may be specified on an attribute

CREATE TABLE DEPARTMENT (


Dname VARCHAR(10) NOT NULL,
Dnumber INTEGER NOT NULL,
Mgr_ssn CHAR(9),
Mgr_start_date CHAR(9) );

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

• May contain A-Z, a-z, 0-9, _

• No longer than 128 characters

• Start with letter

• Cannot contain spaces

9
SQL Data Definition and Data Type:
Attribute data types and domains in SQL

Type SQL Data Type Used


Numeric Integer numbers of various
INTEGER or INT and SMALLINT sizes
Floating-point (real) numbers
FLOAT or REAL and DOUBLE of various precision
PRECISION

Formatted numbers, where i


NUMERIC (i, j) or DECIMAL (i, j) The precision and j the scale
Character- Fixed length, where n is the
string CHAR(n) or CHARACTER(n) number of characters

Varying length, where n is


VARCHAR(n) or CHAR VARYING(n) or the maximum number of
CHARACTER VARYING(n) characters

10
SQL Data Definition and Data Type:
Attribute data types and domains in SQL (contd.)

Type SQL Data Type Used


Bit-string Fixed length, where n is the
BIT(n) number of bits

Varying length, where n is


BIT VARYING (n) the maximum number of bits

Boolean There are three values


(TRUE,FALSE and
BOOLEAN UNKNOWN)

11
SQL Data Definition and Data Type:
Attribute data types and domains in SQL (contd.)

Type SQL Data Type Used


Date_Time Has ten positions. Made up of year-
DATE month-day in the format yyyy-mm-dd
Made up of hour:minute:second in the
TIME format hh:mm:ss
Made up of hour:minute:second plus i
TIME(i) additional digits specifying fractions of
a second. format is hh:mm:ss:i
Timestamp Has both DATE and TIME
TIMESTAMP components
Specifies a relative value rather than an
INTERVAL absolute value. Can be DAY/TIME
intervals or YEAR/MONTH intervals

12
SQL Data Definition and Data Type:
Attribute data types and domains in SQL (contd.)

It is possible to specify the data type of each attribute directly or


a domain can be declared and the domain name used with the
attribute specification.

CREATE DOMAIN SSN_TYPE AS CHAR(9);

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

Three types of attribute constraints:


1. Required data: a constraint NOT NULL may be specified if NULL is not permitted
for a particular attribute.
Dname VARCHAR(10) NOT NULL,
2. Defaults value: it is possible to define a default value for an attribute by
appending the DEFAULT <value> to an attribute definition.
Dno INT NOT NULL DEFAULT 1,
3. Domain values constraints: restrict attribute values using CHECK following an
attribute or domain definition.
Dnumber INT NOT NULL CHECK(Dnumber>0 AND Dnumber<12),
or at domain definition
CREATE DOMAIN D_num AS INTEGER CHECK(D_num>0 AND D_num<12);
17
Specifying Constraints in SQL:
Specifying key and referential integrity constraints
 PRIMARY KEY clause specifies one or more attributes that make up the
primary key of a relation. If the primary key has a single attribute, the
clause can follow the attribute directly.
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 );
or
Dnumber INTEGER PRIMARY KEY,

 UNIQUE clause: specifies alternate secondary keys as in DEPARTMENT


and PROJECT tables. 18
Specifying Constraints in SQL:
Specifying key and referential integrity constraints

Referential integrity is specified via the FOREIGN KEY clause.


FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE (Ssn)
 SQL rejects any insert, update or delete operation that attempts to create a
foreign key value without a matching PK value key.
 The schema designer can specify an alternative action by attaching a
referential triggered action on UPDATE or DELETE operation.
 Four options are supported when the user attempt to delete or update a
PK, and there are matching FKs:
 CASCADE: automatically delete/update the PK row & all matching (FKs) rows in
child table
 SET NULL: delete/update the PK row & set the FK values to NULL
 SET DEFAULT: delete/update the PK row & set the FK values to default. Valid
only if DEFAULT clause is specified.
 NO ACTION: rejects the delete operation 19
REFERENTIAL INTEGRITY OPTIONS (contd.)

 We can specify RESTRICT, CASCADE, SET NULL or SET DEFAULT


on referential integrity constraints (foreign keys)

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)
ON DELETE SET NULL ON UPDATE CASCADE);

20
REFERENTIAL INTEGRITY OPTIONS (contd.)

CREATE TABLE EMPLOYEE(


Ename VARCHAR(30) NOT NULL,
Essn CHAR(9),
Bdate DATE,
Dno INTEGER DEFAULT 1,
Superssn CHAR(9),
PRIMARY KEY (Essn),
FOREIGN KEY (Dno) REFERENCES DEPARTMENT(Dnumber)
ON DELETE SET DEFAULT ON UPDATE CASCADE,
FOREIGN KEY (SUPERSSN) REFERENCES EMPLOYEE(Ssn)
ON DELETE SET NULL ON UPDATE CASCADE);

21
Specifying Constraints in SQL:

Giving Names to constraints:


The constraints can be given a constraint name, following the keyword
CONSTRAINT. The name must be unique.

Specifying constraints on tuples using CHECK:


 Other table constraints can be specified through additional CHECK
clauses at the end of a CREATE TABLE statement.
 Called tuple-based constraints because they apply for each tuple
individually and are checked whenever a tuple is inserted or modified.
CHECK (Dept_create_date <= Mgr_start_date)

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

 The definition of a table or of other named schema element can


be changed by using 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.)

 Used to add an attribute to one of the base relations


 The new attribute will have NULLs in all the tuples of the relation right
after the command is executed; hence, the NOT NULL constraint is
not allowed for such an attribute
Example:
ALTER TABLE EMPLOYEE ADD JOB VARCHAR(12);
 The database users must still enter a value for the new attribute JOB
for each EMPLOYEE tuple.
 Specifying a DEFULT clause
 This can be done using the UPDATE command.

26
Schema Change Statements in SQL
The ALTER command (contd.)

 To alter a column definition by dropping an existing default clause or by


defining a new default clause.
ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN
Mgr_ssn DROP DEFAULT;
ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN
Mgr_ssn SET DEFAULT ‘333445555’;
 To drop the Address column from EMPLOYEE
ALTER TABLE COMPANY.EMPLOYEE DROP COLUMN Address CASCADE;

 To drop the constraint named EMPSUPERFK from EMPLOYEE


ALTER TABLE COMPANY.EMPLOYEE
DROP CONSTRAINT EMPSUPERFK CASCADE;
27
Database Design

Steps in building a database for an application:

Create
Real-world Conceptual DBMS data Load data
Schema
domain model model (DML)
(DDL)

28
29
Basic Queries in SQL

Retrieval Queries in SQL


 SQL has one basic statement for retrieving information from a database;
the SELECT statemen

30
Retrieval Queries in SQL (contd.)

Basic form of the SQL SELECT statement is called a mapping or a


SELECT-FROM-WHERE block

SELECT <attribute list>


FROM <table list>
WHERE <condition> ;

 <attribute list> is a list of attribute names whose values are to be


retrieved by the query
 <table list> is a list of the relation names required to process the query
 <condition> is a conditional (Boolean) expression that identifies the
tuples to be retrieved by the query. Comparison expression use the
following operators (= , <, >, <=, >=, <>)
31
Simple SQL Queries (contd.)
SELECT <attribute list>
FROM <table list>
WHERE <condition> ;

Example of a simple query on one relation:


Query 0: Retrieve the birthdate and address
of the employee whose name is 'John B. Smith'.

Q0: SELECT Bdate, Address


FROM EMPLOYEE
WHERE Fname='John' AND Minit='B’ AND Lname='Smith’;

Note: The result of the query may contain duplicate tuples

32
Simple SQL Queries (contd.)

Query 1: Retrieve the name and address


of all employees
who work for the 'Research' department.

Q1:SELECT Fname, Lname, Address


FROM EMPLOYEE, DEPARTMENT
WHERE Dname='Research' AND Dnumber=Dno;

 (Dname='Research') is a selection condition


 (Dnumber=Dno) is a join condition
33
Simple SQL Queries (contd.)

Query 2: For every project located in 'Stafford', list the


project number, the controlling department number, and the
department manager's last name, address, and birthdate.

Q2: SELECT Pnumber, Dnum, Lname, Bdate, Address


FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum=Dnumber AND Mgr_ssn=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 Mgr_ssn=Ssn relates the controlling
department to the employee who manages that department
34
Ambiguous Attribute Names, Aliasing, and
Tuple Variables

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

 Some queries need to refer to the same relation twice


 In this case, aliases are given to the relation name

Query 8: For each employee, retrieve the employee's name, and the
name of his or her immediate supervisor.

Q8: SELECT E.Fname, E.Lname, S.Fname, S.Lname


FROM EMPLOYEE E S
WHERE E.Super_ssn=S.Ssn ;

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

 Aliasing can also be used in any SQL query for convenience


 Can also use the AS keyword to specify aliases

Q8: SELECT E.Fname, E.Lname,


S.Fname, S.Lname
FROM EMPLOYEE AS E,
EMPLOYEE AS S
WHERE E.Super_ssn=S.Ssn;

37
UNSPECIFIED WHERE-clause

 A missing WHERE-clause indicates no condition; hence, all tuples of the


relations in the FROM-clause are selected
 This is equivalent to the condition WHERE TRUE
Query 9: Retrieve the SSN values for all employees.
Q9: SELECT Ssn
FROM EMPLOYEE;
 If more than one relation is specified in the FROM-clause and there is no
join condition, then the CARTESIAN PRODUCT of tuples is selected
Q10: SELECT Ssn, Dname
FROM EMPLOYEE, DEPARTMENT;

38
JOIN vs. CARTESIAN PRODUCT

R S Cartesian Product Join


A B B C A B B C A B B C
a 1 1 x a 1 1 x a 1 1 x
b 2 1 y a 1 1 y a 1 1 y
3 z a 1 3 z
b 2 1 x Join condition is
b 2 1 y R.B = S.B
b 2 3 z

Both operations is used to combine tuples from two relations in a


combinatorial fashion.
In CROSS PRODUCT the resulting relation state has one tuple for each
combination of tuples one from R and one from S.
The JOIN operation is very important for any relational database, because it
allows us combine related tuples from various relations
Generally, CROSS PRODUCT is not a meaningful operation
39
USE OF ASTERISK *

 To retrieve all the attribute values of the selected tuples, a * is


used, which stands for all the attributes

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

Q11: SELECT ALL Salary


FROM EMPLOYEE;

Q11A: SELECT DISTINCT Salary


FROM EMPLOYEE;

41
SET OPERATIONS

 SQL has directly incorporated some set operations

 There is a union operation (UNION), and in some versions of SQL there

are set difference (MINUS) and intersection (INTERSECT) operations

 The resulting relations of these set operations are sets of tuples;

duplicate tuples are eliminated from the result

 The set operations apply only to union compatible relations; the two

relations must have the same attributes and the attributes must appear

in the same order

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.

Q4: (SELECT Pnumber


FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum=Dnumber AND Mgr_ssn=Ssn
AND Lname='Smith’)

UNION
(SELECT Pnumber
FROM WORKS_ON, EMPLOYEE
WHERE Essn=Ssn AND Lname='Smith');

43
SUBSTRING COMPARISON

 The LIKE comparison operator is used to compare partial strings


 Two reserved characters are used: '%' replaces an arbitrary number of
characters, and '_' replaces a single arbitrary character

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.

Q26: SELECT Fname, Lname


FROM EMPLOYEE
WHERE Bdate LIKE ‘_ _ 5_ _ _ _ _ _ _ ‘;

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.

Q27: SELECT Fname, Lname, 1.1*Salary AS Increased_sal


FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE Ssn=Essn AND Pno=Pnumber AND
Pname='ProductX’;

46
ARITHMETIC OPERATIONS

 Another comparison operator that can be used is BETWEEN


 The BETWEEN operator is inclusive: begin and end values are
included.

 Query 14: Retrieve all employee in department 5 whose salary is


between $30,000 and $40,000

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

Steps in building a database for an application:

Create
Real-world Conceptual DBMS data Load data
Schema
domain model model (DML)
(DDL)

49
50
NULLS in SQL Queries

 SQL allows queries that check if a value is NULL (missing or


undefined or not applicable)
 SQL uses IS or IS NOT to compare NULLs, so equality
comparison is not appropriate.

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

 It is also possible to use an explicit (enumerated) set of values in


the WHERE-clause rather than a nested query

Query 13: Retrieve the social security numbers of all employees who
work on project number 1, 2, or 3.

Q13: SELECT DISTINCT ESSN


FROM WORKS_ON
WHERE PNO IN (1, 2, 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.

Q15: SELECT MAX(Salary), MIN(Salary), AVG(Salary)


FROM EMPLOYEE;

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.

Q16: SELECT MAX(Salary), MIN(Salary), AVG(Salary)


FROM EMPLOYEE, DEPARTMENT
WHERE Dno=Dnumber AND Dname='Research‘;

54
AGGREGATE FUNCTIONS (contd.)

Queries 17 and 18:


Retrieve the total number of employees in the company (Q17), and
the number of employees in the 'Research' department (Q18).

Q17: SELECT COUNT (*)


FROM EMPLOYEE;

Q18: SELECT COUNT (*)


FROM EMPLOYEE, DEPARTMENT
WHERE Dno=Dnumber AND
Dname='Research’;

55
GROUPING

 In many cases, we want to apply the aggregate functions to

subgroups of tuples in a relation

 Each subgroup of tuples consists of the set of tuples that have

the same value for the grouping attribute(s)

 The function is applied to each subgroup independently

 SQL has a GROUP BY-clause for specifying the grouping

attributes, which must also appear in the SELECT-clause

56
GROUPING (contd.)

Query 20:
For each department, retrieve the department number, the number of
employees in the department, and their average salary.

Q20: SELECT Dno, COUNT (*), AVG (Salary)


FROM EMPLOYEE
GROUP BY Dno;
 In Q20, the EMPLOYEE tuples are divided into groups
- Each group having the same value for the grouping attribute DNO
 The COUNT and AVG functions are applied to each such group of tuples
separately
 The SELECT-clause includes only the grouping attribute and the
functions to be applied on each group of tuples
57
GROUPING (contd.)

Query 21:
For each project, retrieve the project number, project name, and
the number of employees who work on that project.

Q21: SELECT Pnumber, Pname, COUNT (*)


FROM PROJECT, WORKS_ON
WHERE Pnumber=Pno
GROUP BY Pnumber, Pname;

In this case, the grouping and functions are applied after the
joining of the two relations

58
THE HAVING- CLAUSE

 Sometimes we want to retrieve the values of these functions


for only those groups that satisfy certain conditions

 The HAVING-clause is used for specifying a selection


condition on groups (rather than on individual tuples)

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

 A complete SELECT query, called a nested query, can be


specified within the WHERE-clause of another query, called the
outer query
 Many of the previous queries can be specified in an alternative
form using nesting
 Query 1: Retrieve the name and address of all employees who
work for the 'Research' department.

Q1: SELECT Fname, Lname, Address


FROM EMPLOYEE
WHERE Dno IN ( SELECT Dnumber
FROM DEPARTMENT
WHERE
Dname='Research' ); 61
NESTING OF QUERIES (contd.)

 The nested query selects the number of the 'Research'


department
 The outer query select an EMPLOYEE tuple if its Dno value is in
the result of either nested query
 The comparison operator IN compares a value v with a set (or
multi-set) of values V, and evaluates to TRUE if v is one of the
elements in V
 In general, we can have several levels of nested 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

Q12A: SELECT E.Fname, E.Lname


FROM EMPLOYEE AS E, DEPENDENT
AS D
WHERE E.Ssn = D.Essn AND
E.Fname =
D.dependent_name ;
64
THE EXISTS FUNCTION

 EXISTS is used to check whether the result of a correlated nested


query is empty (contains no tuples) or not.
Query 12:
Retrieve the name of each employee who has a dependent with the
same first name as the employee.
Q12B: SELECT Fname, Lname
FROM EMPLOYEE
WHERE EXISTS (SELECT *
FROM DEPENDENT
WHERE Ssn=Essn AND

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

In Q6, the correlated nested query retrieves all DEPENDENT tuples


related to an EMPLOYEE tuple. If none exist, the EMPLOYEE tuple
is selected.
66
Joined Relations Feature in SQL2

 Can specify a "joined relation" in the FROM-clause


 Looks like any other relation but is the result of a join
 Allows the user to specify different types of joins (regular
"theta" JOIN, NATURAL JOIN)

67
Different types of JOIN

T U Cartesian Product Theta Join


AB B C A B B C A B B C
a 1 1 x a 1 1 x a 1 1 x
1 y a 1 1 y a 1 1 y
b 2
a 1 3 z
3 z
b 2 1 x
b 2 1 y
b 2 3 z

EquiJoin Natural Join


A B B C A B C
a 1 1 x a 1 x
a 1 1 y a 1 y

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

Another Example: Q2 could be written as follows; this illustrates


multiple joins in the joined tables
Q2: SELECT Pnumber, Dnum, Lname, Bdate,
Address
FROM (PROJECT JOIN DEPARTMENT ON
Dnum=Dnumber) JOIN
EMPLOYEE ON Mgr_ssn=Ssn) )
WHERE Plocation='Stafford’ ;

72
Summary of SQL Queries

 A query in SQL can consist of up to six clauses, but only the


first two, SELECT and FROM, are mandatory. The clauses are
specified in the following order:

SELECT <attribute list>


FROM <table list>
[WHERE <condition>]
[GROUP BY <grouping attribute(s)>]
[HAVING <group condition>]
[ORDER BY <attribute list>]

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

 There are three SQL commands to modify the database (DML):


INSERT, DELETE, and UPDATE

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

 Important Note: Only the constraints specified in the DDL commands


are automatically enforced by the DBMS when updates are applied to
the database

Example:

U2: INSERT INTO EMPLOYEE (Fname, Lname, Ssn, Dno)

VALUES ('Richard', 'Marini', '653298653‘, 2 );

U2 is rejected if referential integrity checking is provided by DBMS

77
INSERT (contd.)

U3A: CREATE TABLE DEPTS_INFO


( Dept_name VARCHAR(10) NOT NULL,
No_of_emps INTEGER NOT NULL,
Total_sal INTEGER );

U3B: INSERT INTO DEPTS_INFO (Dept_name, No_of_emps,Total_sal)


SELECT Dname, COUNT(*), SUM (Salary)
FROM (DEPARTMENT JOIN EMPLOYEE ON Dnumber=Dno)
GROUP BY Dname;

78
DELETE

Removes tuples from a relation


 Includes a WHERE-clause to select the tuples to be deleted
 Referential integrity should be enforced
 Tuples are deleted from only one table at a time (unless
CASCADE is specified on a referential integrity constraint)
 A missing WHERE-clause specifies that all tuples in the relation
are to be deleted; the table then becomes an empty table
 The number of tuples deleted depends on the number of tuples
in the relation that satisfy the WHERE-clause
79
DELETE (contd.)
 Examples:

U4A: DELETE FROM EMPLOYEE


WHERE Lname='Brown’;

U4B: DELETE FROM EMPLOYEE


WHERE Ssn='123456789’;

U4C: DELETE FROM EMPLOYEE


WHERE Dno IN
(SELECT Dnumber
FROM DEPARTMENT
WHERE Dname='Research')

U4D: DELETE FROM EMPLOYEE;

80
UPDATE

 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 should be enforced

81
UPDATE (contd.)

Example: Change the location and controlling department


number of project number 10 to 'Bellaire' and 5, respectively.

U5: UPDATE PROJECT


SET Plocation = 'Bellaire', Dnum
=5
WHERE Pnumber=10;

82
UPDATE (contd.)

Example: Give all employees in the 'Research' department a 10%


raise in salary.
U6: UPDATE EMPLOYEE
SET Salary = Salary *1.1
WHERE Dno IN (SELECT Dnumber
FROM DEPARTMENT
WHERE Dname='Research');

In this request, the modified SALARY value depends on the original


SALARY value in each tuple
 The reference to the SALARY attribute on the right of = refers to
the old SALARY value before modification
 The reference to the SALARY attribute on the left of = refers to the
new SALARY value after modification
83
Concepts of a View in SQL
 View in SQL terminology is a single table that is derived from other
tables.
 These other tables could be base tables or previously defined views.
 in SQL it is possible to define alternative views of the same data
 A view is a virtual relation (like a window) through which it is
possible to access the data stored in the real relations (called base
relations)
 Unlike base tables, a view does not physically store tuples, but it
can be used almost like a base relation
 A view is defined by a query on one or more base relations and/or
other views
 A view is materialized by executing the query that defines it

84
Specification of Views in SQL

 The command to specify a view is CREATE VIEW.


 The view is:
 given a virtual table name (or view name).
 List of attribute names.
 A query to specify the contents of the view.
 If we did not specify the view attributes names next to the view
name, they will have the same attributes names as in base
tables.

85
Specification of Views in SQL (contd.)

Example: create a view returning a subset of the set of tuples of


the Employees relation; the view must include the columns SSN,
frist name and salary for the employees of department #10?

CREATE VIEW Emp10


AS SELECT Ssn, Fname, Salary
FROM EMPLOYEE
WHERE Dno=10;

 The names of the columns of view Emp10 are: SSN, Fname


and Salary “same as Employee table”
86
Specification of Views in SQL (contd.)

V2: CREATE VIEW WORKS_ON1


AS SELECT Fname, Lname,Pname, Hours
FROM EMPLOYEE, PROJECT,WORKS_ON
WHERE Ssn=Essn AND Pno=Pnumber;

WORKS_ON1
Fname Lname Pname Hours

87
Specification of Views in SQL (contd.)

V3: CREATE VIEW DEPT_INFO (Dept_name,No_of_emps,Total_sal)


AS SELECT Dname, COUNT(*), SUM (Salary)
FROM DEPARTMENT, EMPLOYEE
WHERE Dnumber= Dno
GROUP BY Dname;

DEPT_INFO
Dept_name No_of_emps Total_sal

Here we specify new attrbuites names for the view DEPT_INFO

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’;

 A view is up to date, if you modify a tuple in the base tables on


which the view is defined, the view must automatically reflect
these changes.
 If you donot need a view any more, you can drop it by using:
DROP VIEW WORKS_ON1;

89

You might also like