0% found this document useful (0 votes)
15 views564 pages

DB DR - Jehad Slides

Uploaded by

engzoul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views564 pages

DB DR - Jehad Slides

Uploaded by

engzoul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 564

CHAPTER 1 - Introduction

Chapter 1 – Slide 1
BASIC DEFINITIONS

▪ Data –
• facts that are recorded and can be accessed
• facts that can be recorded and have an implicit meaning.
• Data formats – text, numbers, figures, graphics, images,
audio/video recordings and more.
• Data is recorded and kept because it is considered to be of use to
an intended user.

▪ Information - refers to the data that is accessed by a user


for some particular purpose
• Typically, getting the needed information from a collection of
data requires performing an activity, such as searching through,
processing, or manipulating the data in some form or fashion.

Chapter 1 – Slide 2
BASIC DEFINITIONS
▪ Database - structured collection of related data stored on a
computer medium
• Organizes the data in a way that facilitates efficient access to the
information captured in the data

▪ Database management system (DBMS) - software used for:


• Creation of databases
• Insertion, storage, retrieval, update, and deletion of the data in the
database
• Maintenance of databases

▪ Database system - computer-based system whose purpose is


to enable an efficient interaction between the users and the
information captured in a database
• The DBMS software together with the data itself.
• Sometimes, the applications are also included.

Chapter 1 – Slide 3
Operations with Databases
• Design
– Define structure and types of data
• Construction
– Create data structures of DB, populate DB with data
• Manipulation of Data
– Insert, delete, update
– Query: “Which department pays the highest salary?”
– Create reports:
“List monthly salaries of employees, organised
by department, with average salary and total
sum of salaries for each dept”

4
Databases Are Everywhere
• Database = a large (?) collection of related data
• Classically, a DB models a real-world organisation
(e.g., enterprise, university)
– Entities (e.g., students, courses)
– Relationships (e.g., “Martin is taking IDS in 2009/10”)
• Changes in the organisation = changes in the database
• Examples:
– personnel records
– banking
– airline reservations

5
Scientific Databases (Examples)

• Biology:
▪ e.g., DNA sequences of genes, amino-acid sequences
of proteins, genes expressed in tissues
▪ (up to several Gigabytes)
• Astronomy:
▪ e.g., location and spectra of astronomic objects
▪ (up to several Terabytes)
• Physics:
▪ e.g., sensor measurements in particle physics
experiments
▪ (up to several Petabytes)
6
DB Tendencies
• Data are recorded by sensors
DBs grow in size
DBs become more widespread
• Computers are becoming more powerful
DB Management Systems
can run on laptops
(and on phones—and soon on chip cards?)

• Multimedia data arise everywhere


Requirements for larger storage
New query operations

7
An Ideal DB Implementation
Should Support:
• Structure • Performance
– data types – retrieve and store data
– data behaviour quickly
• Persistence • Data Integrity
– store data on • Sharing
secondary storage – concurrency
• Retrieval • Reliability and resilience
– a declarative query • Large data volumes
language
– a procedural database
programming language

8
Database Management System (DBMS)
• A DBMS is a software package designed
to store and manage databases
• A DBMS provides generic functionality that
otherwise would have to be implemented over
and over again
Reduced application development time
• Several brands, e.g.,
– Oracle Xi/Yg (Oracle), DB2 (IBM), SQL Server, Access
(Microsoft), MySQL, PostgreSQL (open source)

9
DATABASE METADATA
▪ A DBMS catalog stores the description of a particular database
• e.g. data structures, types, and constraints
• The description is called meta-data.

▪ Database metadata – represents the structure of the database


• Database content that is not the data itself (data about the data)
• Contains:
o Names of data structures
o Data types
o Data descriptions
o Other information describing the characteristics of the data

▪ Metadata - data that describes the structure and the properties of


the data
• Metadata is essential for the proper understanding and use of the data

Chapter 1 – Slide 10
DATABASE METADATA

Data without metadata - example

Chapter 1 – Slide 11
DATABASE METADATA

Data with metadata - example

Chapter 1 – Slide 12
DATABASE METADATA

Chapter 1 – Slide 13
DATABASE SCHEMA VS. DATABASE STATE
▪ Database Schema
• Includes descriptions of the database structure, data types, and
the constraints on the database.
• Schema is also called intension.
• It changes very infrequently.
▪ Database State:
• The database content at a particular moment in time.
• Refers to the of a database at a moment in time.
• Also called instance (or occurrence or snapshot or extension).
• It changes every time the database is updated.
▪ Valid State:
• A state that satisfies the structure and constraints of the
database.

Chapter 1 – Slide 14
EXAMPLE OF A DATABASE SCHEMA

Chapter 1 – Slide 15
EXAMPLE OF A DATABASE STATE

Chapter 1 – Slide 16
DBMS LANGUAGES
1. DDL – Data Definition Language
2. DQL – Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language

Chapter 1 – Slide
17
DBMS LANGUAGES
▪ Data Definition Language (DDL):
• Used by the DBA and database designers to specify the conceptual
schema of a database.
• In many DBMSs, the DDL is also used to define internal and external
schemas (views).
• CREATE (generates a new table)
• ALTER (alters table)
• DROP (removes a table from the database)
▪ Data Manipulation Language (DML):
• Used to specify database retrievals and updates
• Alternatively, stand-alone DML commands can be applied directly
(called a query language).
• INSERT: command to add new or new value to the database.
• UPDATE: command to change or update current/existing data to a more
recent value within the database.
• DELETE: command to delete or delete the values or data information of
the current table in the database.
Chapter 1 – Slide 18
TYPICAL DATABASE SYSTEM ARCHITECTURE

Chapter 1 – Slide 19
TYPICAL DATABASE SYSTEM ARCHITECTURE

Chapter 1 – Slide 20
EXAMPLE OF A DATABASE

▪ UNIVERSITY Registration System.

▪ Some entities:
• STUDENTs
• COURSEs
• SECTIONs (of COURSEs)
• (academic) DEPARTMENTs
• INSTRUCTORs

Chapter 1 – Slide 21
EXAMPLE OF A DATABASE

▪ Some relationships:
• SECTIONs are of specific COURSEs
• STUDENTs take SECTIONs
• COURSEs have prerequisite COURSEs
• INSTRUCTORs teach SECTIONs
• COURSEs are offered by DEPARTMENTs
• STUDENTs major in DEPARTMENTs

▪ Note: The above entities and relationships are typically


expressed in a conceptual data model, such as the
ENTITY-RELATIONSHIP data model.

Chapter 1 – Slide 22
Chapter 1 – Slide
23
EXAMPLE OF A SIMPLE DATABASE

Chapter 1 – Slide 24
TYPICAL DBMS FUNCTIONALITY
▪ Define a particular database in terms of its data types,
structures, and constraints
▪ Construct or Load the initial database contents on a
secondary storage medium
▪ Manipulating the database:
• Retrieval: Querying, generating reports
• Modification: Insertions, deletions and updates to its
content
• Accessing the database through Web applications
▪ Processing and Sharing by a set of concurrent users and
application programs – yet, keeping all data valid and
consistent

Chapter 1 – Slide 25
ADDITIONAL DBMS FUNCTIONALITY
▪ DBMS may additionally provide:
• Protection or Security measures to prevent unauthorized access

• Presentation and Visualization of data


• Data visualization is the graphical representation of information
and data. By using visual elements like charts, graphs, and maps,
data visualization tools provide an accessible way to see and
understand trends, outliers, and patterns in data. Examples : Tableau,
Zoho Analytics
• Backup and Restoring the database.

Chapter 1 – Slide 26
INTERACTION WITH DATABASE

▪ Front-end applications - provide a mechanism for easy


interaction between the users and the DBMS

▪ End-users (business-users) - users using a database


system to support their tasks and processes

▪ Indirect interaction - end-user communicating with the


database through front-end applications

▪ Direct interaction - end-user communicating with the


database directly through DBMS

Chapter 1 – Slide 27
INTERACTION WITH DATABASE

Direct vs. Indirect Interaction

Chapter 1 – Slide 28
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS

Chapter 1 – Slide 29
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS
▪ Requirements collection, definition, and visualization -
results in the requirements specifying which data the
future database system will hold and in what fashion, and
what the capabilities and functionalities of the database
system will be
• The collected requirements should be clearly defined and stated
in a written document, and then visualized

Chapter 1 – Slide 30
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS
▪ Requirements collection, definition, and visualization
• Conceptual database model – a visualization of requirements by
using a conceptual data modeling technique (such as entity-
relationship [ER] modeling)

Chapter 1 – Slide 31
Chapter 1 – Slide 32
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS
Iterative nature of the database requirements collection,
definition, and visualization process

Chapter 1 – Slide 33
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS
▪ Requirements collection, definition, and visualization

Chapter 1 – Slide 34
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS
▪ Database modeling (logical database modeling ) -
creation of the database model that is implementable by
the DBMS software
• Logical database modeling follows conceptual database
modeling

Chapter 1 – Slide 35
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS
▪ Database modeling (logical database modeling )

Chapter 1 – Slide 36
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS
▪ Database implementation - using a DBMS to implement
the database model as an actual database
• Most modern databases are implemented using a relational
DBMS (RDBMS) software
• SQL (Structured Query Language) is a language used by most
RDBMS packages

Chapter 1 – Slide 37
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS
▪ Database implementation - using a DBMS to implement
the database model as an actual database

Chapter 1 – Slide 38
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS
▪ Developing front-end applications - designing and
creating applications for indirect use by the end-users
• Front-end applications are based on the database model and the
requirements specifying the front-end functionalities
• Front-end applications contain interfaces (such as forms and
reports) accessible via a navigation mechanism (such as a menu)

Chapter 1 – Slide 39
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS
▪ Developing front-end applications - designing and
creating applications for indirect use by the end-users
• Database front-end example

Chapter 1 – Slide 40
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS
▪ Database deployment - releasing the database system
for use by the end users

Chapter 1 – Slide 41
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS
▪ Database use - the insertion, modification, deletion and
retrieval of the data in the database system

Chapter 1 – Slide 42
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS
▪ Database use - the insertion, modification, deletion and
retrieval of the data in the database system
• Example of data in a database that can be inserted, modified,
deleted or retrieved

Chapter 1 – Slide 43
STEPS IN THE DEVELOPMENT OF DATABASE
SYSTEMS
▪ Database administration and maintenance - performing
activities that support the database end user, including
dealing with technical issues, such as:
• Providing security for the information contained in the database
• Ensuring sufficient hard-drive space for the database content
• Implementing the backup and recovery procedures

Chapter 1 – Slide 44
Database Actors

Database Application
Designers Programmers “on the scenes”

Database End Users


Administrator • sophisticated
• casual
(DBA) • ‘parametric’ or
‘canned’ transactions

Database

DBMS developers Operators and Maintenance


Tool Developers Personnel “behind the scenes”

Database Management System


Chapter 1 – Slide 45
PEOPLE INVOLVED WITH DATABASE SYSTEMS
▪ Database analysts, designers, and developers
• Database analysts - involved in the requirements collection,
definition, and visualization stage

• Database designers (a.k.a. database modelers or architects) -


involved in the database modeling stage
o Responsible to define the content, the structure, the constraints, and
functions or transactions against the database.
o They must communicate with the end-users and understand their
needs.

• Database developers – in charge of implementing the database


model as a functioning database using the DBMS software

Chapter 1 – Slide 46
PEOPLE INVOLVED WITH DATABASE SYSTEMS

▪ Front-end applications analysts and developers


• Front-end application analysts - in charge of collecting and
defining requirements for front-end applications

• Front-end applications developers - in charge of creating the


front-end applications

Chapter 1 – Slide 47
PEOPLE INVOLVED WITH DATABASE SYSTEMS

▪ Database administrators (DBAs) - perform the tasks


related to the maintenance and administration of a
database system.

▪ Responsible for
• authorizing access to the database
• coordinating and monitoring its use
• acquiring software and hardware resources
• controlling its use
• monitoring efficiency of operations.

Chapter 1 – Slide 48
PEOPLE INVOLVED WITH DATABASE SYSTEMS
▪ Database end users - They use the data for queries,
reports, and some of them update the database content.
• use a database system to support their work- or life-related tasks
and processes

▪ End-users can be categorized into:


• Casual: access database occasionally when needed
• Naïve or Parametric: they make up a large section of the end-
user population.
o They use previously well-defined functions in the form of “canned
transactions” against the database.
o Users of Mobile Apps mostly fall in this category
o Bank-tellers or reservation clerks are parametric users who do this
activity for an entire shift of operations.
o Social Media Users post and read information from websites

Chapter 1 – Slide 49
PEOPLE INVOLVED WITH DATABASE SYSTEMS
• Sophisticated:
o These include business analysts, scientists, engineers, others
thoroughly familiar with the system capabilities.
o Many use tools in the form of software packages that work closely
with the stored database.

• Stand-alone:
o Mostly maintain personal databases using ready-to-use packaged
applications.
o An example is the user of a tax program that creates its own internal
database.
o Another example is a user that maintains a database of personal
photos and videos.

Chapter 1 – Slide 50
OPERATIONAL VERSUS ANALYTICAL
DATABASES
▪ Operational information (transactional information) - the
information collected and used in support of day to day
operational needs in businesses and other organizations

▪ Operational database - collects and presents operational


information in support of daily operational procedures and
processes

▪ Analytical information - the information collected and used in


support of analytical tasks
• Analytical information is based on operational (transactional)
information

▪ Analytical database - collects and presents analytical


information in support of analytical tasks
Chapter 1 – Slide 51
Chapter 1 – Slide 52
ADVANTAGES OF USING THE DATABASE
APPROACH
▪ Controlling redundancy in data storage and in development
and maintenance efforts.

▪ Restricting unauthorized access to data.

▪ Providing Storage Structures (e.g. indexes) for efficient Query


Processing

▪ Providing optimization of queries for efficient processing.

▪ Providing backup and recovery services.

▪ Providing multiple interfaces to different classes of users.

▪ Enforcing integrity constraints on the database.


Chapter 1 – Slide 53
File System Approach

• Uncontrolled redundancy
• Inconsistent data
• Inflexibility
• Limited data sharing
• Poor enforcement of standards
• Low programmer productivity
• Excessive program maintenance
• Excessive data maintenance

Chapter 1 – Slide 54
DBMS Approach
• Controlled redundancy • Services & controls
– consistency of data &
– security & privacy
integrity constraints controls
• Integration of data – backup & recovery
– self-contained
– enforcement of
standards
– represents semantics

of application • Flexibility
• Data and operation – data independence
sharing – data accessibility
– multiple interfaces – reduced program
maintenance
• Ease of application
development 55
A DBMS Presents Programmers and Users with
a Simplified Environment
Users/Programmers
Database System

Queries / Application Programs

DBMS Software
Software to Process Queries / Programs

Software to Access Stored Data

“Catalogue”, Stored Database Stored


“Data dictionary” Definition Database
(Metadata)
Chapter 1 – Slide 56
Data Model, Schema and Instance
Data Model Schema
• A set of concepts that can • A formal definition that fixes
be used to describe the all the relevant features of
structure of a database: the those parts of the real
data types, relationships, world that are of interest to
constraints, semantics and the users of the database
operational behaviour
• The schema of a db is held
• Hides details of data
storage in the data dictionary

Student(studno,name,address)
Schema Course(courseno,lecturer)
(in relational data model)
Student(123,Egger,Bozen)
Instance Course(CS321,Nutt)
57
Copyright (c) 2020 Nenad Jukic and Prospect Press
Other Data Models
Relational model is good for:
• Large amounts of data and simple operations
• Limited navigation, touching only small numbers of
relations/tables
Difficult applications for relational model:
• VLSI design (CAD in general)
ADDER

ALU A
FA
CPU ADDER
ALU

ADDER

• CASE
• Graphical data
• Bill of materials, transitive closure Chapter 1 – Slide 58
Object Data Models
Where number of “relations” is large, relationships are complex
• Object Data Model
• “Knowledge Data Model” (= Objects + Deductive Rules)

Object Data Model (Principles)

1. Complex Objects –
Nested Structure (pointers or references)
2. Encapsulation, set of methods/access functions
3. Object Identity
4. Inheritance – Defining new classes like old classes

Object model: usually, objects are found via explicit navigation.


Also query language in some systems.

Chapter 1 – Slide 59
Data Models

60’s
Hierarchical Network
70's

80's Choice for most


Relational
applications today
90’s

Object Bases Knowledge Bases, Rules

00’s

Semistructured Data, XML Semantic Web, RDF

Chapter 1 – Slide 60
Sharing—Multiple views of data
Database Management System

Database

Chapter 1 – Slide 61
Characteristics of the DB Approach

• Insulation of programs and data


from each other

• Support of multiple user views

• Use of a catalogue to store the schema

How can one realise these principles?

Chapter 1 – Slide 62
Three Levels of Abstraction
ANSI/SPARC architecture for DBMSs (1978):
• Many external views
• One conceptual View 1 View 2 View 3
(= logical) schema mappings
• One physical
(= internal) schema Conceptual Schema
– Views describe how
users see the data mapping
– Conceptual schema Physical Schema
defines logical
structure
– Physical schema
describes the files and
indexes used Chapter 1 – Slide 63
Data Independence
New New functions
hardware Change in
use
New
users New data
Database
User's
view
Change in
New storage Linkage to other technology
techniques databases

• Logical data independence


– change the logical schema without having to change the
external schemas
• Physical data independence
– change the internal schema without having to change the
logical schema
Change the mapping, not the schema!
Chapter 1 – Slide 64
Database Languages
• Data Definition Language (DDL)
– Commands for setting up the schema of a database

– The process of designing a schema can be complex,


may use a design methodology and/or tool

• Data Manipulation Language (DML)


– Commands to manipulate data in database:
RETRIEVE, INSERT, DELETE, MODIFY

– Also called “query language”

Chapter 1 – Slide 65
Host Languages
C, C++, Fortran, Lisp, Java, Perl, …

Application prog.
Calls to
DB DBMS

Local Vars
(Memory)

(Storage)

Host language is completely general (Turing complete)


but gives no support for data manipulation

Query language—less general, “non procedural” and


optimizable Chapter 1 – Slide 66
Building an Application with a DBMS
• Requirements gathering (natural language, pictures)
• Requirements modeling (conceptual data model, ER)
– Decide what entities should be part of the application
and how they should be related
• Schema design and implementation
– Decide on a set of tables, attributes
– Create the tables in the database system
– Populate database (insert records/tuples)
• Write application programs using the DBMS
– … a lot easier now that the data
management is taken care of
Chapter 1 – Slide 67
category Conceptual
name Modeling name

ssn
cid
Course
Student
Takes
quarter

Advises Teaches

Professor

office name faculty


Chapter 1 – Slide
68
Schema Design and Implementation
• Tables:

Student: Takes:
SSN Name Category SSN CID
123-45-6789 Charles undergrad 123-45-6789 CSE444
234-56-7890 Dan grad 123-45-6789 CSE444
… … 234-56-7890 CSE142

Course:
CID Name Quarter
CSE444 Databases fall
CSE541 Operating systems winter

• The logical schema separates the logical view


from the physical view of the data.
Chapter 1 – Slide 69
Querying a Database

• “Find all courses that Mary takes”


• S(tructured) Q(uery) L(anguage)

▪ select c.name
from Student s, Takes t,
Course c
where s.name = ’Mary’ and
s.ssn = t.ssn and
t.cid = c.cid
• The query processor figures out
how to answer the query efficiently
Chapter 1 – Slide 70
Query Optimization
Goal: Declarative SQL query Query execution plan
select c.name Course.name
from Student s, Takes t,
Course c
where s.name = ’Mary’ and
s.ssn = t.ssn and cid=cid
t.cid = c.cid

sid=sid

name= ’Mary’

Student Takes Course

Plan: Tree of relational algebra operators,


choice of algorithm for each operator
Ideally: Find best plan Practically: Avoid worst plans! Chapter 1 – Slide 71
Traditional and Novel Data Management Issues

• Traditional Data Management:


– Relational data for enterprise applications
– Storage
– Query processing/optimization
– Transaction processing

• Novel Data Management:


– Integration of data from multiple databases, warehousing
– Data management for decision support, data mining
– Managing documents, audio, and visual data
– Exchange of data on the web: XML
– Data Streams
– Incomplete and probabilistic data

Chapter 1 – Slide 72
CHAPTER 2 - Database Requirements and ER
Modeling

Chapter 2 – Slide 1
INTRODUCTION

