DB DR - Jehad Slides
DB DR - Jehad Slides
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.
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
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?)
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.
Chapter 1 – Slide 10
DATABASE METADATA
Chapter 1 – Slide 11
DATABASE METADATA
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
▪ 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
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
Chapter 1 – Slide 26
INTERACTION WITH DATABASE
Chapter 1 – Slide 27
INTERACTION WITH DATABASE
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
Chapter 1 – Slide 46
PEOPLE INVOLVED WITH DATABASE SYSTEMS
Chapter 1 – Slide 47
PEOPLE INVOLVED WITH DATABASE SYSTEMS
▪ 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
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
• 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
DBMS Software
Software to Process Queries / Programs
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)
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
Chapter 1 – Slide 59
Data Models
60’s
Hierarchical Network
70's
00’s
Chapter 1 – Slide 60
Sharing—Multiple views of data
Database Management System
Database
Chapter 1 – Slide 61
Characteristics of the DB Approach
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
Chapter 1 – Slide 65
Host Languages
C, C++, Fortran, Lisp, Java, Perl, …
Application prog.
Calls to
DB DBMS
Local Vars
(Memory)
(Storage)
ssn
cid
Course
Student
Takes
quarter
Advises Teaches
Professor
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
▪ 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’
Chapter 1 – Slide 72
CHAPTER 2 - Database Requirements and ER
Modeling
Chapter 2 – Slide 1
INTRODUCTION
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.
Chapter 2 – Slide 3
DATA MODELS (CONTINUED)
• 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
Chapter 2 – Slide 5
ENTITIES
Two entities
Chapter 2 – Slide 6
ENTITIES
Chapter 2 – Slide 7
ATTRIBUTES
Chapter 2 – Slide 8
ATTRIBUTES
Chapter 2 – Slide 9
RELATIONSHIPS
Chapter 2 – Slide 10
RELATIONSHIPS
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
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
Chapter 2 – Slide 17
RELATIONSHIPS
Chapter 2 – Slide 18
RELATIONSHIPS
A 1:M Relationship
A M:N Relationship
A 1:1 Relationship
Chapter 2 – Slide 19
RELATIONSHIPS
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
Chapter 2 – Slide 28
ATTRIBUTES
Chapter 2 – Slide 29
ATTRIBUTES
Chapter 2 – Slide 30
ATTRIBUTES
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
Chapter 2 – Slide 33
ATTRIBUTES
Chapter 2 – Slide 34
ATTRIBUTES
Chapter 2 – Slide 35
ATTRIBUTES
Chapter 2 – Slide 36
ATTRIBUTES
Chapter 2 – Slide 37
ATTRIBUTES
Another derived attribute example
Chapter 2 – Slide 38
ATTRIBUTES
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
Chapter 2 – Slide 43
RELATIONSHIPS
Chapter 2 – Slide 44
RELATIONSHIPS
Unary relationship examples
Chapter 2 – Slide 45
RELATIONSHIPS
Chapter 2 – Slide 46
RELATIONSHIPS
Unary relationships with role names
Chapter 2 – Slide 47
RELATIONSHIPS
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
Chapter 2 – Slide 50
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
Chapter 2 – Slide 55
WEAK ENTITY
Chapter 2 – Slide 56
NAMING CONVENTIONS FOR ER DIAGRAMS
▪ Relationships
• Use verbs or verb phrases, rather than nouns
Chapter 2 – Slide 57
MULTIPLE ER DIAGRAMS
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
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
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
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
Chapter 2 – Slide 74
REDUCING THE NUMBER OF ATTRIBUTES
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
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
Chapter 2 – Slide 80
Chapter 2 – Slide 81
CHAPTER 3 - Relational Database Modeling
INTRODUCTION
Terminology
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
Sample data
records for the
mapped relation
Entity with a
composite
attribute mapped
into a relation
Sample data
records for the
mapped relation
The mapped
relation as
presented to a
user in a front-end
application
Sample data
records for the
mapped relation
Sample data
records for the
mapped relation
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
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
Sample data
records for the
mapped ER
diagram
Jukić, Vrbsky, Nestorov, Sharma – Database Systems Chapter 3 – Slide 38
REFERENTIAL INTEGRITY CONSTRAINT
Referential integrity
constraint —
compliance example
Referential integrity
constraint —
compliance example
Referential integrity
constraint —
violation example
Sample data
records for the
mapped relation
Sample data
records for the
mapped relation
Sample data
records for the
mapped relations
Mapping a 1:M
unary relationship
Sample data
records for the
mapped relation
Mapping a M:N
unary relationship
Sample data
records for the
mapped relations
Mapping a 1:1
unary relationship
Sample data
records for the
mapped relation
Sample data
records for the
mapped relations
Mapping a
weak entity
Sample data
records for the
mapped relations
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
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
• 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
• Types of constraints:
▪ Key constraint
▪ Entity 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
Key constraint
• Key constraint:
NOTE:
▪ User-defined constraints
• Added by the database designers
Specific
minimum
and
maximum
cardinalities
Sample data
records for the
mapped relations
▪ Business rules
• User defined constraints that specify restrictions on databases that are
not a part of the standard notation for creating ER diagrams
Sample data
records for the
mapped relation
Sample data
records for the
mapped relation
Sample data
records for the
mapped relation
Sample data
records for the
relation with a
designer-created
primary key
DNO = 4 (EMPLOYEE)
◼ Select the employee tuples whose salary is greater than $30,000:
SALARY > 30,000 (EMPLOYEE)
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
operations
◼ Necessary in some cases (see JOIN operation
later)
◼ UNION Example
◼ 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”
{uv | ( q) ( r) ( s) ( t) ( w) ( x) ( y) ( z)
(EMPLOYEE(qrstuvwxyz) and q=‘John’ and r=‘B’ and
s=‘Smith’)}
SQL– Slide 2
Database Systems - FET- JIH 2
INTRODUCTION
SQL– Slide 3
Database Systems - FET- JIH 3
INTRODUCTION
SQL– Slide 4
Database Systems - FET- JIH 4
INTRODUCTION
SQL– Slide 5
Database Systems - FET- JIH 5
INTRODUCTION
SQL– Slide 6
Database Systems - FET- JIH 6
INTRODUCTION
SQL– Slide 7
Database Systems - FET- JIH 7
INTRODUCTION
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
);
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:
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) );
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) );
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) );
– 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
SQL– Slide 25
INSERTING NEW ROWS
SQL– Slide 26
INSERTING ROWS WITH NULL VALUES
SQL– Slide 27
INSERTING SPECIAL VALUES
SQL– Slide 28
INSERTING SPECIFIC DATE VALUES
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;
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));
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');
SQL– Slide 46
CONSTRAINT MANAGEMENT
Alter Statement 5: ALTER TABLE manager
ADD CONSTRAINT fkresidesin
FOREIGN KEY (mresbuildingid)
REFERENCES building (buildingid);
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;
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:
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 result:
SQL– Slide 55
Database Systems - FET- JIH 55
SELECT
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 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 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 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
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
• 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 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 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 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 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 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 result:
SQL– Slide 73
Database Systems - FET- JIH 73
SORTING
SQL– Slide 76
USING THE IN CONDITION
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
SELECT ename
FROM emp
WHERE ename LIKE 'S%' ;
SQL– Slide 80
USING THE LIKE CONDITION
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:
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
SQL– Slide 89
SUBSTITUTION VARIABLES
... salary = ? …
… department_id = ? …
... last_name = ? ...
I want
to query
different
values.
SQL– Slide 90
SUBSTITUTION VARIABLES
SQL– Slide 91
USING THE : SUBSTITUTION VARIABLE
▪ Use a variable prefixed with (:) to prompt the user for a value:
SQL– Slide 92
CHARACTER AND DATE VALUES
WITH SUBSTITUTION VARIABLES
SQL– Slide 93
USING THE & SUBSTITUTION VARIABLE
▪ Use the ampersand (&) if you want to reuse the variable value
without prompting the user each time:
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 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 .
SQL– Slide 98
AGGREGATE FUNCTIONS
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 result:
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 result:
▪ GROUP BY
• Enables summarizations across the groups of related data within tables
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 result:
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 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 result
(vs. Query 16):
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 result:
Query 19 result:
Query 20 text: For each product, retrieve the ProductID value and the total
number of product items sold within all sales transactions.
Query 20 result:
Query 21 text: For each product, retrieve the ProductID value and the number
of sales transactions in which the product was sold
Query 21 result:
Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 111
GROUP BY CLAUSE+AVG
DEPTNO AVG(SAL)
30 1566,66667
20 2175
10 2916,66667
▪ 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
Query 22 result:
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 result:
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 result:
Query 26 text: For each product that has more than three items sold within all
sales transactions, retrieve the ProductID value
Query 26 result:
Query 27 text: For each product that was sold in more than one sales
transaction, retrieve the ProductID value
FROM includes
GROUP BY productid
HAVING COUNT(*) > 1;
Query 27 result:
o The query that uses the nested query is referred to as an outer query
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 text: For each product whose product price is below the average
price of all products, retrieve the product ID, product name,
and product price
▪ IN
• Used for comparison of a value with a set of values
Query 29 result:
Query 30 result:
Query 31 result:
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 |
▪ +----+----------+-----+-----------+----------+
▪ 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
Query 41 result:
Query 41 result:
Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 149
INNER JOIN
Query 41 result:
▪ 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
Query 42 result:
Query 43 result:
Query 44 result:
Query 32 result:
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 33:
SELECT productid, productname, vendorname, productprice
FROM product, vendor;
Chapter
Database5 –Systems
Slide - FET- JIH SQL– Slide 160
JOIN
Query 33 result:
Query 35:
SELECT *
FROM product, vendor
WHERE product.vendorid = vendor.vendorid;
▪ Alias
• An alternative and usually shorter name that can be used anywhere
within a query instead of the full relation name
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:
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 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 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 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 result:
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;
▪ 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
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 result:
Query 36 result:
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
SELECT *
FROM student S INNER JOIN Marks M ON S.Roll_No = M.Roll_No;
▪ 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
Query 30 result:
Query 31 result:
▪ 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.
▪ 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
Query 38 result:
▪ 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
Query 39 result:
▪ IS NULL
• Used in queries that contain comparisons with an empty value in a
column of a record
Query 46 text: Retrieve records for all managers who do not have a bonus
Query 46 result:
▪ 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
Query 47 text: Retrieve records for all corporate clients that are currently
renting one or more apartments from us.
Query 47 result:
▪ NOT
• Can be used in conjunction with the condition comparison statements
returning the Boolean values TRUE or FALSE
Query 48 text: Retrieve records for all corporate clients that are currently
not renting one or more apartments from us.
Query 48 result:
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:
•
….
7702 Alaa Salesman 2100
7902 Ford Analyst 3500
7788 Scott Analyst 3500
7701 Nader Analyst 3750
DESCRIBE dept80
INSERTING FROM A QUERY
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;
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 result:
Query 47 text: Retrieve records for all corporate clients that are currently
renting one or more apartments from us.
Query 47 result:
Query 47 text: Retrieve records for all corporate clients that are currently
renting one or more apartments from us.
Query 47 result:
Query A and B
Result:
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