▪ Entity-relationship (ER) modeling - conceptual database


modeling technique
• Enables the structuring and organizing of the requirements collection
process
• Provides a way to graphically represent the requirements
▪ ER diagram (ERD) - the result of ER modeling
• Serves as a blueprint for the database

Chapter 2 – Slide 2
DATA MODELS
▪ Data Model:
• A set of concepts to describe the structure of a database, the
operations for manipulating these structures, and certain
constraints that the database should obey.

▪ Data Model Structure and Constraints:


• Constructs are used to define the database structure
• Constructs typically include elements (and their data types) as
well as groups of elements (e.g. entity, record, table), and
relationships among such groups
• Constraints specify some restrictions on valid data; these
constraints must be enforced at all times

Chapter 2 – Slide 3
DATA MODELS (CONTINUED)

▪ Data Model Operations:


• These operations are used for specifying database retrievals and
updates by referring to the constructs of the data model.

• Operations on the data model may include basic model operations (e.g.
generic insert, delete, update) and user-defined operations (e.g.
compute_student_gpa, update_inventory)

Chapter 2 – Slide 4
ENTITIES

▪ Entities - constructs that represent what the database keeps


track of
• The basic building blocks of an ER diagram
• Represent various real world notions, such as people, places, objects,
events, items, and other concepts
• Within one ERD each entity must have a different name

Chapter 2 – Slide 5
ENTITIES

Two entities

Chapter 2 – Slide 6
ENTITIES

▪ Entity instances (entity members) - occurrences of an entity


• Entities themselves are depicted in the ER diagrams while entity
instances are not
• Entity instances are eventually recorded in the database that is created
based on the ER diagram

Chapter 2 – Slide 7
ATTRIBUTES

▪ Attribute - depiction of a characteristic of an entity


• Represents the details that will be recorded for each entity instance
• Within one entity, each attribute must have a different name
▪ Unique Attribute - attribute whose value is different for each
entity instance
• Every regular entity must have at least one unique attribute

Chapter 2 – Slide 8
ATTRIBUTES

An entity with attributes


• For entity CUSTOMER, we may decide to keep track of the following
attributes: CustID (customer’s identification number), CustName
(customer’s name), CustBdate (customer’s birth date), and CustGender
(customer’s gender)."

Chapter 2 – Slide 9
RELATIONSHIPS

▪ Relationship - ER modeling construct depicting how entities are


related
• Within an ER diagram, each entity must be related to at least one other
entity via a relationship

Chapter 2 – Slide 10
RELATIONSHIPS

▪ Cardinality constraints - depict how many instances of one


entity can be associated with instances of another entity
• Maximum cardinality
o One (represented by a straight bar: I)

o Many (represented by a crow’s foot symbol: )


• Minimum cardinality (participation)
o Optional (represented by a circular symbol: 0)

o Mandatory (represented by a straight bar: I)

Chapter 2 – Slide 11
RELATIONSHIPS
A relationship between two entities
▪ The database will keep track of employees and departments.
• For each employee, we will keep track of his or her name and unique
employee ID.
• For each department, we will keep track of the unique department ID
and the location.
• Each employee reports to exactly one department. A department has
between zero and many employees reporting to it.

Chapter 2 – Slide 12
RELATIONSHIPS

Four possible cardinality constraints

Chapter 2 – Slide 13
Chapter 2 – Slide 14
RELATIONSHIPS
Several possible versions of the relationship ReportsTo

Chapter 2 – Slide 15
RELATIONSHIPS
Several possible versions of the relationship ReportsTo

Chapter 2 – Slide 16
RELATIONSHIPS

▪ Types of Relationships (maximum cardinality-wise)


• One-to-one relationship (1:1)
• One-to-many relationship (1:M)
• Many-to-many relationship (M:N)

Chapter 2 – Slide 17
RELATIONSHIPS

Three types of relationships (maximum cardinality-wise)

Chapter 2 – Slide 18
RELATIONSHIPS
A 1:M Relationship

A M:N Relationship

A 1:1 Relationship

Chapter 2 – Slide 19
RELATIONSHIPS

▪ Relationship instances - occurrences of a relationship


• Occur when an instance of one entity is related to an instance of
another entity via a relationship
• Relationship themselves are depicted in the ER diagrams while
relationship instances are not
• Relationship instances are eventually recorded in the database that is
created based on the ER diagram

Chapter 2 – Slide 20
RELATIONSHIPS
A relationship and its instances

Chapter 2 – Slide 21
RELATIONSHIPS
▪ Relationship attributes
• In some cases M:N relationships can actually have attributes of their own

Chapter 2 – Slide 22
RELATIONSHIPS
A 1:M relationship with and without an attribute

Chapter 2 – Slide 23
RELATIONSHIPS
A 1:M relationship with and without an attribute

Chapter 2 – Slide 24
ER diagram example: ZAGI Retail Company Sales Department Database

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 2 – Slide 25


ZAGI RETAIL COMPANY SALES DEPARTMENT DATABASE

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 2 – Slide 26


ZAGI RETAIL COMPANY SALES DEPARTMENT DATABASE

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 2 – Slide 27


ATTRIBUTES

▪ Composite attribute – attribute that is composed of several


attributes
• Not an additional attribute of an entity
• Its purpose is to indicate a situation in which a collection of attributes
has an additional meaning, besides the individual meanings of each
attribute

Chapter 2 – Slide 28
ATTRIBUTES

An entity with a composite attribute

Chapter 2 – Slide 29
ATTRIBUTES

Another entity with a composite attribute

Chapter 2 – Slide 30
ATTRIBUTES

Composite attributes sharing components

Chapter 2 – Slide 31
ATTRIBUTES
▪ Composite unique attribute – attribute that is composed of several
attributes and whose value is different for each entity instance.
▪ An entity with a unique composite attribute

Chapter 2 – Slide 32
ATTRIBUTES

▪ Multiple unique attributes (candidate keys) - when an entity has


more than one unique attribute each unique attribute is also
called a candidate key.
▪ An entity with multiple unique attributes (candidate keys)

Chapter 2 – Slide 33
ATTRIBUTES

An entity with a regular and composite candidate key

Chapter 2 – Slide 34
ATTRIBUTES

▪ Multivalued attribute - attribute for which instances of an entity


can have multiple values for the same attribute.
▪ A multivalued attribute

Chapter 2 – Slide 35
ATTRIBUTES

A scenario that does not use multivalued attributes

Chapter 2 – Slide 36
ATTRIBUTES

▪ Derived attribute - attribute whose values are calculated and


not permanently stored in a database.
▪ A derived attribute example

Chapter 2 – Slide 37
ATTRIBUTES
Another derived attribute example

Chapter 2 – Slide 38
ATTRIBUTES

▪ Optional attribute - attribute that is allowed to not have a value.


▪ An optional attribute example

Chapter 2 – Slide 39
ATTRIBUTES
EXAMPLE: An entity with various types of attributes

Chapter 2 – Slide 40
ATTRIBUTES
EXAMPLE: An entity with various types of attributes

Chapter 2 – Slide 41
RELATIONSHIPS
▪ Exact minimum and maximum cardinality in relationships
• In some cases the exact minimum and/or maximum cardinality in relationships
is known in advance
• Exact minimum/and or maximum cardinalities can be depicted in ER diagrams.
▪ A relationship with specific minimum and maximum cardinalities

Chapter 2 – Slide 42
RELATIONSHIPS

A relationship with a mixture of specific and non-specific


cardinalities

Chapter 2 – Slide 43
RELATIONSHIPS

▪ Degree of a relationship - reflects how many entities are


involved in the relationship
▪ Binary relationship - relationship between two entities
(degree 2 relationship)
▪ Unary relationship (recursive relationship) - occurs when an
entity is involved in a relationship with itself
(degree 1 relationship)

Chapter 2 – Slide 44
RELATIONSHIPS
Unary relationship examples

Chapter 2 – Slide 45
RELATIONSHIPS

▪ Relationship roles - additional syntax that can be used in ER


diagrams at the discretion of a data modeler to clarify the role
of each entity in a relationship

Chapter 2 – Slide 46
RELATIONSHIPS
Unary relationships with role names

Chapter 2 – Slide 47
RELATIONSHIPS

A binary relationship with role names

Chapter 2 – Slide 48
RELATIONSHIPS
▪ Multiple relationships between same entities
• Same entities in an ER diagram can be related via more than one relationship .
▪ Multiple relationships between the same entities

Chapter 2 – Slide 49
WEAK ENTITY

▪ Weak entity - ER diagram construct depicting an entity that


does not have a unique attribute of its own
▪ Owner entity - entity whose unique attribute provides a
mechanism for identifying instances of a weak entity
▪ Identifying relationship - relationship between a weak entity
and its owner entity in which each instance of a weak entity is
associated with exactly one instance of an owner entity
• Each weak entity must be associated with its owner entity via an
identifying relationship
• Unique attribute from the owner entity uniquely identifies every instance
of the weak entity via an identifying relationship

Chapter 2 – Slide 50
WEAK ENTITY

▪ Partial key - attribute of a weak entity that combined with the


unique attribute of the owner entity uniquely identifies the
weak entity's instances
• Combination of the partial key and the unique attribute from the owner
entity uniquely identifies every instance of the weak entity

Chapter 2 – Slide 51
WEAK ENTITY
A weak entity example with entity instances

Chapter 2 – Slide 52
WEAK ENTITY
A weak entity versus a multivalued composite attribute

Chapter 2 – Slide 53
WEAK ENTITY
A weak entity with an identifying and regular relationship

Chapter 2 – Slide 54
WEAK ENTITY

▪ Identifying relationship is either 1:M or 1:1 relationship


• In case of 1:M identifying relationship, a weak entity must have a partial
key attribute
• In case of 1:1 identifying relationship, a weak entity doesn’t need to
have a partial key attribute

Chapter 2 – Slide 55
WEAK ENTITY

A weak entity with a 1:1 identifying relationship

Chapter 2 – Slide 56
NAMING CONVENTIONS FOR ER DIAGRAMS

▪ Entities and attributes


• Use singular (rather than plural) nouns

▪ Relationships
• Use verbs or verb phrases, rather than nouns

▪ Names should be as brief as possible, without being too


condensed as to obscure the meaning of the construct

▪ If possible, give all attributes in the entire ER diagram different


names

Chapter 2 – Slide 57
MULTIPLE ER DIAGRAMS

▪ When depicting multiple ER diagrams, each diagram should be


visualized separately
▪ Instead of multiple ER diagrams in one schema a better choice
is to present each ER diagram separately

Chapter 2 – Slide 58
MULTIPLE ER DIAGRAMS
A schema with two separate ER diagrams (potentially misleading)

Chapter 2 – Slide 59
MULTIPLE ER DIAGRAMS
Separate ER diagrams in separate schemas

Chapter 2 – Slide 60
MULTIPLE ER DIAGRAMS
Separate ER diagrams in separate schemas

Chapter 2 – Slide 61
HAFH Realty Company Property Management Database

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 2 – Slide 62


Chapter 2 – Slide 63
HAFH Realty Company Property Management Database

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 2 – Slide 64


DATABASE REQUIREMENTS AND ER MODEL USAGE
▪ One of the common mistakes that beginners make when engaging in ER modeling
for the first time is not recognizing the difference between an entity and the ER
diagram itself.
▪ An ER diagram incorrectly and correctly interpreting requirements

Chapter 2 – Slide 65
DATABASE REQUIREMENTS AND ER MODEL USAGE
An ER diagram incorrectly and correctly interpreting requirements.
In this case, entity COLLEGE would be unnecessary.

Chapter 2 – Slide 66
DATABASE REQUIREMENTS AND ER MODEL USAGE

▪ Another common database requirements collection and ER


modeling mistake made by novices is not distinguishing
between:

Modeling of the data that is wanted and can be kept track of


versus
Modeling of everything that takes place in an organization

Chapter 2 – Slide 67
DATABASE REQUIREMENTS AND ER MODEL USAGE
ER diagrams based on unfeasible vs. proper requirements

Chapter 2 – Slide 68
DATABASE REQUIREMENTS AND ER MODEL USAGE
ER diagrams based on unfeasible vs. proper requirements

Chapter 2 – Slide 69
VARIOUS ER NOTATIONS

▪ There is no universally adopted ER notation to which all


database projects conform
▪ Instead, there is a variety of available ER notations in use
▪ However, if a designer is familiar with one ER notation, other
alternative ER notations are easy to understand and use

Chapter 2 – Slide 70
VARIOUS ER NOTATIONS
Examples of various ER notations

Chapter 2 – Slide 71
TERNARY RELATIONSHIP
▪ Ternary relationship - relationship involving three entities (degree 3 relationship)

Chapter 2 – Slide 72
TERNARY RELATIONSHIP
Three binary relationships that are insufficient for depicting given
requirements.

A ternary relationship

Chapter 2 – Slide 73
TERNARY (AND HIGHER DEGREE) RELATIONSHIPS

▪ In practice, ternary relationships are relatively rare, and


relationships of degree higher than 3 are rarer still

Chapter 2 – Slide 74
REDUCING THE NUMBER OF ATTRIBUTES

▪ Reducing the number of attributes by treating some attributes


as attribute values
• In some cases, it may be appropriate to consider whether an originally
designed attribute can be treated as an attribute value instead
• Valid alternative in some circumstances (but not always)

Chapter 2 – Slide 75
REDUCING THE NUMBER OF ATTRIBUTES
▪ Example of reducing the number of attributes by treating some
attributes as attribute values:

Chapter 2 – Slide 76
REDUCING THE NUMBER OF ATTRIBUTES

▪ Example of reducing the number of attributes by treating some


attributes as attribute values:

Relationship

Chapter 2 – Slide 77
A NOTE ABOUT M:N RELATIONSHIPS WITH MULTIPLE
INSTANCES BETWEEN THE SAME ENTITIES
▪ In some cases, M:N relationships can have multiple
occurrences between the same instances of involved entities.
The following example illustrates such a case.
• • The database will keep track of students and classes.
• • For each student, we will keep track of his or her unique student ID
and name.
• • For each class, we will keep track of the unique class ID and the class
level.
• • Each student in the database can complete multiple classes, but does
not have to complete any.
• • Each class in the database was completed by at least one student and
could have been completed by multiple students.
• • For every instance of a student completing a class, we will record the
class grade and the semester.

Chapter 2 – Slide 78
Chapter 2 – Slide 79
IF WE NOW ADD A SMALL BUT CRITICAL ADDITION TO
THE REQUIREMENTS

▪ If we now add a small but critical addition to the above


requirements, we will fundamentally change the nature of the
depicted M:N relationship:
▪ • A student can take the same class more than once (e.g., if a
student receives a grade below a minimum grade, he has to
take the same class again, until the minimum grade is
achieved).
▪ This addition now allows for multiple instances of a relationship
between the same instances of entities. This is illustrated by
Figure 2.45, in which Pat takes the same class IS101 three
times

Chapter 2 – Slide 80
Chapter 2 – Slide 81
CHAPTER 3 - Relational Database Modeling
INTRODUCTION

▪ Relational database model - logical database model that


represents a database as a collection of related tables
▪ Relational schema - visual depiction of the relational database
model
▪ Most contemporary commercial DBMS software packages, are
relational DBMS (RDBMS) software packages

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 2


INTRODUCTION

Terminology

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 3


INTRODUCTION
▪ Relation - table in a relational database
• A table containing rows and columns
• The main construct in the relational database model
• Every relation is a table, not every table is a relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 4


INTRODUCTION
▪ Relation - table in a relational database
• In order for a table to be a relation the following conditions must hold:
o Within one table, each column must have a unique name.

o Within one table, each row must be unique.

o All values in each column must be from the same (predefined) domain.

o Within each row, each value in each column must be single valued (one

value from a predefined domain, within each row in each column).

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 5


INTRODUCTION
Example of relational and non-relational tables

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 6


INTRODUCTION
▪ Relation - table in a relational database
• Two additional properties of each table:
o Order of columns is irrelevant.

o Order of rows is irrelevant.

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 7


INTRODUCTION
Example of a relation with rows and columns appearing in a
different order

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 8


INTRODUCTION

▪ Relational database - collection of related relations within


which each relation has a unique name

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 9


PRIMARY KEY

▪ Primary key - column (or a set of columns) whose value is


unique for each row
• Each relation must have a primary key
• The name of the primary key column is underlined in order to distinguish
it from the other columns in the relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 10


PRIMARY KEY

Relation with the primary key underlined

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 11


MAPPING ER DIAGRAMS INTO RELATIONAL SCHEMAS

▪ Once an ER diagram is constructed, it is subsequently mapped


into a relational schema (collection of relations)

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 12


MAPPING ENTITIES

▪ Mapping entities into relations


• Each regular entity becomes a relation
• Each regular attribute of a regular entity becomes a column of the newly
created relation
• If an entity has a single unique attribute, then that attribute becomes
the primary key in the resulting mapped relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 13


MAPPING ENTITIES
Entity mapped
into a relation

Sample data
records for the
mapped relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 14


MAPPING ENTITIES WITH COMPOSITE ATTRIBUTES

▪ Mapping entities with composite attributes into relations


• Each component of a composite attribute is mapped as a column of a
relation
• The composite attribute itself does not appear in the mapped relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 15


MAPPING ENTITIES WITH COMPOSITE ATTRIBUTES

Entity with a
composite
attribute mapped
into a relation

Sample data
records for the
mapped relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 16


MAPPING ENTITIES WITH COMPOSITE ATTRIBUTES

The mapped
relation as
presented to a
user in a front-end
application

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 17


COMPOSITE PRIMARY KEY

▪ Composite primary key - a primary key that is composed of


multiple columns
• Column names of a composite primary key are underlined, because
combined together they form the primary key

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 18


MAPPING ENTITIES WITH UNIQUE COMPOSITE
ATTRIBUTES

▪ Mapping entities with unique composite attributes into


relations
• An entity whose only unique attribute is a composite attribute is mapped
as a relation with a composite primary key

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 19


MAPPING ENTITIES WITH UNIQUE COMPOSITE
ATTRIBUTES
Entity with a
unique composite
attribute mapped
into a relation

Sample data
records for the
mapped relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 20


MAPPING ENTITIES WITH OPTIONAL ATTRIBUTES

▪ Mapping entities with optional attributes into relations


• Optional attribute of an entity is mapped as an optional column

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 21


MAPPING ENTITIES WITH OPTIONAL ATTRIBUTES
Entity with an
optional attribute
mapped into a
relation

Sample data
records for the
mapped relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 22


ENTITY INTEGRITY CONSTRAINT

▪ Entity integrity constraint - in a relational table, no primary key


column can have null (empty) values
• A rule stating that no primary key column can be optional
• Every RDBMS enforces this rule

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 23


ENTITY INTEGRITY CONSTRAINT

Entity integrity constraint — compliance and violation example

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 24


ENTITY INTEGRITY CONSTRAINT

Entity integrity constraint — another compliance and violation


example

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 25


FOREIGN KEY

▪ Foreign key - column in a relation that refers to a primary key


column in another (referred) relation
• A mechanism that is used to depict relationships in the relational
database model
• For every occurrence of a foreign key, the relational schema contains a
line pointing from the foreign key to the corresponding primary key

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 26


MAPPING RELATIONSHIPS

▪ Mapping 1:M relationships


• The relation mapped from the entity on the M side of the 1:M
relationship has a foreign key that corresponds to the primary key of the
relation mapped from the 1 side of the 1:M relationship.

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 27


MAPPING RELATIONSHIPS
Example -
Mapping a
1:M
relationship

Sample data
records for the
mapped ER
diagram
Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 28
MAPPING RELATIONSHIPS
Example -
Mapping a
1:M
relationship
Mandatory
participation
on both sides

Sample data
records for the
mapped ER
diagram
Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 29
MAPPING RELATIONSHIPS
Example -
Mapping a
1:M
relationship
Optional
participation
on the 1 side

Sample data
records for the
mapped ER
diagram
Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 30
MAPPING RELATIONSHIPS
Example -
Mapping a
1:M
relationship
Optional
participation
on the M side

Sample data
records for the
mapped ER
diagram
Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 31
MAPPING RELATIONSHIPS
Example -
Mapping a
1:M
relationship
Renaming a
foreign key

Sample data
records for the
mapped ER
diagram
Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 32
MAPPING RELATIONSHIPS

▪ Mapping M:N relationships


• In addition to the two relations representing the two entities involved in
the M:N relationship, another relation is created to represent the M:N
relationship itself
• This new relation has two foreign keys, corresponding to the primary
keys of the two relations representing the two entities involved in the
M:N relationship
• The two foreign keys form the composite primary key of the new relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 33


MAPPING RELATIONSHIPS
Example -
Mapping an
M:N
relationship

Sample data
records for the
mapped ER
diagram
Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 34
MAPPING RELATIONSHIPS
Example -
Mapping an
M:N
relationship
Optional
participation
on both sides

Sample data
records for the
mapped ER
diagram
Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 35
MAPPING RELATIONSHIPS
Example -
Mapping a
M:N
relationship
with an
attribute

Sample data
records for
the mapped
ER diagram
Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 36
MAPPING RELATIONSHIPS

▪ Mapping 1:1 relationships


• 1:1 relationships are mapped in the same way as 1:M relationships
• One of the resulting relations will have a foreign key pointing to the
primary key of another resulting relation
• One of the mapped relations is chosen to have a foreign key referring to
the primary key of the other mapped relation
o In cases when there is no particular advantage in choosing which resulting
relation will include a foreign key, the choice can be arbitrary
o In other cases one choice can be more efficient than the other

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 37


MAPPING RELATIONSHIPS INTO RELATIONAL
DATABASE CONSTRUCTS
Example -
Mapping a
1:1
relationship

Sample data
records for the
mapped ER
diagram
Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 38
REFERENTIAL INTEGRITY CONSTRAINT

▪ Referential integrity constraint - In each row of a relation


containing a foreign key, the value of the foreign key EITHER
matches one of the values in the primary key column of the
referred relation OR the value of the foreign key is null (empty).
• A rule that defines values that are valid for use in foreign keys
• In a relational schema lines pointing from the foreign key to the
corresponding primary key are referred to as referential integrity
constraint lines

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 39


REFERENTIAL INTEGRITY CONSTRAINT

Referential integrity
constraint —
compliance example

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 40


REFERENTIAL INTEGRITY CONSTRAINT

Referential integrity
constraint —
compliance example

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 41


REFERENTIAL INTEGRITY CONSTRAINT

Referential integrity
constraint —
violation example

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 42


Example ER diagram : ZAGI Retail Company Sales Department Database

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 43


Example mapped relational schema: ZAGI Retail Company Sales Department Database

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 44


Example: Sample data records for the ZAGI Retail Company Sales Department Database

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 45


GRANULARITY OF THE TABLE

▪ Granularity of the table


• Describes what is depicted by one row in the table

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 46


MAPPING CANDIDATE KEYS

▪ Mapping entities with candidate keys (multiple unique


attributes) into relations
• One of the candidate keys is chosen by the database designer as the
primary key during the mapping process
• Other candidate keys are mapped as non-primary key columns

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 47


MAPPING ENTITIES WITH CANDIDATE KEYS (MULTIPLE
UNIQUE ATTRIBUTES) INTO RELATIONS
Entity with
candidate keys
mapped
into a relation

Sample data
records for the
mapped relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 48


MAPPING CANDIDATE KEYS
Entity with regular
and composite
candidate keys
mapped into a
relation

Sample data
records for the
mapped relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 49


MAPPING MULTIVALUED ATTRIBUTES

▪ Mapping entities with multivalued attributes into relational


database constructs
• An entity containing the multivalued attribute is mapped without the
multi-valued attribute
• The multi-valued attribute is mapped as a separate relation that has a
column representing the multivalued attribute and a foreign key column
referring to the primary key of the relation resulting from the entity itself
o Both of these columns form a composite primary key for the separate
relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 50


MAPPING MULTIVALUED ATTRIBUTES
Entity with a
multivalued
attribute mapped
into relations

Sample data
records for the
mapped relations

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 51


MAPPING DERIVED ATTRIBUTES

▪ Mapping derived attributes


• Derived attributes are not mapped as a part of the relational schema
• They are implemented as a part of the database front-end application

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 52


MAPPING DERIVED ATTRIBUTES
Entity with
derived attributes
mapped into a
relation

Sample data The relation


records for shown as
the presented to
mapped a user in a
relation front-end
application
Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 53
Example : Entity with various types of attributes mapped into a relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 54


Example : Sample data records for the mapped relations

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 55


MAPPING UNARY RELATIONSHIPS

▪ Mapping unary relationships


• Unary relationships in ER diagrams are mapped in the same way as
binary relationships

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 56


MAPPING UNARY RELATIONSHIPS

▪ Mapping 1:M unary relationships


• The relation mapped from an entity involved in a 1:M unary relationship
contains a foreign key that corresponds to its own primary key

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 57


MAPPING UNARY RELATIONSHIPS

Mapping a 1:M
unary relationship

Sample data
records for the
mapped relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 58


MAPPING UNARY RELATIONSHIPS

▪ Mapping M:N unary relationships


• In addition to the relation representing the entity involved in a unary
M:N relationship, another relation is created to represent the M:N
relationship itself
• This new relation has two foreign keys, both of them corresponding to
the primary key of the relation representing the entity involved in the
unary M:N relationship
• Each of the foreign keys is used as a part of the composite primary key
of the new relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 59


MAPPING UNARY RELATIONSHIPS

Mapping a M:N
unary relationship

Sample data
records for the
mapped relations

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 60


MAPPING UNARY RELATIONSHIPS

▪ Mapping 1:1 unary relationships


• Mapped in the same way as 1:M unary relationships

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 61


MAPPING UNARY RELATIONSHIPS

Mapping a 1:1
unary relationship

Sample data
records for the
mapped relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 62


MAPPING MULTIPLE RELATIONSHIPS BETWEEN THE
SAME ENTITIES

▪ Mapping multiple relationships between the same entities


• Each relationship is mapped

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 63


MAPPING MULTIPLE RELATIONSHIPS BETWEEN THE
SAME ENTITIES
Mapping multiple
relationships
between the
same entities

Sample data
records for the
mapped relations

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 64


MAPPING WEAK ENTITIES

▪ Mapping weak entities


• Weak entities are mapped in a same way as regular entities with one
addition:
o The resulting relation has a composite primary key that is composed of the
partial identifier and the foreign key corresponding to the primary key of the
owner entity

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 65


MAPPING WEAK ENTITIES

Mapping a
weak entity

Sample data
records for the
mapped relations

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 66


MAPPING WEAK ENTITIES

Mapping a
weak entity
with two
owners

Sample
data
records for
the mapped
relations
Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 67
MAPPING WEAK ENTITIES

Mapping a weak
entity with no
partial identifier

Sample data
records for the
mapped relations

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 68


Example ER diagram : HAFH Realty Company Property Management Database

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 69


Example mapped relational schema: HAFH Realty Company Property Management
Database

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 70


Example: Sample data records for the HAFH Realty Company Property Management
Database (part 1)

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 71


RELATIONAL DATABASE CONSTRAINTS

▪ Relational database constraints - rules that a relational


database has to satisfy in order to be valid
• Implicit constraints
o The implicit relational database model rules that a relational database must
satisfy in order to be valid
• User-defined constraints
o Database constraints that are added by the database designer

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 72


RELATIONAL DATABASE CONSTRAINTS
▪ Implicit constraints
• Each relation in a relational schema must have a different name
• Each relation must satisfy the following conditions:
o Each column must have a different name

o Each row must be unique

o Domain constraint - all values in each column must be from the same
predefined domain
o In each row, each value in each column must be single valued

o The order of columns is irrelevant

o The order of rows is irrelevant

• Primary key constraint - each relation must have a primary key, which is
a column (or a set of columns) whose value is unique for each row
• Entity integrity constraint
• Referential integrity constraint

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 73


INTEGRITY CONSTRAINTS

❖ Integrity constraints are a set of rules. It is used to maintain the


quality of information.
❖ Integrity constraints ensure that the data insertion, updating, and
other processes have to be performed in such a way that data
integrity is not affected.
❖ Thus, integrity constraint is used to guard against accidental
damage to the database.

Jukić, Vrbsky, Nestorov, Sharma, Sharma – Database Systems Chapter 1 – Slide 74


TYPES OF INTEGRITY CONSTRAINT

Jukić, Vrbsky, Nestorov, Sharma, Sharma – Database Systems Chapter 1 – Slide 75


INTEGRITY CONSTRAINTS
Integrity Constraints in the Relational Model

• Integrity constraints :

▪ Integrity constraints = constraints that every tuple in a relational


database must satisfy.

• Types of constraints:

▪ Key constraint
▪ Entity integrity constraint
▪ Referential integrity constraint

Jukić, Vrbsky, Nestorov, Sharma, Sharma – Database Systems Chapter 1 – Slide 76


1. DOMAIN CONSTRAINTS
❑ Domain constraints can be defined as the definition of a valid set
of values for an attribute.
❑ The data type of domain includes string, character, integer, time,
date, currency, etc. The value of the attribute must be available in
the corresponding domain.
▪ Example:

Jukić, Vrbsky, Nestorov, Sharma, Sharma – Database Systems Chapter 1 – Slide 77


2. ENTITY INTEGRITY CONSTRAINTS
❑ The entity integrity constraint states that primary key value can't
be null.
❑ This is because the primary key value is used to identify individual
rows in relation and if the primary key has a null value, then we
can't identify those rows.
❑ A table can contain a null value other than the primary key field.
❑ Example:

Jukić, Vrbsky, Nestorov, Sharma, Sharma – Database Systems Chapter 1 – Slide 78


Entity Integrity constraint

• Entity integrity constraint:

▪ The attribute values of the primary


key cannot have NULL values

This constraint make perfect sense:

▪ The primary key is used to identify a tuple


▪ NULL value means Not Applicablex or Not Available
▪ In either case, the primary key would be crippled (useless) in its ability
to identify a tuple.

Jukić, Vrbsky, Nestorov, Sharma, Sharma – Database Systems Chapter 1 – Slide 79


3. REFERENTIAL INTEGRITY CONSTRAINTS
❖ A referential integrity constraint is specified between two tables.
❖ In the Referential integrity constraints, if a foreign key in Table 1
refers to the Primary Key of Table 2, then every value of the
Foreign Key in Table 1 must be null or be available in Table 2.
▪ Example:

Jukić, Vrbsky, Nestorov, Sharma, Sharma – Database Systems Chapter 1 – Slide 80


Referential Integrity constraint

• Referential integrity constraint:

▪ Suppose relation schema R1 contains a foreign key (which is the primary key) of
the relation schema R2 (in other words: R1 "points to" R2).
▪ Then the following constraint must hold:

▪ if a tuple t1 in R1 that references the tuple t2 in R2, then the tuple t2 must exist

Jukić, Vrbsky, Nestorov, Sharma, Sharma – Database Systems Chapter 1 – Slide 81


Jukić, Vrbsky, Nestorov, Sharma, Sharma – Database Systems Chapter 1 – Slide 82
Pictorially explanation of Referential integrity constraint:

Jukić, Vrbsky, Nestorov, Sharma, Sharma – Database Systems Chapter 1 – Slide 83


4. KEY CONSTRAINTS
❖ Keys are the entity set that is used to identify an entity within its
entity set uniquely.
❖ An entity set can have multiple keys, but out of which one key will
be the primary key. A primary key can contain a unique and null
value in the relational table.
▪ Example

Jukić, Vrbsky, Nestorov, Sharma, Sharma – Database Systems Chapter 1 – Slide 84


KEY CONSTRAINT

Key constraint

• Key constraint:

▪ Every relation schema must have a primary key

NOTE:

▪ A key may consist of all attributes in the relation !!!

(Usually, a key is a subset of the attributes in a relation).

Jukić, Vrbsky, Nestorov, Sharma, Sharma – Database Systems Chapter 1 – Slide 85


RELATIONAL DATABASE CONSTRAINTS

▪ User-defined constraints
• Added by the database designers

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 86


RELATIONAL DATABASE CONSTRAINTS

Specific
minimum
and
maximum
cardinalities

Sample data
records for the
mapped relations

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 87


RELATIONAL DATABASE CONSTRAINTS

▪ Business rules
• User defined constraints that specify restrictions on databases that are
not a part of the standard notation for creating ER diagrams

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 88


ENTERPRISE CONSTRAINTS

▪ Enterprise constraints – sometimes referred to as


semantic constraints – are additional rules specified by
users or database administrators and can be based on
multiple tables.
▪ Here are some examples.
• A class can have a maximum of 30 students.
• A teacher can teach a maximum of four classes per semester.
• An employee cannot take part in more than five projects.
• The salary of an employee cannot exceed the salary of the
employee’s

Jukić, Vrbsky, Nestorov, Sharma, Sharma – Database Systems Chapter 1 – Slide 89


BUSINESS RULES
▪ Business rules are obtained from users when gathering
requirements. The requirements-gathering process is
very important, and its results should be verified by the
user before the database design is built. If the business
rules are incorrect, the design will be incorrect, and
ultimately the application built will not function as
expected by the users.
▪ Some examples of business rules are:
• A teacher can teach many students.
• A class can have a maximum of 35 students.
• A course can be taught many times, but by only one instructor.
• Not all teachers teach classes

Jukić, Vrbsky, Nestorov, Sharma, Sharma – Database Systems Chapter 1 – Slide 90


RELATIONAL DATABASE CONSTRAINTS
Business rule for
salary amounts

Sample data
records for the
mapped relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 91


RELATIONAL DATABASE CONSTRAINTS
Business rule for
the dates of
enrollment and
graduation

Sample data
records for the
mapped relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 92


RELATIONAL DATABASE CONSTRAINTS

Business rule for


gender of
students in an
organization

Sample data
records for the
mapped relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 93


MAPPING ASSOCIATIVE ENTITIES

▪ Mapping associative entities


• Associative entities are mapped into relational database constructs in
the identical way as M:N relationships

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 94


Example: An M:N relationship and associative entity mapped into a relation in the
same way

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 95


MAPPING TERNARY RELATIONSHIPS

▪ Mapping ternary relationships


• Ternary relationships are used as many-to-many-to-many relationships
• A new relation is created with foreign keys from the participating entities
forming a composite primary key of the new relation

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 96


Example: Mapping a ternary relationship

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 97


Example: Sample data records for the mapped relations

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 98


DESIGNER-CREATED PRIMARY KEYS AND THE
AUTONUMBER OPTION

▪ Autonumber data type option - enables automatic generation of


consecutive numeric data values in a column
▪ Designer-created primary key - primary key column, not called
for by the original requirements, added to a table by the
database designer
• Often used in conjunction with the autonumber data type option

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 99


DESIGNER-CREATED PRIMARY KEYS AND THE
AUTONUMBER OPTION
Entity and the resulting relation with a
Entity and the resulting relation designer-created primary key column

Sample data
records for the
relation with a
designer-created
primary key

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide


ER AND RELATIONAL MODELING

▪ Process of requirements collection should be accompanied by


the ER modeling and then followed by mapping the ER model
into a subsequent relational schema
▪ Some practitioners prefer to create relational schemas straight
from the requirements
• In such cases, the ER modeling phase is simply omitted

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide


ER AND RELATIONAL MODELING

▪ Create relational schemas straight from the requirements is not


advisable for following reasons
• ER modeling is more suited for visualization of the requirements
• Certain concepts can be visualized graphically only in ER diagrams
• Every attribute is mentioned only once in the ER diagram
• An ER model is a better communication and documentation device

Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide


Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 1
Chapter 6
The Relational Algebra and
Calculus

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe


Chapter Outline
◼ Relational Algebra
◼ Unary Relational Operations
◼ Relational Algebra Operations From Set Theory
◼ Binary Relational Operations
◼ Additional Relational Operations
◼ Examples of Queries in Relational Algebra
◼ Relational Calculus
◼ Tuple Relational Calculus
◼ Domain Relational Calculus
◼ Example Database Application (COMPANY)
◼ Overview of the QBE language (appendix D)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 3


Relational Algebra Overview

◼ Relational algebra is the basic set of operations


for the relational model
◼ These operations enable a user to specify basic
retrieval requests (or queries)
◼ The result of an operation is a new relation, which
may have been formed from one or more input
relations
◼ This property makes the algebra “closed” (all
objects in relational algebra are relations)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 4


Relational Algebra Overview (continued)

◼ The algebra operations thus produce new


relations
◼ These can be further manipulated using
operations of the same algebra
◼ A sequence of relational algebra operations
forms a relational algebra expression
◼ The result of a relational algebra expression is also a
relation that represents the result of a database
query (or retrieval request)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 5


Brief History of Origins of Algebra
◼ Muhammad ibn Musa al-Khwarizmi (800-847 CE) wrote a
book titled al-jabr about arithmetic of variables
◼ Book was translated into Latin.
◼ Its title (al-jabr) gave Algebra its name.
◼ Al-Khwarizmi called variables “shay”
◼ “Shay” is Arabic for “thing”.
◼ Spanish transliterated “shay” as “xay” (“x” was “sh” in Spain).
◼ In time this word was abbreviated as x.
◼ Where does the word Algorithm come from?
◼ Algorithm originates from “al-Khwarizmi"
◼ Reference: PBS (http://www.pbs.org/empires/islam/innoalgebra.html)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 6


Relational Algebra Overview
◼ Relational Algebra consists of several groups of operations
◼ Unary Relational Operations

◼ SELECT (symbol:  (sigma))


◼ PROJECT (symbol:  (pi))
◼ RENAME (symbol:  (rho))
◼ Relational Algebra Operations From Set Theory
◼ UNION (  ), INTERSECTION (  ), DIFFERENCE (or MINUS, – )
◼ CARTESIAN PRODUCT ( x )
◼ Binary Relational Operations
◼ JOIN (several variations of JOIN exist)
◼ DIVISION
◼ Additional Relational Operations
◼ OUTER JOINS, OUTER UNION
◼ AGGREGATE FUNCTIONS (These compute summary of
information: for example, SUM, COUNT, AVG, MIN, MAX)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 7


Database State for COMPANY
◼ All examples discussed below refer to the COMPANY database
shown here.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 8


Unary Relational Operations: SELECT
◼ The SELECT operation (denoted by  (sigma)) is used to select a
subset of the tuples from a relation based on a selection condition.
◼ The selection condition acts as a filter
◼ Keeps only those tuples that satisfy the qualifying condition
◼ Tuples satisfying the condition are selected whereas the
other tuples are discarded (filtered out)
◼ Examples:
◼ Select the EMPLOYEE tuples whose department number is 4:

 DNO = 4 (EMPLOYEE)
◼ Select the employee tuples whose salary is greater than $30,000:
 SALARY > 30,000 (EMPLOYEE)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 9


Unary Relational Operations: SELECT

◼ In general, the select operation is denoted by


 <selection condition>(R) where
◼ the symbol  (sigma) is used to denote the select
operator
◼ the selection condition is a Boolean (conditional)
expression specified on the attributes of relation R
◼ tuples that make the condition true are selected
◼ appear in the result of the operation
◼ tuples that make the condition false are filtered out
◼ discarded from the result of the operation

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 10


Unary Relational Operations: SELECT
(contd.)
◼ SELECT Operation Properties
◼ The SELECT operation  <selection condition>(R) produces a relation
S that has the same schema (same attributes) as R
◼ SELECT  is commutative:
◼ 
<condition1>( < condition2> (R)) =  <condition2> ( < condition1> (R))
◼ Because of commutativity property, a cascade (sequence) of
SELECT operations may be applied in any order:
◼ <cond1>(<cond2> (<cond3> (R)) = <cond2> (<cond3> (<cond1> ( R)))

◼ A cascade of SELECT operations may be replaced by a single


selection with a conjunction of all the conditions:
◼ <cond1>(< cond2> (<cond3>(R)) =  <cond1> AND < cond2> AND <

cond3>(R)))
◼ The number of tuples in the result of a SELECT is less than
(or equal to) the number of tuples in the input relation R

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 11


The following query results refer to this
database state

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 12


Unary Relational Operations: PROJECT
◼ PROJECT Operation is denoted by  (pi)
◼ This operation keeps certain columns (attributes)
from a relation and discards the other columns.
◼ PROJECT creates a vertical partitioning
◼ The list of specified columns (attributes) is kept in
each tuple
◼ The other attributes in each tuple are discarded
◼ Example: To list each employee’s first and last
name and salary, the following is used:
LNAME, FNAME,SALARY(EMPLOYEE)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 13


Unary Relational Operations: PROJECT
(cont.)

◼ The general form of the project operation is:


<attribute list>(R)
◼  (pi) is the symbol used to represent the project
operation
◼ <attribute list> is the desired list of attributes from
relation R.
◼ The project operation removes any duplicate
tuples
◼ This is because the result of the project operation
must be a set of tuples
◼ Mathematical sets do not allow duplicate elements.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 14


Unary Relational Operations: PROJECT
(contd.)

◼ PROJECT Operation Properties


◼ The number of tuples in the result of projection
<list>(R) is always less or equal to the number of
tuples in R
◼ If the list of attributes includes a key of R, then the

number of tuples in the result of PROJECT is equal


to the number of tuples in R
◼ PROJECT is not commutative
◼  <list1> ( <list2> (R) ) =  <list1> (R) as long as <list2>
contains the attributes in <list1>

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 15


Examples of applying SELECT and
PROJECT operations

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 16


Relational Algebra Expressions
◼ We may want to apply several relational algebra
operations one after the other
◼ Either we can write the operations as a single
relational algebra expression by nesting the
operations, or
◼ We can apply one operation at a time and create
intermediate result relations.
◼ In the latter case, we must give names to the
relations that hold the intermediate results.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 17


Single expression versus sequence of
relational operations (Example)
◼ To retrieve the first name, last name, and salary of all
employees who work in department number 5, we must
apply a select and a project operation
◼ We can write a single relational algebra expression as
follows:
◼ FNAME, LNAME, SALARY( DNO=5(EMPLOYEE))

◼ OR We can explicitly show the sequence of operations,


giving a name to each intermediate relation:
◼ DEP5_EMPS   DNO=5(EMPLOYEE)

◼ RESULT   FNAME, LNAME, SALARY (DEP5_EMPS)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 18


Unary Relational Operations: RENAME

◼ The RENAME operator is denoted by  (rho)


◼ In some cases, we may want to rename the
attributes of a relation or the relation name or
both
◼ Useful when a query requires multiple

operations
◼ Necessary in some cases (see JOIN operation

later)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 19


Unary Relational Operations: RENAME
(contd.)

◼ The general RENAME operation  can be


expressed by any of the following forms:
◼ S (B1, B2, …, Bn )(R) changes both:
◼ the relation name to S, and

◼ the column (attribute) names to B1, B1, …..Bn


◼ S(R) changes:
◼ the relation name only to S

◼ (B1, B2, …, Bn )(R) changes:


◼ the column (attribute) names only to B1, B1, …..Bn

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 20


Unary Relational Operations: RENAME
(contd.)

◼ For convenience, we also use a shorthand for


renaming attributes in an intermediate relation:
◼ If we write:
• RESULT   FNAME, LNAME, SALARY (DEP5_EMPS)
• RESULT will have the same attribute names as
DEP5_EMPS (same attributes as EMPLOYEE)
• If we write:
• RESULT (F, M, L, S, B, A, SX, SAL, SU, DNO)
 FNAME, LNAME, SALARY (DEP5_EMPS)
• The 10 attributes of DEP5_EMPS are renamed to
F, M, L, S, B, A, SX, SAL, SU, DNO, respectively

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 21


Example of applying multiple operations
and RENAME

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 22


Relational Algebra Operations from
Set Theory: UNION
◼ UNION Operation
◼ Binary operation, denoted by 
◼ The result of R  S, is a relation that includes all
tuples that are either in R or in S or in both R and
S
◼ Duplicate tuples are eliminated
◼ The two operand relations R and S must be “type
compatible” (or UNION compatible)
◼ R and S must have same number of attributes
◼ Each pair of corresponding attributes must be type
compatible (have same or compatible domains)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 23


Relational Algebra Operations from
Set Theory: UNION
◼ Example:
◼ To retrieve the social security numbers of all employees who
either work in department 5 (RESULT1 below) or directly
supervise an employee who works in department 5 (RESULT2
below)
◼ We can use the UNION operation as follows:
DEP5_EMPS  DNO=5 (EMPLOYEE)
RESULT1   SSN(DEP5_EMPS)
RESULT2(SSN)  SUPERSSN(DEP5_EMPS)
RESULT  RESULT1  RESULT2
◼ The union operation produces the tuples that are in either
RESULT1 or RESULT2 or both

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 24


Example of the result of a UNION
operation

◼ UNION Example

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 25


Relational Algebra Operations from
Set Theory
◼ Type Compatibility of operands is required for the binary
set operation UNION , (also for INTERSECTION , and
SET DIFFERENCE –, see next slides)
◼ R1(A1, A2, ..., An) and R2(B1, B2, ..., Bn) are type
compatible if:
◼ they have the same number of attributes, and
◼ the domains of corresponding attributes are type compatible
(i.e. dom(Ai)=dom(Bi) for i=1, 2, ..., n).
◼ The resulting relation for R1R2 (also for R1R2, or R1–
R2, see next slides) has the same attribute names as the
first operand relation R1 (by convention)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 26


Relational Algebra Operations from Set
Theory: INTERSECTION

◼ INTERSECTION is denoted by 
◼ The result of the operation R  S, is a
relation that includes all tuples that are in
both R and S
◼ The attribute names in the result will be the
same as the attribute names in R
◼ The two operand relations R and S must be
“type compatible”

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 27


Relational Algebra Operations from Set
Theory: SET DIFFERENCE (cont.)

◼ SET DIFFERENCE (also called MINUS or


EXCEPT) is denoted by –
◼ The result of R – S, is a relation that includes all
tuples that are in R but not in S
◼ The attribute names in the result will be the
same as the attribute names in R
◼ The two operand relations R and S must be
“type compatible”

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 28


Example to illustrate the result of UNION,
INTERSECT, and DIFFERENCE

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 29


Some properties of UNION, INTERSECT,
and DIFFERENCE
◼ Notice that both union and intersection are commutative
operations; that is
◼ R  S = S  R, and R  S = S  R
◼ Both union and intersection can be treated as n-ary
operations applicable to any number of relations as both
are associative operations; that is
◼ R  (S  T) = (R  S)  T
◼ (R  S)  T = R  (S  T)
◼ The minus operation is not commutative; that is, in
general
◼ R–S≠S–R

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 30


Relational Algebra Operations from Set
Theory: CARTESIAN PRODUCT
◼ CARTESIAN (or CROSS) PRODUCT Operation
◼ This operation is used to combine tuples from two relations
in a combinatorial fashion.
◼ Denoted by R(A1, A2, . . ., An) x S(B1, B2, . . ., Bm)
◼ Result is a relation Q with degree n + m attributes:
◼ Q(A1, A2, . . ., An, B1, B2, . . ., Bm), in that order.
◼ The resulting relation state has one tuple for each
combination of tuples—one from R and one from S.
◼ Hence, if R has nR tuples (denoted as |R| = nR ), and S has
nS tuples, then R x S will have nR * nS tuples.
◼ The two operands do NOT have to be "type compatible”

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 31


Relational Algebra Operations from Set
Theory: CARTESIAN PRODUCT (cont.)
◼ Generally, CROSS PRODUCT is not a
meaningful operation
◼ Can become meaningful when followed by other
operations
◼ Example (not meaningful):
◼ FEMALE_EMPS   SEX=’F’(EMPLOYEE)
◼ EMPNAMES   FNAME, LNAME, SSN (FEMALE_EMPS)
◼ EMP_DEPENDENTS  EMPNAMES x DEPENDENT
◼ EMP_DEPENDENTS will contain every combination of
EMPNAMES and DEPENDENT
◼ whether or not they are actually related

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 32


Relational Algebra Operations from Set
Theory: CARTESIAN PRODUCT (cont.)
◼ To keep only combinations where the
DEPENDENT is related to the EMPLOYEE, we
add a SELECT operation as follows
◼ Example (meaningful):
◼ FEMALE_EMPS   SEX=’F’(EMPLOYEE)
◼ EMPNAMES   FNAME, LNAME, SSN (FEMALE_EMPS)
◼ EMP_DEPENDENTS  EMPNAMES x DEPENDENT
◼ ACTUAL_DEPS   SSN=ESSN(EMP_DEPENDENTS)
◼ RESULT   FNAME, LNAME, DEPENDENT_NAME (ACTUAL_DEPS)
◼ RESULT will now contain the name of female employees
and their dependents

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 33


Example of applying CARTESIAN
PRODUCT

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 34


Binary Relational Operations: JOIN
◼ JOIN Operation (denoted by )
◼ The sequence of CARTESIAN PRODECT followed by
SELECT is used quite commonly to identify and select
related tuples from two relations
◼ A special operation, called JOIN combines this sequence
into a single operation
◼ This operation is very important for any relational database
with more than a single relation, because it allows us
combine related tuples from various relations
◼ The general form of a join operation on two relations R(A1,
A2, . . ., An) and S(B1, B2, . . ., Bm) is:
R <join condition>S
◼ where R and S can be any relations that result from general
relational algebra expressions.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 35


Binary Relational Operations: JOIN (cont.)
◼ Example: Suppose that we want to retrieve the name of the
manager of each department.
◼ To get the manager’s name, we need to combine each
DEPARTMENT tuple with the EMPLOYEE tuple whose SSN
value matches the MGRSSN value in the department tuple.
◼ We do this by using the join operation.

◼ DEPT_MGR  DEPARTMENT MGRSSN=SSN EMPLOYEE


◼ MGRSSN=SSN is the join condition
◼ Combines each department record with the employee who
manages the department
◼ The join condition can also be specified as
DEPARTMENT.MGRSSN= EMPLOYEE.SSN

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 36


Example of applying the JOIN operation

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 37


Some properties of JOIN
◼ Consider the following JOIN operation:
◼ R(A1, A2, . . ., An) S(B1, B2, . . ., Bm)
R.Ai=S.Bj
◼ Result is a relation Q with degree n + m attributes:
◼ Q(A1, A2, . . ., An, B1, B2, . . ., Bm), in that order.
◼ The resulting relation state has one tuple for each
combination of tuples—r from R and s from S, but only if
they satisfy the join condition r[Ai]=s[Bj]
◼ Hence, if R has nR tuples, and S has nS tuples, then the join
result will generally have less than nR * nS tuples.
◼ Only related tuples (based on the join condition) will appear
in the result

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 38


Some properties of JOIN
◼ The general case of JOIN operation is called a
Theta-join: R S
theta
◼ The join condition is called theta
◼ Theta can be any general boolean expression on
the attributes of R and S; for example:
◼ R.Ai<S.Bj AND (R.Ak=S.Bl OR R.Ap<S.Bq)
◼ Most join conditions involve one or more equality
conditions “AND”ed together; for example:
◼ R.Ai=S.Bj AND R.Ak=S.Bl AND R.Ap=S.Bq

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 39


Binary Relational Operations: EQUIJOIN
◼ EQUIJOIN Operation
◼ The most common use of join involves join
conditions with equality comparisons only
◼ Such a join, where the only comparison operator
used is =, is called an EQUIJOIN.
◼ In the result of an EQUIJOIN we always have one
or more pairs of attributes (whose names need not
be identical) that have identical values in every
tuple.
◼ The JOIN seen in the previous example was an
EQUIJOIN.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 40


Binary Relational Operations:
NATURAL JOIN Operation
◼ NATURAL JOIN Operation
◼ Another variation of JOIN called NATURAL JOIN —
denoted by * — was created to get rid of the second
(superfluous) attribute in an EQUIJOIN condition.
◼ because one of each pair of attributes with identical values is
superfluous
◼ The standard definition of natural join requires that the two
join attributes, or each pair of corresponding join attributes,
have the same name in both relations
◼ If this is not the case, a renaming operation is applied first.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 41


Binary Relational Operations
NATURAL JOIN (contd.)
◼ Example: To apply a natural join on the DNUMBER attributes of
DEPARTMENT and DEPT_LOCATIONS, it is sufficient to write:
◼ DEPT_LOCS  DEPARTMENT * DEPT_LOCATIONS
◼ Only attribute with the same name is DNUMBER
◼ An implicit join condition is created based on this attribute:
DEPARTMENT.DNUMBER=DEPT_LOCATIONS.DNUMBER

◼ Another example: Q  R(A,B,C,D) * S(C,D,E)


◼ The implicit join condition includes each pair of attributes with the
same name, “AND”ed together:
◼ R.C=S.C AND R.D.S.D
◼ Result keeps only one attribute of each such pair:
◼ Q(A,B,C,D,E)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 42


Example of NATURAL JOIN operation

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 43


Complete Set of Relational Operations

◼ The set of operations including SELECT ,


PROJECT  , UNION , DIFFERENCE - ,
RENAME , and CARTESIAN PRODUCT X is
called a complete set because any other
relational algebra expression can be expressed
by a combination of these five operations.
◼ For example:
◼ R  S = (R  S ) – ((R - S)  (S - R))
◼ R <join condition>S =  <join condition> (R X S)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 44


Binary Relational Operations: DIVISION
◼ DIVISION Operation
◼ The division operation is applied to two relations
◼ R(Z)  S(X), where X subset Z. Let Y = Z - X (and hence Z
= X  Y); that is, let Y be the set of attributes of R that are
not attributes of S.

◼ The result of DIVISION is a relation T(Y) that includes a


tuple t if tuples tR appear in R with tR [Y] = t, and with
◼ tR [X] = ts for every tuple ts in S.

◼ For a tuple t to appear in the result T of the DIVISION, the


values in t must appear in R in combination with every tuple
in S.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 45


Example of DIVISION

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 46


Recap of Relational Algebra Operations

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 47


Additional Relational Operations:
Aggregate Functions and Grouping
◼ A type of request that cannot be expressed in the basic
relational algebra is to specify mathematical aggregate
functions on collections of values from the database.
◼ Examples of such functions include retrieving the average
or total salary of all employees or the total number of
employee tuples.
◼ These functions are used in simple statistical queries that
summarize information from the database tuples.
◼ Common functions applied to collections of numeric
values include
◼ SUM, AVERAGE, MAXIMUM, and MINIMUM.
◼ The COUNT function is used for counting tuples or
values.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 48


Aggregate Function Operation
◼ Use of the Aggregate Functional operation ℱ
◼ ℱMAX Salary (EMPLOYEE) retrieves the maximum salary value
from the EMPLOYEE relation
◼ ℱMIN Salary (EMPLOYEE) retrieves the minimum Salary value
from the EMPLOYEE relation
◼ ℱSUM Salary (EMPLOYEE) retrieves the sum of the Salary
from the EMPLOYEE relation
◼ ℱCOUNT SSN, AVERAGE Salary (EMPLOYEE) computes the count
(number) of employees and their average salary
◼ Note: count just counts the number of rows, without removing
duplicates

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 49


Using Grouping with Aggregation
◼ The previous examples all summarized one or more
attributes for a set of tuples
◼ Maximum Salary or Count (number of) Ssn
◼ Grouping can be combined with Aggregate Functions
◼ Example: For each department, retrieve the DNO,
COUNT SSN, and AVERAGE SALARY
◼ A variation of aggregate operation ℱ allows this:
◼ Grouping attribute placed to left of symbol
◼ Aggregate functions to right of symbol
◼ DNO ℱCOUNT SSN, AVERAGE Salary (EMPLOYEE)
◼ Above operation groups employees by DNO (department
number) and computes the count of employees and
average salary per department

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 50


Examples of applying aggregate functions
and grouping

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 51


Illustrating aggregate functions and
grouping

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 52


Additional Relational Operations (cont.)
◼ Recursive Closure Operations
◼ Another type of operation that, in general,
cannot be specified in the basic original
relational algebra is recursive closure.
◼ This operation is applied to a recursive
relationship.
◼ An example of a recursive operation is to
retrieve all SUPERVISEES of an EMPLOYEE
e at all levels — that is, all EMPLOYEE e’
directly supervised by e; all employees e’’
directly supervised by each employee e’; all
employees e’’’ directly supervised by each
employee e’’; and so on.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 53
Additional Relational Operations (cont.)

◼ Although it is possible to retrieve employees at


each level and then take their union, we cannot,
in general, specify a query such as “retrieve the
supervisees of ‘James Borg’ at all levels” without
utilizing a looping mechanism.
◼ The SQL3 standard includes syntax for recursive
closure.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 54


Additional Relational Operations (cont.)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 55


Additional Relational Operations (cont.)
◼ The OUTER JOIN Operation
◼ In NATURAL JOIN and EQUIJOIN, tuples without a
matching (or related) tuple are eliminated from the join
result
◼ Tuples with null in the join attributes are also eliminated
◼ This amounts to loss of information.
◼ A set of operations, called OUTER joins, can be used when
we want to keep all the tuples in R, or all those in S, or all
those in both relations in the result of the join, regardless of
whether or not they have matching tuples in the other
relation.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 56


Additional Relational Operations (cont.)
◼ The left outer join operation keeps every tuple in
the first or left relation R in R S; if no matching
tuple is found in S, then the attributes of S in the
join result are filled or “padded” with null values.
◼ A similar operation, right outer join, keeps every
tuple in the second or right relation S in the result
of R S.
◼ A third operation, full outer join, denoted by
keeps all tuples in both the left and the right
relations when no matching tuples are found,
padding them with null values as needed.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 57


Additional Relational Operations (cont.)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 58


Additional Relational Operations (cont.)
◼ OUTER UNION Operations
◼ The outer union operation was developed to take
the union of tuples from two relations if the
relations are not type compatible.
◼ This operation will take the union of tuples in two
relations R(X, Y) and S(X, Z) that are partially
compatible, meaning that only some of their
attributes, say X, are type compatible.
◼ The attributes that are type compatible are
represented only once in the result, and those
attributes that are not type compatible from either
relation are also kept in the result relation T(X, Y,
Z).

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 59


Additional Relational Operations (cont.)
◼ Example: An outer union can be applied to two relations
whose schemas are STUDENT(Name, SSN, Department,
Advisor) and INSTRUCTOR(Name, SSN, Department,
Rank).
◼ Tuples from the two relations are matched based on having the
same combination of values of the shared attributes— Name,
SSN, Department.
◼ If a student is also an instructor, both Advisor and Rank will
have a value; otherwise, one of these two attributes will be null.
◼ The result relation STUDENT_OR_INSTRUCTOR will have the
following attributes:
STUDENT_OR_INSTRUCTOR (Name, SSN, Department,
Advisor, Rank)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 60


Examples of Queries in Relational
Algebra
◼ Q1: Retrieve the name and address of all employees who work for the
‘Research’ department.
RESEARCH_DEPT   DNAME=’Research’ (DEPARTMENT)
RESEARCH_EMPS  (RESEARCH_DEPT DNUMBER= DNOEMPLOYEE EMPLOYEE)
RESULT   FNAME, LNAME, ADDRESS (RESEARCH_EMPS)

◼ Q6: Retrieve the names of employees who have no dependents.


ALL_EMPS   SSN(EMPLOYEE)
EMPS_WITH_DEPS(SSN)   ESSN(DEPENDENT)
EMPS_WITHOUT_DEPS  (ALL_EMPS - EMPS_WITH_DEPS)
RESULT   LNAME, FNAME (EMPS_WITHOUT_DEPS * EMPLOYEE)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 61


Relational Calculus
◼ A relational calculus expression creates a new
relation, which is specified in terms of variables
that range over rows of the stored database
relations (in tuple calculus) or over columns of
the stored relations (in domain calculus).
◼ In a calculus expression, there is no order of
operations to specify how to retrieve the query
result—a calculus expression specifies only what
information the result should contain.
◼ This is the main distinguishing feature between
relational algebra and relational calculus.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 62


Relational Calculus

◼ Relational calculus is considered to be a


nonprocedural language.
◼ This differs from relational algebra, where we
must write a sequence of operations to specify a
retrieval request; hence relational algebra can be
considered as a procedural way of stating a
query.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 63


Tuple Relational Calculus
◼ The tuple relational calculus is based on specifying a
number of tuple variables.
◼ Each tuple variable usually ranges over a particular
database relation, meaning that the variable may take as
its value any individual tuple from that relation.
◼ A simple tuple relational calculus query is of the form
{t | COND(t)}
◼ where t is a tuple variable and COND (t) is a conditional
expression involving t.
◼ The result of such a query is the set of all tuples t that
satisfy COND (t).

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 64


Tuple Relational Calculus

◼ Example: To find the first and last names of all employees


whose salary is above $50,000, we can write the following
tuple calculus expression:
{t.FNAME, t.LNAME | EMPLOYEE(t) AND
t.SALARY>50000}
◼ The condition EMPLOYEE(t) specifies that the range
relation of tuple variable t is EMPLOYEE.
◼ The first and last name (PROJECTION FNAME, LNAME) of
each EMPLOYEE tuple t that satisfies the condition
t.SALARY>50000 (SELECTION  SALARY >50000) will be
retrieved.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 65


The Existential and Universal Quantifiers
◼ Two special symbols called quantifiers can appear in
formulas; these are the universal quantifier () and the
existential quantifier ().
◼ Informally, a tuple variable t is bound if it is quantified,
meaning that it appears in an ( t) or ( t) clause;
otherwise, it is free.
◼ If F is a formula, then so are ( t)(F) and ( t)(F), where t
is a tuple variable.
◼ The formula ( t)(F) is true if the formula F evaluates to true
for some (at least one) tuple assigned to free occurrences
of t in F; otherwise ( t)(F) is false.
◼ The formula ( t)(F) is true if the formula F evaluates to
true for every tuple (in the universe) assigned to free
occurrences of t in F; otherwise ( t)(F) is false.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 66


The Existential and Universal Quantifiers

◼  is called the universal or “for all” quantifier


because every tuple in “the universe of” tuples
must make F true to make the quantified formula
true.
◼  is called the existential or “there exists”
quantifier because any tuple that exists in “the
universe of” tuples may make F true to make the
quantified formula true.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 67


Example Query Using Existential
Quantifier
◼ Retrieve the name and address of all employees who work for the
‘Research’ department. The query can be expressed as :
{t.FNAME, t.LNAME, t.ADDRESS | EMPLOYEE(t) and ( d)
(DEPARTMENT(d) and d.DNAME=‘Research’ and
d.DNUMBER=t.DNO) }
◼ The only free tuple variables in a relational calculus expression
should be those that appear to the left of the bar ( | ).
◼ In above query, t is the only free variable; it is then bound
successively to each tuple.
◼ If a tuple satisfies the conditions specified in the query, the attributes
FNAME, LNAME, and ADDRESS are retrieved for each such tuple.
◼ The conditions EMPLOYEE (t) and DEPARTMENT(d) specify the
range relations for t and d.
◼ The condition d.DNAME = ‘Research’ is a selection condition and
corresponds to a SELECT operation in the relational algebra,
whereas the condition d.DNUMBER = t.DNO is a JOIN condition.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 68


Example Query Using Universal
Quantifier
◼ Find the names of employees who work on all the projects controlled by
department number 5. The query can be:
{e.LNAME, e.FNAME | EMPLOYEE(e) and ( ( x)(not(PROJECT(x)) or
not(x.DNUM=5)
OR ( ( w)(WORKS_ON(w) and w.ESSN=e.SSN and x.PNUMBER=w.PNO))))}
◼ Exclude from the universal quantification all tuples that we are not interested
in by making the condition true for all such tuples.
◼ The first tuples to exclude (by making them evaluate automatically to true) are
those that are not in the relation R of interest.
◼ In query above, using the expression not(PROJECT(x)) inside the universally
quantified formula evaluates to true all tuples x that are not in the PROJECT
relation.
◼ Then we exclude the tuples we are not interested in from R itself. The
expression not(x.DNUM=5) evaluates to true all tuples x that are in the project
relation but are not controlled by department 5.
◼ Finally, we specify a condition that must hold on all the remaining tuples in R.
( ( w)(WORKS_ON(w) and w.ESSN=e.SSN and x.PNUMBER=w.PNO)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 69


Languages Based on Tuple Relational
Calculus
◼ The language SQL is based on tuple calculus. It uses the
basic block structure to express the queries in tuple
calculus:
◼ SELECT <list of attributes>
◼ FROM <list of relations>
◼ WHERE <conditions>
◼ SELECT clause mentions the attributes being projected,
the FROM clause mentions the relations needed in the
query, and the WHERE clause mentions the selection as
well as the join conditions.
◼ SQL syntax is expanded further to accommodate other
operations. (See Chapter 8).

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 70


Languages Based on Tuple Relational
Calculus

◼ Another language which is based on tuple


calculus is QUEL which actually uses the range
variables as in tuple calculus. Its syntax includes:
◼ RANGE OF <variable name> IS <relation name>
◼ Then it uses
◼ RETRIEVE <list of attributes from range variables>
◼ WHERE <conditions>
◼ This language was proposed in the relational
DBMS INGRES.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 71


The Domain Relational Calculus
◼ Another variation of relational calculus called the domain relational
calculus, or simply, domain calculus is equivalent to tuple calculus
and to relational algebra.
◼ The language called QBE (Query-By-Example) that is related to
domain calculus was developed almost concurrently to SQL at IBM
Research, Yorktown Heights, New York.
◼ Domain calculus was thought of as a way to explain what QBE
does.
◼ Domain calculus differs from tuple calculus in the type of variables
used in formulas:
◼ Rather than having variables range over tuples, the variables
range over single values from domains of attributes.
◼ To form a relation of degree n for a query result, we must have n of
these domain variables— one for each attribute.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 72


The Domain Relational Calculus

◼ An expression of the domain calculus is of the


form
{ x1, x2, . . ., xn |
COND(x1, x2, . . ., xn, xn+1, xn+2, . . ., xn+m)}
◼ where x1, x2, . . ., xn, xn+1, xn+2, . . ., xn+m are
domain variables that range over domains (of
attributes)
◼ and COND is a condition or formula of the domain
relational calculus.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 73


Example Query Using Domain Calculus
◼ Retrieve the birthdate and address of the employee whose name is
‘John B. Smith’.
◼ Query :
{uv | ( q) ( r) ( s) ( t) ( w) ( x) ( y) ( z)
(EMPLOYEE(qrstuvwxyz) and q=’John’ and r=’B’ and s=’Smith’)}
◼ Ten variables for the employee relation are needed, one to range
over the domain of each attribute in order.
◼ Of the ten variables q, r, s, . . ., z, only u and v are free.

◼ Specify the requested attributes, BDATE and ADDRESS, by the free


domain variables u for BDATE and v for ADDRESS.
◼ Specify the condition for selecting a tuple following the bar ( | )—
◼ namely, that the sequence of values assigned to the variables
qrstuvwxyz be a tuple of the employee relation and that the values
for q (FNAME), r (MINIT), and s (LNAME) be ‘John’, ‘B’, and
‘Smith’, respectively.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 74


QBE: A Query Language Based on
Domain Calculus (Appendix C)
◼ This language is based on the idea of giving an example
of a query using example elements.
◼ An example element stands for a domain variable and is
specified as an example value preceded by the
underscore character.
◼ P. (called P dot) operator (for “print”) is placed in those
columns which are requested for the result of the query.
◼ A user may initially start giving actual values as examples,
but later can get used to providing a minimum number of
variables as example elements.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 75


QBE: A Query Language Based on
Domain Calculus (Appendix C)
◼ The language is very user-friendly, because it
uses minimal syntax.
◼ QBE was fully developed further with facilities for
grouping, aggregation, updating etc. and is
shown to be equivalent to SQL.
◼ The language is available under QMF (Query
Management Facility) of DB2 of IBM and has
been used in various ways by other products like
ACCESS of Microsoft, PARADOX.
◼ For details, see Appendix C in the text.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 76


QBE Examples

◼ QBE initially presents a relational schema as a


“blank schema” in which the user fills in the query
as an example:

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 77


QBE Examples
◼ The following domain calculus query can be successively
minimized by the user as shown:
◼ Query :

{uv | ( q) ( r) ( s) ( t) ( w) ( x) ( y) ( z)
(EMPLOYEE(qrstuvwxyz) and q=‘John’ and r=‘B’ and
s=‘Smith’)}

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 78


QBE Examples

◼ Specifying complex conditions in QBE:


◼ A technique called the “condition box” is used in
QBE to state more involved Boolean expressions
as conditions.
◼ The C.4(a) gives employees who work on either
project 1 or 2, whereas the query in C.4(b) gives
those who work on both the projects.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 79


QBE Examples

◼ Illustrating join in QBE. The join is simple


accomplished by using the same example
element in the columns being joined. Note that
the Result is set us as an independent table.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 80


Chapter Summary
◼ Relational Algebra
◼ Unary Relational Operations
◼ Relational Algebra Operations From Set Theory
◼ Binary Relational Operations
◼ Additional Relational Operations
◼ Examples of Queries in Relational Algebra
◼ Relational Calculus
◼ Tuple Relational Calculus
◼ Domain Relational Calculus
◼ Overview of the QBE language (appendix C)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6- 81


CHAPTER 5 - SQL
SQL– Slide 1
INTRODUCTION

▪ SQL - Structured Query Language


▪ SQL is used for:
• Creating databases
• Adding, modifying and deleting database structures
• Inserting, deleting, and modifying records in databases
• Querying databases (data retrieval)
▪ SQL functions as a standard relational database language
• It can be used (with minor dialectical variations) with the majority of
relational DBMS software tools

SQL– Slide 2
Database Systems - FET- JIH 2
INTRODUCTION

▪ SQL commands – categories:


• Data Definition Language (DDL)
• Data Manipulation Language (DML)
• Data Control Language (DCL)
• Transaction Control Language (TCL)

SQL– Slide 3
Database Systems - FET- JIH 3
INTRODUCTION

▪ Data Definition Language (DDL)


• Used to create and modify the structure of the database
• Example commands:
CREATE
ALTER
DROP

SQL– Slide 4
Database Systems - FET- JIH 4
INTRODUCTION

▪ Data Manipulation Language (DML)


• Used to insert, modify, delete and retrieve data
• Example commands:
INSERT INTO
UPDATE
DELETE
SELECT

SQL– Slide 5
Database Systems - FET- JIH 5
INTRODUCTION

▪ Data Control Language (DCL)


• Used for data access control
▪ Transaction Control Language (TCL)
• Used for managing database transactions

SQL– Slide 6
Database Systems - FET- JIH 6
INTRODUCTION

▪ SQL data types


• Each column of each SQL created relation has a specified data type
• Commonly used SQL data types:
• Numeric (10,3)→ XXXXXXX.YYY

SQL– Slide 7
Database Systems - FET- JIH 7
INTRODUCTION

▪ Brief SQL syntax notes


• Semicolon “;” following the end of an SQL statement, indicates the end
of the SQL command
o In a list of multiple SQL statements the semicolon indicates where each SQL
statement ends
• SQL keywords, as well as the table and column names used in the SQL
commands, are not case sensitive
o E.g. SELECT is the same as select or SeLeCt
• An SQL statement can be written as one long sentence in one line of text
o However, for legibility reasons SQL statements are usually broken down into

multiple lines of text

SQL– Slide 8
Database Systems - FET- JIH 8
CREATE TABLE

▪ CREATE TABLE
• Used for creating and connecting relational tables

SQL– Slide 9
Database Systems - FET- JIH 9
CREATE TABLE SYNTAX
CREATE TABLE schema_name.table_name
(
column_1 data_type column_constraint,
column_2 data_type column_constraint,
...
table_constraint
);

Chapter 5 – Slide SQL– Slide 10


▪ First, specify the table name and schema name to which the
new table belongs on the CREATE TABLE clause.
▪ Second, list all columns of the table within the parentheses. In
case a table has multiple columns, you need to separate them
by commas (,).
▪ A column definition includes the column name followed by its
data type e.g., NUMBER, VARCHAR2, and a column constraint
such as NOT NULL, primary key, check.
▪ Third, add table constraints if applicable e.g., primary key,
foreign key, check.

SQL– Slide 11
Chapter 5 – Slide
ORACLE CREATE TABLE STATEMENT EXAMPLE
▪ The following example shows how to create a new table named
persons in the ot schema:

CREATE TABLE ot.persons(


person_id NUMBER GENERATED BY DEFAULT AS IDENTITY,
first_name VARCHAR2(50) NOT NULL,
last_name VARCHAR2(50) NOT NULL,
PRIMARY KEY(person_id)
);

The person_id is the identity column that identifies unique rows in the
table. The data type of the person_id column is NUMBER. The clause
GENERATED BY DEFAULT AS IDENTITYinstructs Oracle to generate a new
integer for the column whenever a new row is inserted into the table.

SQL– Slide 12
ER diagram : ZAGI Retail Company Sales Department Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 13
Relational schema: ZAGI Retail Company Sales Department Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 14
CREATE TABLE statements for ZAGI Retail Company Sales Department Database
CREATE TABLE vendor
( vendorid CHAR(2) NOT NULL,
vendorname VARCHAR(25) NOT NULL,
PRIMARY KEY (vendorid) );

CREATE TABLE category


( categoryid CHAR(2) NOT NULL,
categoryname VARCHAR(25) NOT NULL,
PRIMARY KEY (categoryid) );

CREATE TABLE product


( productid CHAR(3) NOT NULL,
productname VARCHAR(25) NOT NULL,
productprice NUMERIC(7,2) NOT NULL,
vendorid CHAR(2) NOT NULL,
categoryid CHAR(2) NOT NULL,
PRIMARY KEY (productid),
FOREIGN KEY (vendorid) REFERENCES vendor(vendorid),
FOREIGN KEY (categoryid) REFERENCES category(categoryid) );

CREATE TABLE region


( regionid CHAR(1) NOT NULL,
regionname VARCHAR(25) NOT NULL,
PRIMARY KEY (regionid) );

CREATE TABLE store


( storeid VARCHAR(3) NOT NULL,
storezip CHAR(5) NOT NULL,
regionid CHAR(1) NOT NULL,
PRIMARY KEY (storeid),
FOREIGN KEY (regionid) REFERENCES region(regionid) );
Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 15
CREATE TABLE statements for ZAGI Retail Company Sales Department Database

CREATE TABLE customer


( customerid CHAR(7) NOT NULL,
customername VARCHAR(15) NOT NULL,
customerzip CHAR(5) NOT NULL,
PRIMARY KEY (customerid) );

CREATE TABLE salestransaction


( tid VARCHAR(8) NOT NULL,
customerid CHAR(7) NOT NULL,
storeid VARCHAR(3) NOT NULL,
tdate DATE NOT NULL,
PRIMARY KEY (tid),
FOREIGN KEY (customerid) REFERENCES customer(customerid),
FOREIGN KEY (storeid) REFERENCES store(storeid) );

CREATE TABLE includes


( productid CHAR(3) NOT NULL,
tid VARCHAR(8) NOT NULL,
quantity INT NOT NULL,
PRIMARY KEY (productid, tid),
FOREIGN KEY (productid) REFERENCES product(productid),
FOREIGN KEY (tid) REFERENCES salestransaction(tid) );

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 16
ER diagram : ZAGI Retail Company Sales Department Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 17
CREATE TABLE statements for ZAGI Retail Company Sales Department Database
CREATE TABLE vendor
( vendorid CHAR(2) NOT NULL,
vendorname VARCHAR(25) NOT NULL,
PRIMARY KEY (vendorid) );

CREATE TABLE category


( categoryid CHAR(2) NOT NULL,
categoryname VARCHAR(25) NOT NULL,
PRIMARY KEY (categoryid) );

CREATE TABLE region


( regionid CHAR(1) NOT NULL,
regionname VARCHAR(25) NOT NULL,
PRIMARY KEY (regionid) );

CREATE TABLE customer


( customerid CHAR(7) NOT NULL,
customername VARCHAR(15) NOT NULL,
customerzip CHAR(5) NOT NULL,
PRIMARY KEY (customerid) );

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 18
Chapter 5 – Slide SQL– Slide 19
CREATE TABLE statements for ZAGI Retail Company Sales Department Database
CREATE TABLE product
( productid CHAR(3) NOT NULL,
productname VARCHAR(25) NOT NULL,
productprice NUMERIC(7,2) NOT NULL,
vendorid CHAR(2) NOT NULL,
categoryid CHAR(2) NOT NULL,
PRIMARY KEY (productid),
FOREIGN KEY (vendorid) REFERENCES vendor(vendorid),
FOREIGN KEY (categoryid) REFERENCES category(categoryid) );
CREATE TABLE salestransaction
( tid VARCHAR(8) NOT NULL,
customerid CHAR(7) NOT NULL,
storeid VARCHAR(3) NOT NULL,
tdate DATE NOT NULL,
PRIMARY KEY (tid),
FOREIGN KEY (customerid) REFERENCES customer(customerid),
FOREIGN KEY (storeid) REFERENCES store(storeid) );

CREATE TABLE includes


( productid CHAR(3) NOT NULL,
tid VARCHAR(8) NOT NULL,
quantity INT NOT NULL,
PRIMARY KEY (productid, tid),
FOREIGN KEY (productid) REFERENCES product(productid),
FOREIGN KEY (tid) REFERENCES salestransaction(tid) );

CREATE TABLE store


( storeid VARCHAR(3) NOT NULL,
storezip CHAR(5) NOT NULL,
regionid CHAR(1) NOT NULL,
PRIMARY KEY (storeid),
FOREIGN KEY (regionid) REFERENCES region(regionid) );
Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 20
Defining Constraints

– Column-level constraint:
CREATE TABLE employees(
employee_id NUMBER(6)
CONSTRAINT emp_emp_id_pk PRIMARY KEY, 1
first_name VARCHAR2(20),
...);
– Table-level constraint:
CREATE TABLE employees(
employee_id NUMBER(6),
first_name VARCHAR2(20),
...
job_id VARCHAR2(10) NOT NULL,
2
CONSTRAINT emp_emp_id_pk
PRIMARY KEY (EMPLOYEE_ID));
DROP TABLE

▪ DROP TABLE
• Used to remove a table from the database

SQL– Slide 22
Database Systems - FET- JIH 22
DROP TABLE statements for ZAGI Retail Company Sales Department Database

INVALID SEQUENCE
DROP TABLE region;
DROP TABLE store;
DROP TABLE salestransaction;
DROP TABLE product;
DROP TABLE vendor;
DROP TABLE category;
DROP TABLE customer;
DROP TABLE includes;

VALID SEQUENCE
DROP TABLE includes;
DROP TABLE salestransaction;
DROP TABLE store;
DROP TABLE product;
DROP TABLE vendor;
DROP TABLE region;
DROP TABLE category;
DROP TABLE customer;

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 23
INSERT INTO

▪ INSERT INTO
• Used to populate the created relations with data

SQL– Slide 24
Database Systems - FET- JIH 24
INSERT STATEMENT SYNTAX

• Add new rows to a table by using the INSERT statement:

INSERT INTO table [(column [, column...])]


VALUES (value [, value...]);

• With this syntax, only one row is inserted at a time.


• You can add new rows to a table by issuing the INSERT statement.
• In the syntax:
table is the name of the table
column is the name of the column in the table to populate
value is the corresponding value for the column
• Note: This statement with the VALUES clause adds only one row at a
time to a table.

SQL– Slide 25
INSERTING NEW ROWS

• Insert a new row containing values for each column.


• List values in the default order of the columns in the table.
• Optionally, list the columns in the INSERT clause.
INSERT INTO departments(department_id,
department_name, manager_id, location_id)
VALUES (70, 'Public Relations', 100, 1700);
1 row created.
• Enclose character and date values in single quotation
marks.

SQL– Slide 26
INSERTING ROWS WITH NULL VALUES

• Implicit method: Omit the column from the


column list.
INSERT INTO departments (department_id,
department_name )
VALUES (30, 'Purchasing');
1 row created.

• Explicit method: Specify the NULL keyword in the


VALUES clause.
INSERT INTO departments
VALUES (100, 'Finance', NULL, NULL);
1 row created.

SQL– Slide 27
INSERTING SPECIAL VALUES

The SYSDATE function records the current date and time.

INSERT INTO employees (employee_id,


first_name, last_name,
email, phone_number,
hire_date, job_id, salary,
commission_pct, manager_id,
department_id)
VALUES (113,
'Louis', 'Popp',
'LPOPP', '515.124.4567',
SYSDATE, 'AC_ACCOUNT', 6900,
NULL, 205, 100);
1 row created.

SQL– Slide 28
INSERTING SPECIFIC DATE VALUES

• Add a new employee DD-MON-YY.


INSERT INTO employees
VALUES (114,
'Den', 'Raphealy',
'DRAPHEAL', '515.127.4561',
TO_DATE('FEB 3, 1999', 'MON DD, YYYY'),
'AC_ACCOUNT', 11000, NULL, 100, 30);
1 row created.
• Verify your addition.

SQL– Slide 29
ER diagram: HAFH Realty Company Property Management Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 30
Relational schema: HAFH Realty Company Property Management Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 31
Data records: ZAGI Retail Company Sales Department Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 32
INSERT INTO vendor VALUES ('PG','Pacifica Gear');
INSERT INTO INSERT INTO vendor VALUES ('MK','Mountain King');
statements INSERT INTO category VALUES ('CP','Camping');
INSERT INTO category VALUES ('FW','Footwear');
for ZAGI Retail INSERT INTO product VALUES ('1X1','Zzz Bag',100,'PG','CP');
Company INSERT INTO product VALUES ('2X2','Easy Boot',70,'MK','FW');
Sales INSERT INTO product VALUES ('3X3','Cosy Sock',15,'MK','FW');
INSERT INTO product VALUES ('4X4','Dura Boot',90,'PG','FW');
Department INSERT INTO product VALUES ('5X5','Tiny Tent',150,'MK','CP');
Database INSERT INTO product VALUES ('6X6','Biggy Tent',250,'MK','CP');
INSERT INTO region VALUES ('C','Chicagoland');
INSERT INTO region VALUES ('T','Tristate');
INSERT INTO store VALUES ('S1','60600','C');
INSERT INTO store VALUES ('S2','60605','C');
INSERT INTO store VALUES ('S3','35400','T’);
INSERT INTO customer VALUES ('1-2-333','Tina','60137');
INSERT INTO customer VALUES ('2-3-444','Tony','60611');
INSERT INTO customer VALUES ('3-4-555','Pam','35401’);
INSERT INTO salestransaction VALUES ('T111','1-2-333','S1','01/Jan/2020');
INSERT INTO salestransaction VALUES ('T222','2-3-444','S2','01/Jan/2020');
INSERT INTO salestransaction VALUES ('T333','1-2-333','S3','02/Jan/2020');
INSERT INTO salestransaction VALUES ('T444','3-4-555','S3','02/Jan/2020');
INSERT INTO salestransaction VALUES ('T555','2-3-444','S3','02/Jan/2020');
INSERT INTO includes VALUES ('1X1','T111',1);
INSERT INTO includes VALUES ('2X2','T222',1);
INSERT INTO includes VALUES ('3X3','T333',5);
INSERT INTO includes VALUES ('1X1','T333',1);
INSERT INTO includes VALUES ('4X4','T444',1);
INSERT INTO includes VALUES ('2X2','T444',2);
INSERT INTO includes VALUES ('4X4','T555',4);
INSERT INTO includes VALUES ('5X5','T555',2);
INSERT INTO includes VALUES ('6X6','T555',1);
Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 33
CREATE TABLE statements for HAFH Realty Company Property Management Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 34
CREATE TABLE statements for HAFH Realty Company Property Management Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 35
Data records: HAFH Realty Company Property Management Database (part 1)

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 36
INSERT INTO statements for HAFH Realty Company Property Management Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 37
INSERT INTO statements for HAFH Realty Company Property Management Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 38
ALTER TABLE
▪ ALTER TABLE
• Used to change the structure of the relation, once the relation is already
created
▪ ALTER TABLE - ADD COLUMN
• ALTER TABLE table_name
ADD column_name datatype;
▪ Example
▪ ALTER TABLE Customers
ADD Email varchar(255);
▪ ALTER TABLE - DROP COLUMN
▪ ALTER TABLE table_name
DROP COLUMN column_name;
▪ Example
▪ ALTER TABLE Customers
DROP COLUMN Email;

SQL– Slide 39
39
Database Systems - FET- JIH
ALTER TABLE
▪ ALTER TABLE - ALTER/MODIFY COLUMN
▪ ALTER TABLE table_name
MODIFY column_name datatype;

▪ ALTER TABLE Persons


ADD DateOfBirth date;

SQL– Slide 40
Database Systems - FET- JIH
▪ Change Data Type Example
▪ ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;
▪ DROP COLUMN Example
▪ ALTER TABLE Persons
DROP COLUMN DateOfBirth;

SQL– Slide 41
ALTER TABLE
Alter Statement 1: ALTER TABLE vendor
ADD ( vendorphonenumber CHAR(12));

Alter Statement 2: ALTER TABLE vendor


DROP ( vendorphonenumber);

SQL– Slide 42
Database Systems - FET- JIH 42
UPDATE

▪ UPDATE
• Used to modify the data stored in database relations

SQL– Slide 43
Database Systems - FET- JIH 43
Data records: ZAGI Retail Company Sales Department Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 44
UPDATE
Insert Statement 1:
INSERT INTO product VALUES ('7×7','Airy Sock',1000,'MK','CP');

Update Statement 1: UPDATE product


SET productprice = 10
WHERE productid = '7×7';

Alter Statement 3: ALTER TABLE product ADD


(discount NUMERIC(3,2) );

Update Statement 2: UPDATE product


SET discount = 0.2;

Update Statement 3: UPDATE product


SET discount = 0.3
WHERE vendorid = 'MK';

Alter Statement 4: ALTER TABLE product DROP (discount);


SQL– Slide 45
Database Systems - FET- JIH 45
EXAMPLE
▪ UPDATE CUSTOMERS SET
ADDRESS = 'Pune'
WHERE ID = 6;

SQL– Slide 46
CONSTRAINT MANAGEMENT
Alter Statement 5: ALTER TABLE manager
ADD CONSTRAINT fkresidesin
FOREIGN KEY (mresbuildingid)
REFERENCES building (buildingid);

Update Statement 4: UPDATE manager


SET mresbuildingid = 'B1'
WHERE managerid = 'M12';

Update Statement 5: UPDATE manager


SET mresbuildingid = 'B2'
WHERE managerid = 'M23';

Update Statement 6: UPDATE manager


SET mresbuildingid = 'B4'
WHERE managerid = 'M34';

Alter Statement 6: ALTER TABLE manager


MODIFY (mresbuildingid NOT NULL);
SQL– Slide 47
Database Systems - FET- JIH 47
Data records: HAFH Realty Company Property Management Database (part 1)

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 48
CONSTRAINT MANAGEMENT
DROP TABLE sequence HAFH database—First seven tables:
DROP TABLE cleaning;
DROP TABLE staffmember;
DROP TABLE apartment;
DROP TABLE corpclient;
DROP TABLE inspecting;
DROP TABLE inspector;
DROP TABLE managerphone;

Alter Statement 7: ALTER TABLE manager


DROP CONSTRAINT fkresidesin;

DROP TABLE sequence HAFH database—Last two tables:


DROP TABLE building;
DROP TABLE manager;

SQL– Slide 49
Database Systems - FET- JIH 49
DELETE

▪ DELETE
• Used to delete the data stored in database relations

SQL– Slide 50
Database Systems - FET- JIH 50
DELETE
Delete Statement 1: DELETE FROM product
WHERE productid = '7×7';

SQL– Slide 51
Database Systems - FET- JIH 51
RUN ORACLE SQL*PLUS SCRIPT FROM COMMAND
LINE IN WINDOWS
▪ Example
▪ To run the SQL script, follow these steps:

❖ Open the command prompt by pressing the key Window+R and


then type CMD in the Run window and press enter.
❖ In the Windows command prompt, change the directory where your
SQL script exists, for example, CD F:\mysqlscripts and press enter.
❖ In your scripts folder, type the following command to run the SQL
script:
• sqlplus username/psw@orcl
• Sqlplus> @your_script.sql

SQL– Slide 52
Data records: ZAGI Retail Company Sales Department Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 53
SELECT

▪ SELECT
• Used for the retrieval of data from the database relations
• Most commonly issued SQL statement
• Basic form:
SELECT <columns>
FROM <table>

SQL– Slide 54
Database Systems - FET- JIH 54
SELECT

Query 1 text: Retrieve the entire contents of the relation PRODUCT

Query 1: SELECT productid, productname, productprice,


vendorid, categoryid
FROM product;

Query 1 result:

SQL– Slide 55
Database Systems - FET- JIH 55
SELECT

Query 1 text: Retrieve the entire contents of the relation PRODUCT

Query 1a: SELECT *


FROM product;

Query 1a result:

SQL– Slide 56
Database Systems - FET- JIH 56
SELECT
Query 2 text: Retrieve the entire contents of the relation PRODUCT and
show the columns in the following order: ProductName,
ProductID, VendorID, CategoryID, ProductPrice

Query 2: SELECT productname, productid, vendorid,


categoryid, productprice
FROM product;

Query 2 result:

SQL– Slide 57
Database Systems - FET- JIH 57
SELECT

Query 3 text: For the relation PRODUCT, show the columns ProductID and
ProductPrice

Query 3: SELECT productid, productprice


FROM product;

Query 3 result:

SQL– Slide 58
Database Systems - FET- JIH 58
SELECT

▪ SELECT
• In addition to displaying columns, the SELECT clause can be used to
display derived attributes (calculated columns) represented as
expressions
• SELECT statement can be structured as follows:
SELECT <columns, expressions>
FROM <table>

SQL– Slide 59
Database Systems - FET- JIH 59
SELECT

Query 3a text: For the relation PRODUCT, show the columns ProductID and
ProductPrice and a column showing ProductPrice increased by
10%

Query 3a: SELECT productid, productprice, productprice * 1.1


‘New Price’
FROM product;

Query 3a result:

SQL– Slide 60
Database Systems - FET- JIH 60
SELECT

▪ SELECT
• The SELECT FROM statement can contain other optional keywords, such
as WHERE, GROUP BY, HAVING, and ORDER BY, appearing in this order: :
SELECT <columns, expressions>
FROM <tables>
WHERE <row selection condition>
GROUP BY <grouping columns>
HAVING <group selection condition>
ORDER BY <sorting columns, expressions>

SQL– Slide 61
Database Systems - FET- JIH 61
WHERE
WHERE
• WHERE condition determines which Operator Meaning
rows should be retrieved and = Equal to
consequently which rows should not be
> Greater than
retrieved
• The logical condition determining >= Greater than or equal to
which records to retrieve can use one < Less than
of the following logical comparison <= Less than or equal to
operators:
!= or <> Not equal to
= Equal to
< Less than BETWEEN Between two values
> Greater than ...AND.. (inclusive)
<= Less than or equal to .
>= Greater than or equal IN(set) Match any of a list of
to values
!= Not equal to
<> Not equal to LIKE Match a character pattern
(alternative notation) IS NULL Is a null value
SQL– Slide 62
Database Systems - FET- JIH 62
LOGICAL CONDITIONS

Operator Meaning
AND Returns TRUE if both component
conditions are true

OR Returns TRUE if either component


condition is true

NOT Returns TRUE if the following


condition is false

Chapter 5 – Slide SQL– Slide 63


RULES OF PRECEDENCE

Operator Meaning
1 Arithmetic operators
2 Concatenation operator
3 Comparison conditions
4 IS [NOT] NULL, LIKE, [NOT] IN
5 [NOT] BETWEEN
6 Not equal to
7 NOT logical condition
8 AND logical condition
9 OR logical condition

You can use parentheses to override rules of precedence.

Chapter 5 – Slide SQL– Slide 64


WHERE
Query 4 text: Retrieve the product ID, product name, vendor ID, and
product price for each product whose price is above $100

Query 4: SELECT productid, productname, vendorid,


productprice
FROM product
WHERE productprice > 100;

• Character strings and date values are enclosed in single quotation marks.
• Character values are case sensitive, and date values are format sensitive.
• The default date format is DD-MON-RR

Query 4 result:

SQL– Slide 65
Database Systems - FET- JIH 65
WHERE

Query 5 text: Retrieve the product ID, product name, vendor ID, and
product price for each product in the FW category whose price
is equal to or below $110

Query 5: SELECT productid, productname, vendorid,


productprice
FROM product
WHERE productprice <= 110 AND
categoryid = 'FW';

Query 5 result:

SQL– Slide 66
Database Systems - FET- JIH 66
DISTINCT

▪ DISTINCT
• Can be used in conjunction with the SELECT statement
• Eliminates duplicate values from a query result

SQL– Slide 67
Database Systems - FET- JIH 67
DISTINCT

Query 6 text: Retrieve the VendorID value for each record in the relation
PRODUCT

Query 6: SELECT vendorid


FROM product;

Query 6 result:

SQL– Slide 68
Database Systems - FET- JIH 68
DISTINCT

Query 7 text: Show one instance of all the different VendorID values in the
relation PRODUCT

Query 7: SELECT DISTINCT vendorid


FROM product;

Query 7 result:

SQL– Slide 69
Database Systems - FET- JIH 69
ORDER BY

▪ ORDER BY
• Used to sort the results of the query by one or more columns (or
expressions)
• Sort retrieved rows with the ORDER BY clause:
o ASC: ascending order, default
o DESC: descending order
• The ORDER BY clause comes last in the SELECT

SQL– Slide 70
Database Systems - FET- JIH 70
ORDER BY

Query 8 text: Retrieve the product ID, product name, category ID, and
product price for each product in the FW product category,
sorted by product price

Query 8: SELECT productid, productname, categoryid,


productprice
FROM product
WHERE categoryid = 'FW'
ORDER BY productprice;

Query 8 result:

SQL– Slide 71
Database Systems - FET- JIH 71
ORDER BY

Query 9 text: Retrieve the product ID, product name, category ID, and
product price for each product in the FW product category,
sorted by product price in descending order

Query 9: SELECT productid, productname, categoryid,


productprice
FROM product
WHERE categoryid = 'FW'
ORDER BY productprice DESC;

Query 9 result:

SQL– Slide 72
Database Systems - FET- JIH 72
ORDER BY
Query 10 text: Retrieve the product ID, product name, category ID, and
product price for each product, sorted by category ID and,
within the same category ID, by product price

Query 10 : SELECT productid, productname, categoryid,


productprice
FROM product
ORDER BY categoryid, productprice;

Query 10 result:

SQL– Slide 73
Database Systems - FET- JIH 73
SORTING

• Sorting in descending order:

SELECT ename, job, deptno, hiredate


FROM emp
ORDER BY hiredate DESC ; 1

• Sorting by column alias:


SELECT empno, ename, sal*12 annsal
FROM emp 2
ORDER BY annsal ;

• Sorting by multiple columns:

SELECT ename, deptno, sal


FROM emp 3
ORDER BY deptno, sal DESC;
SQL– Slide 74
USING COMPARISON CONDITIONS

SELECT ename, sal


FROM emp
WHERE sal <= 3000 ;

Chapter 5 – Slide SQL– Slide 75


USING THE BETWEEN CONDITION
▪ Use the BETWEEN condition to display rows based on a range
of values:

SELECT ENAME, sal


FROM emp Lower limit Upper limit
WHERE sal BETWEEN 2500 AND 3500;
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

SQL– Slide 76
USING THE IN CONDITION

▪ Use the IN membership condition to test for values in a list:

SELECT empno, ename, sal, SUPERENO


FROM emp
WHERE SUPERENO IN (7902, 7788, 7782) ;

SQL– Slide 77
LIKE

▪ LIKE
• Used for retrieval of records whose values partially match a certain
criteria

SQL– Slide 78
Database Systems - FET- JIH 78
LIKE

Query 11 text: Retrieve the record for each product whose product name
contains the phrase ’Boot’

Query 11 : SELECT *
FROM product
WHERE productname LIKE '%Boot%';

Query 11 result:

SQL– Slide 79
Database Systems - FET- JIH 79
USING THE LIKE CONDITION

• Use the LIKE condition to perform wildcard searches of


valid search string values.
• Search conditions can contain either literal characters or
numbers:
o % denotes zero or many characters.
o _ denotes one character.

SELECT ename
FROM emp
WHERE ename LIKE 'S%' ;

SQL– Slide 80
USING THE LIKE CONDITION

• You can combine pattern-matching characters:

SELECT ename
FROM emp
WHERE ename LIKE '_o%' ;

• You can use the ESCAPE identifier to search for the actual
% and _ symbols.

SQL– Slide 81
Examples showing different LIKE operators
with '%' and '_' wildcards:

LIKE Operator Description


WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any
position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the
second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and
are at least 2 characters in length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and
are at least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and
ends with "o"
SQL– Slide 82
Wildcard Characters in SQL Server
Symbol Description Example
% Represents zero or bl% finds bl, black,
more characters blue, and blob
_ Represents a single h_t finds hot, hat, and
character hit
[] Represents any single h[oa]t finds hot and
character within the hat, but not hit
brackets
^ Represents any h[^oa]t finds hit, but
character not in the not hot and hat
brackets
- Represents any single c[a-b]t finds cat and
character within the cbt
specified range
SQL– Slide 83
USING THE NULL CONDITIONS

▪ Test for nulls with the IS NULL operator.

SELECT ename, SUPERENO


FROM emp
WHERE SUPERENO IS NULL ;

SQL– Slide 84
LOGICAL CONDITIONS

Operator Meaning
AND Returns TRUE if both component
conditions are true
OR Returns TRUE if either component
condition is true
NOT Returns TRUE if the following
condition is false

Chapter 5 – Slide SQL– Slide 85


USING THE AND OPERATOR

AND requires both conditions to be true:


SELECT empno, ename, job, sal
FROM emp
WHERE sal >=3000
AND job LIKE ‘%MAN%' ;

Chapter 5 – Slide SQL– Slide 86


USING THE OR OPERATOR

OR requires either condition to be true:


SELECT empno, ename, job, sal
FROM emp
WHERE sal >=3000
OR job LIKE '%Man%' ;

Chapter 5 – Slide SQL– Slide 87


USING THE NOT OPERATOR

SELECT last_name, job_id


FROM employees
WHERE job_id
NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;

Chapter 5 – Slide SQL– Slide 88


EXAMPLES
1. SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);

2. SELECT * FROM Products


WHERE ProductName BETWEEN 'Carnarvon
Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

3. SELECT * FROM Products


WHERE ProductName BETWEEN "Carnarvon
Tigers" AND "Chef Anton's Cajun Seasoning"
ORDER BY ProductName;

4. SELECT * FROM Products


WHERE ProductName NOT BETWEEN 'Carnarvon
Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

SQL– Slide 89
SUBSTITUTION VARIABLES

... salary = ? …
… department_id = ? …
... last_name = ? ...

I want
to query
different
values.

SQL– Slide 90
SUBSTITUTION VARIABLES

• Use substitution variables to:


o Temporarily store values with (:) and ampersand (&)
substitution

SQL– Slide 91
USING THE : SUBSTITUTION VARIABLE

▪ Use a variable prefixed with (:) to prompt the user for a value:

SELECT empno, ename, sal, deptno


FROM emp
WHERE empno= :employee_num ;

SQL– Slide 92
CHARACTER AND DATE VALUES
WITH SUBSTITUTION VARIABLES

SELECT last_name, department_id, salary*12


FROM employees
WHERE job_id = :job_title ;

SQL– Slide 93
USING THE & SUBSTITUTION VARIABLE

▪ Use the ampersand (&) if you want to reuse the variable value
without prompting the user each time:

SELECT employee_id, last_name, job_id, :Value * salary


FROM employees
Where &Value * salary < 100000 ;

SQL– Slide 94
AGGREGATE FUNCTIONS

▪ Aggregate functions
• For calculating and summarizing values in queries, SQL
provides the following aggregate functions:
o COUNT
o SUM
o AVG
o MIN
o MAX

SQL– Slide 95
Database Systems - FET- JIH 95
AGGREGATE FUNCTIONS

Query 12 text: Retrieve the average price of all products

Query 12 : SELECT AVG(productprice)


FROM product;

Query 12 result:

SQL– Slide 96
Database Systems - FET- JIH 96
USING THE COUNT FUNCTION
COUNT(*) returns the number of rows in a table.

SELECT COUNT(*)
FROM emp;
The COUNT Function The COUNT function has two formats:
COUNT(*)
COUNT(expr)
COUNT(*) returns the number of rows in a table, including duplicate rows
and rows containing null values in any of the columns.
If a WHERE clause is included in the SELECT statement COUNT(*) returns
the number of rows that satisfies the condition in the WHERE clause.
In contrast. COUNT(expr) returns the number of nonnull rows in the column
identified by expr.
COUNT(expr) returns the number of non NULL rows in a table,
i.e. number of rows that satisfies expr .

SELECT COUNT(deptno)
FROM emp; SQL– Slide 97
USING THE COUNT FUNCTION

COUNT( expr) returns the number of rows in a table that satisfies the expr .

SELECT COUNT(DISTINCT deptno)


FROM emp ;

SQL– Slide 98
AGGREGATE FUNCTIONS

Query 13 text: Show how many products we offer for sale

Query 13 : SELECT COUNT(*)


FROM product;

Query 13 result:

SQL– Slide 99
Database Systems - FET- JIH 99
AGGREGATE FUNCTIONS

Query 14 text: Retrieve the number of vendors that supply our products

Query 14 : SELECT COUNT(DISTINCT vendorid)


FROM product;

Query 14 result:

SQL– Slide 100


Database Systems - FET- JIH 100
AGGREGATE FUNCTIONS

Query 15 text: Retrieve the number of products, average product price, lowest
product price, and highest product price in the CP product
category

Query 15 : SELECT COUNT(*), AVG(productprice),


MIN(productprice), MAX(productprice)
FROM product
WHERE categoryid = 'CP';

Query 15 result:

SQL– Slide 101


Database Systems - FET- JIH 101
GROUP BY

▪ GROUP BY
• Enables summarizations across the groups of related data within tables

SQL– Slide 102


Database Systems - FET- JIH 102
GROUP BY

Query 16 text: For each vendor, retrieve the vendor ID, number of products
supplied by the vendor, and average price of the products
supplied by the vendor

Query 16 : SELECT vendorid, COUNT(*), AVG(productprice)


FROM product
GROUP BY vendorid;

Query 16 result:

SQL– Slide 103


Database Systems - FET- JIH 103
Query 16
illustration

SQL– Slide 104


Database Systems - FET- JIH 104
GROUP BY

Query 16 text: For each vendor, retrieve the vendor ID, number of products
supplied by the vendor, and average price of the products
supplied by the vendor

Query 16 : SELECT vendorid, COUNT(*), AVG(productprice)


INVALID FROM product;
ERROR MESSAGE RETURNED

SQL– Slide 105


Database Systems - FET- JIH 105
GROUP BY

Query 17 text: For each vendor, retrieve the number of products supplied by
the vendor and the average price of the products supplied by
the vendor

Query 17 : SELECT COUNT(*), AVG(productprice)


FROM product
GROUP BY vendorid;

Query 17 result
(vs. Query 16):

Query 17 result Query 16 result

SQL– Slide 106


Database Systems - FET- JIH 106
GROUP BY

Query 18 text: For each vendor, retrieve the vendor ID and the number of
products with a product price of $100 or higher supplied by the
vendor

Query 18 : SELECT vendorid, COUNT(*)


FROM product
WHERE productprice >= 100
GROUP BY vendorid;

Query 18 result:

SQL– Slide 107


Database Systems - FET- JIH 107
GROUP BY
Query 19 text: Consider the groups of products where each group contains
the products that are from the same category supplied by the
same vendor. For each such group, retrieve the vendor ID,
product category ID, number of products in the group, and
average price of the products in the group.

Query 19 : SELECT vendorid, categoryid, COUNT(*),


AVG(productprice)
FROM product
GROUP BY vendorid, categoryid;

Query 19 result:

SQL– Slide 108


Database Systems - FET- JIH 108
GROUP BY

Query 20 text: For each product, retrieve the ProductID value and the total
number of product items sold within all sales transactions.

Query 20 : SELECT productid, SUM(quantity)


FROM includes
GROUP BY productid;

Query 20 result:

SQL– Slide 109


Database Systems - FET- JIH 109
GROUP BY

Query 21 text: For each product, retrieve the ProductID value and the number
of sales transactions in which the product was sold

Query 21: SELECT productid, COUNT(*)


FROM includes
GROUP BY productid;

Query 21 result:

SQL– Slide 110


Database Systems - FET- JIH 110
Data records: ZAGI Retail Company Sales Department Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 111
GROUP BY CLAUSE+AVG

1. SELECT deptno, AVG(sal)


FROM emp
GROUP BY deptno ;
DEPTNO AVG(SAL)
30 1566,66667
20 2175
10 2916,66667
2. SELECT deptno, AVG(sal)
FROM emp
GROUP BY deptno
ORDER BY AVG(sal) ;

DEPTNO AVG(SAL)
30 1566,66667
20 2175
10 2916,66667

SQL– Slide 112


GROUPING BY MORE THAN ONE COLUMN
SELECT deptno, job, SUM(sal)
FROM emp
GROUP BY deptno, job
ORDER BY deptno ;

DEPTNO JOB SUM(SAL)


10 CLERK 1300
10 MANAGER 2450
10 PRESIDENT 5000
20 ANALYST 6000
20 CLERK 1900
20 MANAGER 2975
30 CLERK 950
30 MANAGER 2850
30 SALESMAN 5600

SQL– Slide 113


HAVING

▪ HAVING
• Enables summarizations across the groups of related data within tables
• Determines which groups will be displayed in the result of a query and,
consequently, which groups will not be displayed in the result of the
query
• A query that contains a HAVING clause must also contain a GROUP BY
clause

SQL– Slide 114


Database Systems - FET- JIH 114
HAVING
Query 22 text: Consider the groups of products where each group contains
the products that are from the same category and supplied by
the same vendor. For each such group that has more than one
product, retrieve the vendor ID, product category ID, number
of products in the group, and average price of the products in
the group.

Query 22: SELECT vendorid, categoryid, COUNT(*),


AVG(productprice)
FROM product
GROUP BY vendorid, categoryid
HAVING COUNT(*) > 1;

Query 22 result:

SQL– Slide 115


Database Systems - FET- JIH 115
Query 22
illustration

SQL– Slide 116


Database Systems - FET- JIH 116
Query 22
illustration

SQL– Slide 117


Database Systems - FET- JIH 117
HAVING
Query 23 text: Consider the groups of products where each group contains
the products that are from the same category, supplied by the
same vendor, and whose product price is $50 or higher. For
each such group that has more than one product, retrieve the
vendor ID, product category ID, number of products in the
group, and average price of the products.

Query 23: SELECT vendorid, categoryid, COUNT(*),


AVG(productprice)
FROM product
WHERE productprice >= 50
GROUP BY vendorid, categoryid
HAVING COUNT(*) > 1;
Query 23 result:

SQL– Slide 118


Database Systems - FET- JIH 118
HAVING

Query 24 text: For each product that has more than three items sold within all
sales transactions, retrieve the ProductID value and the total
number of product items sold within all sales transactions

Query 24: SELECT productid, SUM(quantity)


FROM includes
GROUP BY productid
HAVING SUM(quantity) > 3;

Query 24 result:

SQL– Slide 119


Database Systems - FET- JIH 119
HAVING

Query 25 text: For each product that was sold in more than one sales
transaction, retrieve the ProductID value and the number of
sales transactions in which the product was sold

Query 25: SELECT productid, COUNT(*)


FROM includes
GROUP BY productid
HAVING COUNT(*) > 1;

Query 25 result:

SQL– Slide 120


Database Systems - FET- JIH 120
HAVING

Query 26 text: For each product that has more than three items sold within all
sales transactions, retrieve the ProductID value

Query 26: SELECT productid


FROM includes
GROUP BY productid
HAVING SUM(quantity) > 3;

Query 26 result:

SQL– Slide 121


Database Systems - FET- JIH 121
HAVING

Query 27 text: For each product that was sold in more than one sales
transaction, retrieve the ProductID value

Query 27: SELECT productid

FROM includes
GROUP BY productid
HAVING COUNT(*) > 1;
Query 27 result:

SQL– Slide 122


Database Systems - FET- JIH 122
HAVING EXAMPLE 1
▪ Problem: List the number of customers in each country. Only
include countries with more than 10 customers.
SELECT Country, COUNT(Id) AS Customers
CUSTOMER
FROM Customer Id
FirstName
GROUP BY Country
LastName
HAVING COUNT(Id) > 10 City
Country
Phone

SQL– Slide 123


HAVING EXAMPLE 2
▪ Problem: List the number of customers in each country, except
the USA, sorted high to low. Only include countries with 9 or
more customers.
CUSTOMER
SELECT Country, COUNT(Id) AS Customers Id
FROM Customer FirstName
WHERE Country <> 'USA’
LastName
GROUP BY Country
City
HAVING COUNT(Id) >= 9
ORDER BY COUNT(Id) DESC Country
Phone

SQL– Slide 124


HAVING EXAMPLE 3

SQL– Slide 125


NESTED QUERIES
▪ A Subquery or Inner query or a Nested query is a
query within another SQL query and embedded
within the WHERE clause.
▪ A subquery is used to return data that will be used
in the main query as a condition to further restrict
the data to be retrieved.
▪ Nested Query
• A query that is used within another query
A nested query is also referred to as an inner query
o

o The query that uses the nested query is referred to as an outer query

o Subqueries can be used with the SELECT, INSERT, UPDATE, and


DELETE statements along with the operators like =, <, >, >=, <=, IN,
BETWEEN, etc.
SQL– Slide 126
Database Systems - FET- JIH 126
RULES THAT SUBQUERIES MUST FOLLOW
▪ Subqueries must be enclosed within parentheses.
▪ A subquery can have only one column in the SELECT clause,
unless multiple columns are in the main query for the subquery to
compare its selected columns.
▪ An ORDER BY command cannot be used in a subquery, although
the main query can use an ORDER BY. The GROUP BY
command can be used to perform the same function as the
ORDER BY in a subquery.
▪ Subqueries that return more than one row can only be used with
multiple value operators such as the IN operator.
▪ The SELECT list cannot include any references to values that
evaluate to a BLOB, ARRAY, CLOB, or NCLOB.
▪ A subquery cannot be immediately enclosed in a set function.
▪ The BETWEEN operator cannot be used with a subquery.
However, the BETWEEN operator can be used within the
subquery. SQL– Slide 127
SUBQUERIES WITH THE SELECT STATEMENT
▪ The basic syntax is as follows −

SELECT column_name [, column_name ]


FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])

SQL– Slide 128


NESTED QUERIES

Query 28 text: For each product whose product price is below the average
price of all products, retrieve the product ID, product name,
and product price

Query 28: SELECT productid, productname, productprice


FROM product
WHERE productprice <( SELECT AVG(productprice)
FROM product);
Query 28 result:

SQL– Slide 129


Database Systems - FET- JIH 129
Query 28
illustration

SQL– Slide 130


Database Systems - FET- JIH 130
NESTED QUERIES

Query 28 text: For each product whose product price is below the average
price of all products, retrieve the product ID, product name,
and product price

Query 28: SELECT productid, productname, productprice


INVALID FROM product
WHERE productprice < AVG(productprice);
ERROR MESSAGE RETURNED

SQL– Slide 131


Database Systems - FET- JIH 131
IN

▪ IN
• Used for comparison of a value with a set of values

SQL– Slide 132


Database Systems - FET- JIH 132
IN
Query 29 text: Retrieve the product id, product name, and product price for
products whose product id is either 1X1 or 2X2 or 3X3

Query 29: SELECT productid, productname, productprice


FROM product
WHERE (productid = '1X1' OR productid = '2X2'
OR productid = '3X3');

Query 29 result:

SQL– Slide 133


Database Systems - FET- JIH 133
IN
Query 29 text: Retrieve the product id, product name, and product price for
products whose product id is either 1X1 or 2X2 or 3X3

Query 29alt: SELECT productid, productname, productprice


FROM product
WHERE productid IN ('1X1', '2X2', '3X3');

Query 29alt result:

SQL– Slide 134


Database Systems - FET- JIH 134
IN
Query 30 text: For each product that has more than three items sold within all
sales transactions, retrieve the product ID, product name, and
product price

Query 30: SELECT productid, productname, productprice


FROM product
WHERE productid IN
(SELECT productid
FROM includes
GROUP BY productid
HAVING SUM(quantity) > 3);

Query 30 result:

SQL– Slide 135


Database Systems - FET- JIH 135
IN
Query 31 text: For each product whose items were sold in more than one
sales transaction, retrieve the product id, product name and
product price

Query 31 : SELECT productid, productname, productprice


FROM product
WHERE productid IN
(SELECT productid
FROM includes
GROUP BY productid
HAVING COUNT(*) > 1);

Query 31 result:

SQL– Slide 136


Database Systems - FET- JIH
Data records: ZAGI Retail Company Sales Department Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 137
EXAMPLE
▪ Consider the CUSTOMERS table having the following records −
▪ +----+----------+-----+-----------+----------+
▪ | ID | NAME | AGE | ADDRESS | SALARY |
▪ +----+----------+-----+-----------+----------+
▪ | 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
▪ | 2 | Khilan | 25 | Delhi | 1500.00 |
▪ | 3 | kaushik | 23 | Kota | 2000.00 |
▪ | 4 | Chaitali | 25 | Mumbai | 6500.00 |
▪ | 5 | Hardik | 27 | Bhopal | 8500.00 |
▪ | 6 | Komal | 22 | MP | 4500.00 |
▪ | 7 | Muffy | 24 | Indore | 10000.00 |
▪ +----+----------+-----+-----------+----------+

SQL– Slide 138


SQL> SELECT * FROM CUSTOMERS
WHERE ID IN
(SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;

SQL– Slide 139


USING A SUBQUERY
SELECT ename, sal, deptno, job
FROM EMP
WHERE job =
( SELECT job FROM emp
WHERE empno=7369);
ENAME SAL DEPTNO JOB
ADAMS 1100 20 CLERK
JAMES 950 30 CLERK
MILLER 1300 10 CLERK
SMITH 800 20 CLERK
ADAMS 1100 20 CLERK
JAMES 950 30 CLERK
MILLER 1300 10 CLERK
SQL– Slide 140
JOIN
• A JOIN clause is used to combine rows from two or more
tables, based on a related column between them.

• Facilitates the querying of multiple tables

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:
•(INNER) JOIN: Returns records that have matching values in both tables
•LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
•RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the left table
•FULL (OUTER) JOIN: Returns all records when there is a match in either left or
right table

SQL– Slide 141


Database Systems - FET- JIH 141
INNER JOIN
The INNER JOIN keyword selects records that have matching values in
both tables.
INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

SQL– Slide 142


LEFT JOIN
The LEFT JOIN keyword returns all records from the left table
(table1), and the matching records from the right table (table2). The
result is 0 records from the right side, if there is no match.
Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.
LEFT JOIN Syntax
SELECT column_name(s)
FROM table1 LEFT JOIN table2
ON table1.column_name = table2.column_name;

SQL– Slide 143


RIGHT JOIN
The RIGHT JOIN keyword returns all records from the right table
(table2), and the matching records from the left table (table1). The
result is 0 records from the left side, if there is no match.
Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

RIGHT JOIN Syntax


SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

SQL– Slide 144


FULL OUTER JOIN
The FULL OUTER JOIN keyword returns all records when there is a match in
left (table1) or right (table2) table records.
Tip: FULL OUTER JOIN and FULL JOIN are the same.
FULL OUTER JOIN Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;

Note: FULL OUTER JOIN can


potentially return very large
result-sets!

SQL– Slide 145


INNER AND OUTER JOIN

▪ INNER JOIN
• Regular JOIN
• Joins records from two tables where the value of a specified column in a
record in one table matches the value of a specified column in another
(or same) table
• Regular JOIN is also sometimes referred to as an INNER JOIN, to
differentiate it from the OUTER JOIN

SQL– Slide 146


Database Systems - FET- JIH 146
INNER JOIN

Query 41: SELECT a.buildingid, a.aptno, c.ccname


FROM apartment a, corpclient c
WHERE a.ccid = c.ccid;

Query 41 result:

SQL– Slide 147


Database Systems - FET- JIH 147
INNER JOIN

Query 41: SELECT a.buildingid, a.aptno, c.ccname


alt syntax 1
FROM apartment a JOIN corpclient c
ON a.ccid = c.ccid;

Query 41 result:

SQL– Slide 148


Database Systems - FET- JIH 148
Data records: HAFH Realty Company Property Management Database (part 1)

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 149
INNER JOIN

Query 41: SELECT a.buildingid, a.aptno, c.ccname


alt syntax 2 FROM apartment a
INNER JOIN corpclient c
ON a.ccid = c.ccid;

Query 41 result:

SQL– Slide 150


Database Systems - FET- JIH 150
INNER AND OUTER JOIN

▪ OUTER JOIN
• Variation of the JOIN operation that supplements the results with the
records from one relation that have no match in the other relation
o LEFT OUTER JOIN
o RIGHT OUTER JOIN
o FULL OUTER JOIN

SQL– Slide 151


Database Systems - FET- JIH 151
OUTER JOIN

Query 42: SELECT a.buildingid, a.aptno, c.ccname


FROM apartment a LEFT OUTER JOIN corpclient c
ON a.ccid = c.ccid;

Query 42 result:

SQL– Slide 152


Database Systems - FET- JIH 152
OUTER JOIN

Query 43: SELECT a.buildingid, a.aptno, c.ccname


FROM apartment a RIGHT OUTER JOIN corpclient c
ON a.ccid = c.ccid;

Query 43 result:

SQL– Slide 153


Database Systems - FET- JIH 153
OUTER JOIN

Query 44: SELECT a.buildingid, a.aptno, c.ccname


FROM apartment a FULL OUTER JOIN corpclient c
ON a.ccid = c.ccid;

Query 44 result:

SQL– Slide 154


Database Systems - FET- JIH 154
JOIN
Query 32 text: For each product, retrieve the product ID, name of the product,
name of the vendor of the product, and price of the product

Query 32: SELECT productid, productname, vendorname,


productprice
FROM product, vendor
WHERE product.vendorid = vendor.vendorid;

Query 32 result:

SQL– Slide 155


Database Systems - FET- JIH 155
Data records: ZAGI Retail Company Sales Department Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 156
JOIN
Query 32 text: For each product, retrieve the product ID, name of the product,
name of the vendor of the product, and price of the product

Query 32: SELECT productid, productname, vendorname,


productprice
FROM product inner join vendor
on product.vendorid = vendor.vendorid;
Query 32 result:

SQL– Slide 157


Database Systems - FET- JIH 157
CARTESIAN PRODUCT
The CARTESIAN JOIN or
CROSS JOIN returns the
Cartesian product of the sets of
records from two or more
joined tables. Thus, it equates
to an inner join where the join-
condition always evaluates to
either True or where the join-
condition is absent from the
statement.
The CROSS JOIN is used to
generate a paired combination
of each row of the first table
with each row of the second
table.

SQL– Slide 158


Database Systems - FET- JIH 158
JOIN

Query 33:
SELECT productid, productname, vendorname, productprice
FROM product, vendor;

SQL– Slide 159


Database Systems - FET- JIH 159
Data records: ZAGI Retail Company Sales Department Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 160
JOIN

Query 33 result:

SQL– Slide 161


Database Systems - FET- JIH 161
JOIN

Query 34: SELECT *


FROM product, vendor;

Query 35:
SELECT *
FROM product, vendor
WHERE product.vendorid = vendor.vendorid;

SQL– Slide 162


Database Systems - FET- JIH 162
QUERY 34 RESULT:

SQL– Slide 163


CARTESIAN PRODUCT to JOIN
Formation of the result of Query 35:

SQL– Slide 164


Database Systems - FET- JIH 164
JOIN
Query 35 result:

SQL– Slide 165


Database Systems - FET- JIH 165
ALIAS

▪ Alias
• An alternative and usually shorter name that can be used anywhere
within a query instead of the full relation name

SQL– Slide 166


Database Systems - FET- JIH 166
ALIAS

Query 32 text: For each product, retrieve the product ID, name of the product,
name of the vendor of the product, and price of the product

Query 32:
SELECT productid, productname, vendorname,productprice
FROM product, vendor
WHERE product.vendorid = vendor.vendorid;
Query 32 result:

SQL– Slide 167


Database Systems - FET- JIH 167
ALIAS

Query 32a text: For each product, retrieve the product ID, name of the product,
(same query) name of the vendor of the product, and price of the product

Query 32a: SELECT p.productid, p.productname,


v.vendorname, p.productprice
FROM product p, vendor v
WHERE p.vendorid = v.vendorid;
Query 32a result:
(same result)
PRODUCTID PRODUCTNAME VENDORNAME PRODUCTPRICE
1X1 Zzz Bag Pacifica Gear 100

2X2 Easy Boot Mountain King 70

3X3 Cosy Sock Mountain King 15

4X4 Dura Boot Pacifica Gear 90

5X5 Tiny Tent Mountain King 150


SQL– Slide 168
6X6 Systems - FET- JIH
Database Biggy Tent Mountain King 250 168
ALIAS

Query 32b text: For each product, retrieve the product id, name of the product,
(same query) name of the vendor of the product, and price of the product

Query 32b: SELECT p.productid pid, p.productname pname,


v.vendorname vname, p.productprice pprice
FROM product p, vendor v
WHERE p.vendorid = v.vendorid;

Query 32b result:


(same result,
different column
names in the result)

SQL– Slide 169


Database Systems - FET- JIH 169
ALIAS

Query 32c text: For each product, retrieve the product id, name of the product,
(same query) name of the vendor of the product, and price of the product

Query 32c: SELECT p.productid AS pid, p.productname AS pname,


v.vendorname AS vname, p.productprice AS pprice
FROM product p, vendor v
WHERE p.vendorid = v.vendorid;

Query 32c result:


(same result,
as Query 32b)

SQL– Slide 170


Database Systems - FET- JIH 170
JOIN WITHOUT USING A PRIMARY KEY/ FOREIGN KEY
COMBINATION

▪ Join without using a primary key/foreign key combination


• It is possible to join two tables without joining a foreign key column in
one table with a primary key column in another table.
• A JOIN condition can connect a column from one table with a column
from the other table as long as those columns contain the same values.

SQL– Slide 171


Database Systems - FET- JIH 171
JOIN WITHOUT USING A PRIMARY KEY/FOREIGN KEY
COMBINATION

Query 45 text: For each manager who has a staff member with the same
name as the manager’s first name, show the manager’s ID,
first name, and last name and the ID of the staff members who
have the same name as the manager’s first name

Query 45: SELECT m.managerid, m.mfname, m.mlname, s.smemberid


FROM manager m, staffmember s
WHERE m.mfname = s.smembername;

Query 45 result:

SQL– Slide 172


Database Systems - FET- JIH 172
Data records: HAFH Realty Company Property Management Database (part 1)

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 173
A SELF JOIN
▪ A self join is a regular join, but the table is joined with itself.
▪ SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;

▪ T1 and T2 are different table aliases for the same table.

SQL– Slide 174


EXAMPLE 1 (SELF JOIN)

Problem: Match customers that are from


the same city and country.
SELECT B.FirstName AS FirstName1, B.LastName AS LastName1,
A.FirstName AS FirstName2, A.LastName AS LastName2, B.City,
B.Country
FROM Customer A JOIN Customer B
ON A.Id <> B.Id
AND A.City = B.City
AND A.Country = B.Country
ORDER BY A.Country

SQL– Slide 175


EXAMPLE 1 (SELF JOIN, FINDING DUPLICATES)

Problem: Find customers with the same name


(first ) i.e. duplicates.

SELECT CONCAT(C1.FirstName, ' ', C1.LastName) AS Name,


CONCAT(C2.FirstName, ' ', C2.LastName) AS Duplicate
FROM Customer C1 JOIN Customer C2
ON C1.Id <> C2.Id
WHERE C1.FirstName = C2.FirstName
ORDER BY C1.FirstName

SQL– Slide 176


SELF-JOIN

▪ Self-JOIN
• A join statement that includes a relation that contains a foreign key
referring to itself, and joins a relation with itself in a query

SQL– Slide 177


Database Systems - FET- JIH 177
SELF-JOIN

Query 40 text: For all corporate clients that were referred by other corporate
clients, retrieve the name of the corporate client and the name
of the corporate client that referred it

Query 40: SELECT c.ccname AS client, r.ccname AS recommender


FROM corpclient c, corpclient r
WHERE r.ccid = c.ccidreferredby;

Query 40 result:

SQL– Slide 178


Database Systems - FET- JIH 178
JOINING MULTIPLE RELATIONS

▪ Joining multiple relations


• A query can contain multiple JOIN conditions, joining multiple relations

SQL– Slide 179


Database Systems - FET- JIH 179
JOINING MULTIPLE RELATIONS
Query 36 text: For each line item of a sales transaction, retrieve the
transaction identifier, date of the transaction, name of the
product that was sold, quantity sold, and amount charged, sorted
by transaction identifier
Query 36: SELECT t.tid, t.tdate, p.productname,
i.quantity AS quantity,
(i.quantity * p.productprice) AS amount
FROM product p, salestransaction t, includes i
WHERE i.productid = p.productid AND i.tid = t.tid
ORDER BY t.tid;

Query 36 result:

SQL– Slide 180


Database Systems - FET- JIH 180
Data records: ZAGI Retail Company Sales Department Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 181
DIFFERENCE BETWEEN NATURAL JOIN AND INNER
JOIN IN SQL
▪ 1. Natural Join :
Natural Join joins two tables based on same attribute name and
datatypes. The resulting table will contain all the attributes of
both the table but keep only one copy of each common column.
▪ Example:
Consider the two tables given below:
▪ Student Table Marks Table

SQL– Slide 182


DIFFERENCE BETWEEN NATURAL JOIN AND INNER
JOIN IN SQL

Consider the given query


SELECT * FROM Student NATURAL JOIN Marks;
Output :

SQL– Slide 183


DIFFERENCE BETWEEN NATURAL JOIN AND INNER
JOIN IN SQL
2. Inner Join :
Inner Join joins two table on the basis of the column which is
explicitly specified in the ON clause. The resulting table will
contain all the attributes from both the tables including common
column also.

SELECT *
FROM student S INNER JOIN Marks M ON S.Roll_No = M.Roll_No;

SQL– Slide 184


SR.NO. NATURAL JOIN INNER JOIN
1. Natural Join joins two tables Inner Join joins two table on the
based on same attribute name basis of the column which is
and datatypes. explicitly specified in the ON clause.
2. In Natural Join, The resulting table In Inner Join, The resulting table will
will contain all the attributes of contain all the attribute of both the
both the tables but keep only one tables including duplicate columns
copy of each common column also
3. In Natural Join, If there is no In Inner Join, only those records will
condition specifies then it returns return which exists in both the
the rows based on the common tables
column
4. SYNTAX: SYNTAX:
SELECT * SELECT *
FROM table1 NATURAL JOIN FROM table1 INNER JOIN table2
table2; ON table1.Column_Name =
table2.Column_Name;
SQL– Slide 185
VIEW

▪ VIEW
• Mechanism in SQL that allows the structure of a query to be saved in the
RDBMS
• Also known as a virtual table
o View is not an actual table and does not have any data physically saved
• Every time a view is invoked, it executes a query that retrieves the data
from the actual tables
• A view can be used in SELECT statements just like any other table from
a database

SQL– Slide 186


Database Systems - FET- JIH 186
VIEW

Create View Statement 1:


CREATE VIEW products_more_than_3_sold AS
SELECT productid, productname, productprice
FROM product
WHERE productid IN
(SELECT productid
FROM includes
GROUP BY productid
HAVING SUM(quantity) > 3);

SQL– Slide 187


Database Systems - FET- JIH 187
VIEW
Query 30 text: For each product that has more than three items sold within all
sales transactions, retrieve the product ID, product name, and
product price

Query 30: SELECT productid, productname, productprice


FROM product
WHERE productid IN
(SELECT productid
FROM includes
GROUP BY productid
HAVING SUM(quantity) > 3);

Query 30 result:

SQL– Slide 188


Database Systems - FET- JIH 188
VIEW
Query 30a text: For each product that has more than three items sold
(same query) within all sales transactions, retrieve the product ID, product
name, and product price

Query 30a: SELECT *


FROM products_more_than_3_sold;

Query 30a result:


(same result)

SQL– Slide 189


Database Systems - FET- JIH 189
VIEW

Create View Statement 2:


CREATE VIEW products_in_multiple_trnsc AS
SELECT productid, productname, productprice
FROM product
WHERE productid IN
(SELECT productid
FROM includes
GROUP BY productid
HAVING COUNT(*) > 1);

SQL– Slide 190


Database Systems - FET- JIH 190
VIEW
Query 31 text: For each product whose items were sold in more than one
sales transaction, retrieve the product name and product price

Query 31 : SELECT productid, productname, productprice


FROM product
WHERE productid IN
(SELECT productid
FROM includes
GROUP BY productid
HAVING COUNT(*) > 1);

Query 31 result:

SQL– Slide 191


Database Systems - FET- JIH 191
VIEW
Query 31a text: For each product whose items were sold in more than one
sales transaction, retrieve the product name and product price

Query 31a : SELECT *


FROM products_in_multiple_trnsc;

Query 31a result:


(same result)

SQL– Slide 192


Database Systems - FET- JIH 192
SET OPERATORS

▪ Set operators
• Standard set operators: union, intersection, and difference
• Used to combine the results of two or more SELECT statements that are
union compatible
• Two sets of columns are union compatible if they contain the same
number of columns, and if the data types of the columns in one set
match the data types of the columns in the other set
o The first column in one set has a compatible data type with the data type of
the first column in the other set, the second column in one set has a
compatible data type with the data type of the second column in the other
set, and so on.
• The set operators can combine results from SELECT statements
querying relations, views, or other SELECT queries.

SQL– Slide 193


Database Systems - FET- JIH 193
SQL– Slide 194
SET OPERATORS
▪ UNION
• Used to combine the union compatible results of two
SELECT statements by listing all rows from the result
of the first SELECT statement and all rows from the
result of the other SELECT statement
o If two or more rows are identical only one of them

is shown (duplicates are eliminated from the result)


▪ Union All Operation
▪ Union all operation is most of the wark to Union. But it
also display the multiple duplicate records.
SELECT * FROM Products
UNION ALL
SELECT * FROM User;
SQL– Slide 195
Database Systems - FET- JIH 195
SET OPERATORS
Query 37 text: Retrieve the product ID, product name, and product price for
each product that has more than three items sold within all
sales transactions or whose items were sold in more than one
sales transaction

Query 37: SELECT *


FROM products_more_than_3_sold
UNION
SELECT *
FROM products_in_multiple_trnsc;
Query 37 result:

SQL– Slide 196


Database Systems - FET- JIH 196
SQL– Slide 197
SET OPERATORS

▪ INTERSECT
• Used to combine the results of two SELECT statements that are union
compatible by listing every row that appears in the result of both of the
SELECT statements

SQL– Slide 198


Database Systems - FET- JIH 198
SET OPERATORS
Query 38 text: Retrieve the product ID, product name, and product price for
each product that has more than three items sold within all
sales transactions and whose items were sold in more than
one sales transaction

Query 38: SELECT *


FROM products_more_than_3_sold
INTERSECT
SELECT *
FROM products_in_multiple_trnsc;

Query 38 result:

SQL– Slide 199


Database Systems - FET- JIH 199
SET OPERATORS

▪ MINUS (EXCEPT)
• Used to combine the results of two SELECT statements that are union
compatible by listing every row from the result of the first SELECT
statement that does not appear in the result of the other SELECT
statement

SQL– Slide 200


Database Systems - FET- JIH 200
SET OPERATORS
Query 39 text: Retrieve the product ID, product name, and product price for
each product that has more than three items sold within all
sales transactions but whose items were not sold in more than
one sales transaction

Query 39: SELECT *


FROM products_more_than_3_sold
MINUS
SELECT *
FROM products_in_multiple_trnsc;

Query 39 result:

SQL– Slide 201


Database Systems - FET- JIH 201
IS NULL

▪ IS NULL
• Used in queries that contain comparisons with an empty value in a
column of a record

SQL– Slide 202


Database Systems - FET- JIH 202
IS NULL

Query 46 text: Retrieve records for all managers who do not have a bonus

Query 46: SELECT *


FROM manager
WHERE mbonus IS NULL;

Query 46 result:

SQL– Slide 203


Database Systems - FET- JIH 203
EXISTS

▪ EXISTS
• In queries where the inner query (nested query) uses columns from the
relations listed in the SELECT part of the outer query, the inner query is
referred to as a correlated subquery
• In such cases, the EXISTS operator can be used to check if the result of
the inner correlated query is empty

SQL– Slide 204


Database Systems - FET- JIH 204
EXISTS

Query 47 text: Retrieve records for all corporate clients that are currently
renting one or more apartments from us.

Query 47: SELECT *


FROM corpclient c
WHERE EXISTS
(SELECT *
FROM apartment a
WHERE c.ccid = a.ccid);

Query 47 result:

SQL– Slide 205


Database Systems - FET- JIH 205
NOT

▪ NOT
• Can be used in conjunction with the condition comparison statements
returning the Boolean values TRUE or FALSE

SQL– Slide 206


Database Systems - FET- JIH 206
NOT

Query 48 text: Retrieve records for all corporate clients that are currently
not renting one or more apartments from us.

Query 48: SELECT *


FROM corpclient c
WHERE NOT EXISTS
(SELECT *
FROM apartment a
WHERE c.ccid = a.ccid);

Query 48 result:

SQL– Slide 207


Database Systems - FET- JIH 207
MULTIPLE-ROW SUBQUERIES

• Return more than one row


• Use multiple-row comparison operators

Operator Meaning
IN Equal to any member in the list
ANY Compare value to each value returned by
the subquery
ALL Compare value to every value returned by
the subquery
MULTIPLE-ROW SUBQUERIES
• Subqueries that return more than one row are called multiple-row
subqueries. You use a multiple-row operator, instead of a single-row
operator, with a multiple-row subquery. The multiple-row operator expects
one or more values:

• SELECT last_name, salary, department_id


• FROM employees
• WHERE salary IN (SELECT MIN(salary)
• FROM employees
• GROUP BY department_id);
• Example
• Find the employees who earn the same salary as the minimum salary for
each department.
• The inner query is executed first, producing a query result. The main
query block is then processed and uses the values that were returned by
the inner query to complete its search condition. In fact, the main query
appears to the Oracle server as follows:
• SELECT last_name, salary, department_id
• FROM employees
• WHERE salary IN (2500, 4200, 4400, 6000, 7000, 8300,8600,
17000);
SQL– Slide 209
USING THE ANY OPERATOR
IN MULTIPLE-ROW SUBQUERIES
• The ANY operator (and its synonym, the SOME operator) compares a
value to each value returned by a subquery. The slide example displays
employees who are not MANAGER and whose salary is less than that of
any MANAGER. The maximum salary that a programmer earns is
$9,000.
• <ANY means less than the maximum. >ANY means more than the
minimum. =ANY is equivalent to IN.

SELECT EMPNO, ENAME, JOB, sal


FROM emp `
3375, 3250, 2850, 4000
WHERE sal < ANY
(SELECT sal
FROM emp
WHERE job = 'Manager')
AND job <> 'Manager';
EMPNO ENAME JOB SAL
7369 Smith Clerk 1200
7900 James Clerk 1350
7876 Adams Clerk 1500
7521 Ward Salesman 1650
7654 Martin Salesman 1650

….
7702 Alaa Salesman 2100
7902 Ford Analyst 3500
7788 Scott Analyst 3500
7701 Nader Analyst 3750

13 rows returned in 0.00 seconds

SQL– Slide 211


USING THE ALL OPERATOR
IN MULTIPLE-ROW SUBQUERIES
• The ALL operator compares a value to every value returned by a
subquery. The slide example displays employees whose salary is less
than the salary of all employees with a job ID of IT_PROG and whose
job is not IT_PROG.
• >ALL means more than the maximum, and <ALL means less than the
minimum.
• The NOT operator can be used with IN, ANY, and ALL operators.
SELECT EMPNO, ENAME, JOB, sal
FROM emp 3375, 3250, 2850, 4000
WHERE sal < all
(SELECT sal
FROM emp
WHERE job = 'Manager')
AND job <> 'Manager';
EMPNO ENAME JOB SAL
7702 Alaa Salesman 2100
7499 Allen Salesman 2000
7844 Turner Salesman 1900
7703 Walaa Clerk 1800
7934 Miller Clerk 1700
7654 Martin Salesman 1650
7521 Ward Salesman 1650
7876 Adams Clerk 1500
7900 James Clerk 1350
7369 Smith Clerk 1200

10 rows returned in 0.00 seconds

SQL– Slide 213


NULL VALUES IN A SUBQUERY

SELECT e.EMPNO, e.ENAME, e.JOB, e.sal


FROM emp e
WHERE e.empno NOT IN
(select m.SUPERENO from emp m)
no rows selected
SELECT e.EMPNO, e.ENAME, e.JOB, e.sal
FROM emp e
WHERE e.empno NOT IN
(select m.SUPERENO from emp m
where m.SUPERENO IS NOT NULL))

EMPNO ENAME JOB SAL


7369 Smith Clerk 1200
7499 Allen Salesman 2000
7521 Ward Salesman 1650
7654 Martin Salesman 1650
7701 Nader Analyst 3750
7702 Alaa Salesman 2100
7703 Walaa Clerk 1800
7844 Turner Salesman 1900
7876 Adams Clerk 1500
7900 James Clerk 1350
7934 Miller Clerk 1700
Creating a Table
by Using a Subquery

– Create a table and insert rows by combining the CREATE


TABLE statement and the AS subquery option.
CREATE TABLE table
[(column, column...)]
AS subquery;

– Match the number of specified columns to the number of


subquery columns.
– Define columns with column names and
default values.
Creating a Table
by Using a Subquery

CREATE TABLE dept80


AS
SELECT employee_id, last_name,
salary*12 ANNSAL,
hire_date
FROM employees
WHERE department_id = 80;
Table created.

DESCRIBE dept80
INSERTING FROM A QUERY

▪ Inserting from a query


• A query retrieving the data from one relation can be used to populate
another relation

SQL– Slide 218


Database Systems - FET- JIH 218
INSERTING FROM A QUERY
Create Table Statement 1:
CREATE TABLE cleaningdenormalized
( buildingid CHAR(3) NOT NULL,
aptno CHAR(5) NOT NULL,
smemberid CHAR(4) NOT NULL,
smembername VARCHAR(15) NOT NULL,
PRIMARY KEY (buildingid, aptno, smemberid));

Insert Statement 2:
INSERT INTO cleaningdenormalized
SELECT c.buildingid, c.aptno, s.smemberid, s.smembername
FROM cleaning c, staffmember s
WHERE c.smemberid = s.smemberid;

SQL– Slide 219


Database Systems - FET- JIH 219
Data records: HAFH Realty Company Property Management Database (part 1)

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 220
ALTERNATIVE QUERIES

Query 47 text: Retrieve records for all corporate clients that are currently
renting one or more apartments from us.

Query 47: SELECT *


FROM corpclient c
WHERE EXISTS
(SELECT *
FROM apartment a
WHERE c.ccid = a.ccid);

Query 47 result:

SQL– Slide 221


Database Systems - FET- JIH 221
ALTERNATIVE QUERIES

Query 47 text: Retrieve records for all corporate clients that are currently
renting one or more apartments from us.

Query 47: SELECT *


alt 1 FROM corpclient c
WHERE c.ccid IN
(SELECT cc.ccid
FROM apartment a, corpclient cc
WHERE cc.ccid = a.ccid);

Query 47 result:

SQL– Slide 222


Database Systems - FET- JIH 222
ALTERNATIVE QUERIES

Query 47 text: Retrieve records for all corporate clients that are currently
renting one or more apartments from us.

Query 47: SELECT DISTINCT c.ccid, c.ccname, c.ccindustry


alt 2 c.cclocation, c.ccidreferredby
FROM corpclient c, apartment a
WHERE c.ccid = a.ccid;

Query 47 result:

SQL– Slide 223


Database Systems - FET- JIH 223
INAPPROPRIATE USE OF OBSERVED VALUES IN SQL

▪ Inappropriate use of Observed Values in SQL


• A common beginner’s SQL mistake occurs when novice user creates a
simplistic query that produces the correct result by inappropriately using
observed values

SQL– Slide 224


Database Systems - FET- JIH 224
INAPPROPRIATE USE OF OBSERVED VALUES IN SQL
Request A For each product that has more than three items sold within all
sales transactions, retrieve the product id, product name, and
product price
SQL Query A: SELECT productid, productname, productprice
FROM product
WHERE productid IN
(SELECT productid
FROM includes
GROUP BY productid
HAVING SUM(quantity) > 3);

SQL Query B: SELECT productid, productname, productprice


FROM product
WHERE productid IN ('3X3','4X4');

Query A and B
Result:

SQL– Slide 225


Database Systems - FET- JIH 225
Data records: ZAGI Retail Company Sales Department Database

Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 226
SQL STANDARD AND SQL SYNTAX DIFFERENCES

▪ SQL Standard
• SQL became the standard language for querying data contained in a
relational database

SQL– Slide 227


Database Systems - FET- JIH 227
SQL STANDARD AND SQL SYNTAX DIFFERENCES
▪ SQL standard and SQL syntax differences
• Minor SQL syntax differences exist in SQL implementations in various
popular RDBMS packages, such as differences in:
o DATE and TIME data types
o FOREIGN KEY syntax
o Usage of AS keyword with aliases
o ALTER TABLE syntax
o Set operators
o FULL OUTER JOIN implementation
o Constraint management
o GROUP BY restrictions

SQL– Slide 228


Database Systems - FET- JIH 228

You might also like