0% found this document useful (0 votes)
52 views50 pages

Introduction To Databases - Brief Sketch-Combined

This document provides an overview of key concepts in database systems, including: - Database management systems (DBMS) allow for online transaction processing and data analytics. - Common data models include the relational model, entity-relationship model, semi-structured model, and object-based model. - Database languages include data definition languages (DDL) to define schemas and data manipulation languages (DML) like SQL to query and manipulate data. - Proper database design includes understanding user needs, choosing a data model, and creating a conceptual schema. - A database engine includes storage management, a query processor, and transaction management components.
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)
52 views50 pages

Introduction To Databases - Brief Sketch-Combined

This document provides an overview of key concepts in database systems, including: - Database management systems (DBMS) allow for online transaction processing and data analytics. - Common data models include the relational model, entity-relationship model, semi-structured model, and object-based model. - Database languages include data definition languages (DDL) to define schemas and data manipulation languages (DML) like SQL to query and manipulate data. - Proper database design includes understanding user needs, choosing a data model, and creating a conceptual schema. - A database engine includes storage management, a query processor, and transaction management components.
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/ 50

10/26/21, 6:25 PM Introduction to Databases 1 – Brief Sketch

Brief Sketch
Notes I take
3:54

Introduction to Databases 1
Chapter 1 Introduction

1.1 Database-management system (DBMS): a collection of interrelated data


and a set of programs to access those data. 

Broadly speaking, there are two modes in which databases are used:

online transaction processing: where a large number of users use the


database, with each user retrieving relatively small amounts of data, and
performing small updates. 

data analytics: the processing of data to draw conclusions, and infer rules or
decision procedures, which are then used to drive business decisions. 

1.2 Data model: a collection of conceptual tools for describing data, data
relationships, data semantics, and consistency constraints. The data models can be
classified into four different categories. 

1- Relational Model: uses a collection of tables to represent both data and the
relationships among those data. Tables are also known as relations. Each tables
contains records of a particular type. Each record type defines a fixed number of
fields, or attributes. The columns of the table correspond to the attributes of the
record type.  

2- Entity-Relationship Model: Uses a collection of basic objects, called


entities, and relationships among these objects. 

3- Semi-structures Data Model: permits specification of data where


individual data items of the same type may have different sets of attributes. This is
in contrast to the models mentioned earlier where every data item of a particular

https://briefsketch97.wordpress.com/2021/10/04/introduction-to-databases-1/ 1/7
10/26/21, 6:25 PM Introduction to Databases 1 – Brief Sketch

type must have the same set of attributes. JSON and Extensible Markup
Language (XML) are semi-structured data representations. 

4- Object-Based Data Model: Standards exist to store objects in relational


tables. Database systems allow procedures to be stores in the database system and
executed by the database system. This can be seen as extending the relational
3:54
model with notions of encapsulations, methods, and object identity. 

In this book, we focus on relational data model. 

Relational Data Model

Data are represented in the form of tables. Each table has multiple columns, and
each column has a unique name. Each row of the table represents one piece of
information. 

1.3 Data Abstraction

Physical level: the lowest level of abstraction describes how the data are actually
stored. 

Logical level: The next higher-level of abstraction describes what data are stored
in the database, and what relationships exist among those data. 

View level: The highest level of abstraction describes only part of the database –
it only shows the relevant information depending on which user is accessing the
database. So it can also “hide” content. 

Instance: the collection of information stored in the database at a particular


moment.

Schema: the overall design of the database. Each database has a physical, logical
and view level schema. 

1.4 Database Languages 

(In practice, DDLs and DMLs are not two separate languages)

Data-definition language (DDL): specifies the database schema, specifies


constraints, and check these constraints every time the database is updated. 

https://briefsketch97.wordpress.com/2021/10/04/introduction-to-databases-1/ 2/7
10/26/21, 6:25 PM Introduction to Databases 1 – Brief Sketch

Types of constraints:

1- Domain Constraints: check if the values are of the correct data type.

2- Referential Integrity: check that a value that appears in one relation for a
given set of attributes also appears in a certain set of attributes in another relation.
3:54
Ex. The dept_name value in a course record must appear in the dept_name
attribute of some record of the department relation.

3- Authorization:  differentiate among the users the type of access they are
permitted. There are 

read authorization: reading, but no modification 

insert authorization: insertion of data, but no modification

update authorization: modification of data, but not deletion of data

delete authorization: deletion of data

The processing of DDL statements generates some output. The output of the DDL
is placed in the data dictionary, which contains metadata. The data dictionary
is a special type of table that can be accessed and updated only by the database
system itself (not a regular user). The database system consults the data dictionary
before reading or modifying actual data. 

SQL provides a rich DDL.

Ex. 

create table department

(dept_name char(20),

  building char(15),

  budget numeric(12, 2));

Data-manipulation language (DML): expresses database queries and


updates. 

https://briefsketch97.wordpress.com/2021/10/04/introduction-to-databases-1/ 3/7
10/26/21, 6:25 PM Introduction to Databases 1 – Brief Sketch

There are basically two types of data-manipulation language: 

1- Procedural DMLs: requires users to specify what data are needed and how to
get those data

2- Declarative DMLs (nonprocedural DMLs): requires users to specify what


3:54
data are needed without specifying how to get those data. 

Query: a statement requesting retrieval of information. 

SQL is nonprocedural (declarative). A query takes as input several tables and


always returns a single table

Ex. 

select instructor.name

from instructor

where instructor.dept_name = ‘History’;

The result of this qurty is a table with a single column laballed name and a set of
rows, each of which contains the name of an instructor whose dept_name is
History. 

SQL does not support actions such as input from users, output to displays, or
communication over the network. Such computations must be written in a host
language, such as C/C++, Java, or Python, with embedded SQL queries that access
the data in the database. To access the database, DML statements need to be sent
from the host to the database where they will be executed. 

1.5 Database Design 

1- characterize fully the data needs of the prospective database users.

2- choose a data model and translate these requirements into a conceptual schema
of the database. The schema provides a detailed overview of the enterprise, and
describes the data and their relationships. 

1.6 Database Engine

https://briefsketch97.wordpress.com/2021/10/04/introduction-to-databases-1/ 4/7
10/26/21, 6:25 PM Introduction to Databases 1 – Brief Sketch

The functional components of a database system can be broadly divided into three
parts:

 1- storage manager: the server, and the amount of storage it contains
(gigabytes, terabytes).
3:54
2- query processor: simplifies and facilitates access to data. 

3- transaction management: allows application developers to treat. sequence


of database accesses as if they were a single unit that either happens in its entirety
or not at all (atomicity).

1.7 Database and Application Architecture 

(use, write) > (query processor) > (storage manager) > (disk storage)

Three-tier architecture: the client machine acts as a front end and does not
contain any direct database calls.Web browsers and mobile applications are the
most commonly used application clients today. 

(front end) > (application server) > (database system) > (access the data)

1.8 Database Users and Administrators

There are three types of database-system users, differentiated by the way they
expect to interact with the system. 

1- Naive users: normal users, usually interact with a forms interface where they
fill appropriate fields of the form. They usually read reports generated from the
database. 

2- Application programmers: computer professionals who write application


programs. 

3- Sophisticated users: interact with the system without writing programs.


They form their requests using a database query language.

https://briefsketch97.wordpress.com/2021/10/04/introduction-to-databases-1/ 5/7
10/26/21, 6:25 PM Introduction to Databases 1 – Brief Sketch

Advertisements

Occasionally, some of your visitors may see an advertisement here,

as well as a Privacy & Cookies banner at the bottom of the page.

You can hide ads completely by upgrading to one of our paid plans.
UPGRADE NOW
DISMISS MESSAGE
3:54

Share this:

 Press This  Twitter  Facebook


Customize buttons


Reblog
Like

Be the first to like this.

Related

Introduction to Databases 2: Introduction to Databases 6.1 Networks 2.2 – 2.6:


The Relational Model – 6.5: Databse Design Using Application Layer
October 4, 2021 the E-R Model October 18, 2021
In "Fall 2021" October 6, 2021 In "Fall 2021"
In "Fall 2021"

Guilherme Soares October 4, 2021 Uncategorized


,
Fall 2021 Introduction to Databases Edit

Published by Guilherme Soares


I’m a Computer Science and Public Relations senior student at Rollins College
with a passion for software engineering, healthy living practices, and social
entrepreneurship. View more posts

https://briefsketch97.wordpress.com/2021/10/04/introduction-to-databases-1/ 6/7
10/26/21, 6:25 PM Introduction to Databases 1 – Brief Sketch

Leave a Reply
Enter your comment here...

3:54

Brief Sketch,
Create a free website or blog at WordPress.com.

https://briefsketch97.wordpress.com/2021/10/04/introduction-to-databases-1/ 7/7
10/26/21, 6:26 PM Introduction to Databases 2: The Relational Model – Brief Sketch

Brief Sketch
Notes I take
3:45

Introduction to Databases 2: The


Relational Model
Mathematics Relational Databases

relation table

tuple (cannot contain duplicates) row

attribute column

2.1 Structure of Relational Databases

Since a table is a collection of such relationships, there is a close correspondence


between the concept of table and the mathematical concept of relation.

In mathematical terminology,

relation: a set of tuples, a table

tuple: is a sequence (or list) of values, which correcponds to a row in a table.

attribute: a column of a table

relation instance: a specific instance of a relation, containing a specific set of


rows.

domain: the set of all permitted/possible values for a given attribute

We require that for all relations r, the domains of all attributes of r be atomic,
that is, an attribute does not have a list as its element, but only one element.

2.2 Database Schema

Relation schema: consists of a list of attributes and their corresponding


domains.

Ex. The schema for the department relation is:

department (dept_name, building, budget)

https://briefsketch97.wordpress.com/2021/10/04/introduction-to-databases-2-the-relational-model/ 1/6
10/26/21, 6:26 PM Introduction to Databases 2: The Relational Model – Brief Sketch

2.3 Keys

No two tuples in a relation are allowed to have exactly the same value for all
attributes.

superkey: a set of one or more attributes that allow us to identify uniquely a


tuple in the relation. Ex. the ID attribute in a relation.

candidate keys: superkeys for which no proper subset is a superkey.


3:45
primary key: a candidate key that is chosen by the database designer as the
principal means of identifying tuples within a relation.

A primary key is listed before the other attributes in the relation schema, and it is
also underlined.

Ex.

classroom (building, room_number, capacity)

foreign key: when an attribute (or a set of attributes) from a relation, r1, can only
have values that are included in the primary key of another relation, r2.
Ex. The attribute dept_name from the realtion instructor can only have values
that are included in the attribute dept_name from the relation department (where
dept_name is the primary key of the relation department).

referencing relation: r1

referenced relation: r2

referential integrity constraint: when an attribute (or set of attributes) from a


relation, r1, can only have the values that are included in another attribute from
another relation, r2. It is a more relaxed version of foreign key.

2.4 Schema Diagrams

In schema diagrams,

Primary keys are underlined.

Foreign key constaints appear as arrows from the foreign key attributes of the
referencing relation to the primary key of the referenced relation.

Referential integrity constraints are indicated by two-headed arrows.

2.5 Relational Query Languages

Query languages can be categorized as imperative, functional, or declarative.

imperative query language: the user instructs the system to perform a specific
sequence of operations on the database to compute the desired result.

functional query language: the computation is expressed as the evaluation of


functions that may operate on data in the database or on the results of other
functions; funcitons are side-effect free, and do not update the program state.

declarative query language: the user describes the desired information


without giving a specific sequence of steps or function calls for obtaining that
information.

https://briefsketch97.wordpress.com/2021/10/04/introduction-to-databases-2-the-relational-model/ 2/6
10/26/21, 6:26 PM Introduction to Databases 2: The Relational Model – Brief Sketch

Pure query languages include: relational algebra, Tuple relational calculus, and
domain relational calculus.

Query languages used in practice include: SQL.

2.6 The Relational Algebra

Relational algebra consists of a set of operations that take one or two relations
3:45
as input and produce a new relation as their result.

Unary operations: select, project, and rename operations. They are called
unary operations because they operate on one relation.

Binary operations: union, Cartesian product, and set difference operations.


They are called binary operations because they operate on pairs of relations.

2.6.1 The Select Operation

The select operation (σ) selects tuples that satisfy a given predicate.

The predicate appears as a subscript to σ.

The argument relation is in parentheses after the σ.

Thus, to select those tuples of the instructor relation where the instructor is in the
“Physics” department, we write:

σdept_name = “Physics”(instructor)

2.6.2 The Project Operation

The project operation (Π) is a unary operation that returns its argument relation,
with certain attributes left out. Any duplicate rows are eliminated.
We list those attributes that we wish to appear in the result as a subscript to Π.

Suppose we want to list all instructors’ ID, name, and salary, but we do not care
about the dept_name.

ΠID, name, salary (instructor)

We may also use expressions to modify the values that appear in the table.
Suppose we want the monthly salary of the professors:

ΠID, name, (salary/12) (instructor)

2.6.3 Composition of Relational Operations

The result of a relational operation is a relation itself. So we can nest relational


operations inside each other.

Suppose we want to find the names of all instructors in the Physics department.
We write:

Πname (σdept_name = “Physics” (instructor))

https://briefsketch97.wordpress.com/2021/10/04/introduction-to-databases-2-the-relational-model/ 3/6
10/26/21, 6:26 PM Introduction to Databases 2: The Relational Model – Brief Sketch

2.6.4 The Cartesian-Product Operation

The Cartesian-product operation creates a table with all possible combinations


from the merning of two tables. It associates every tuple of r1 with every tuple of
r2.

3:45 in
Assume there are n1 tuples is r1 and n2 tuples in r2. Then there are n1 * n2 tuples
r1 X r2.

The Cartesian-product operation (Χ) allows us to combine information from any


two relations. We write the Cartesian product of relations r1 and r2 as r1 X r2.

2.6.5 The Join Operation

The join operation (r⋈θ s) is defined as follows:

r⋈θ s = σθ(r X s)

Thus, σinstructor.ID = teaches.ID (instructor X teaches)

Is the same as: instructor ⋈instructor.ID = teaches.ID teaches.

2.6.6 Set Operations

There are three common operations: union, intersection, and set-difference.

Rules for operations: compatible relations

(1) Input relations have the same number of attributes (arity).

(2) The types of the ith attributes of both input relations must be the same, for
each i.

Union: a table whose tuples are found either only in r1, or only in r2, or in both r1
and r2.

Ex.

Πcourse_id (σsemester = “Fall” ^ year = 2017 (section)) U Πcourse_id (σsemester = “Spring” ^ year
= 2018 (section))

Intersection: A table whose tuples are both in r1 and r2.

Ex.

Πcourse_id (σsemester=”Fall” ^ year=2017 (section)) ∩ Πcourse_id (σsemester=”Spring” ^


year=2018 (section))

Set-difference: A table whose tuples are in one relation, but not in another.

Ex.

Πcourse_id (σsemester=”Fall” ^ year=2017 (section)) – Πcourse_id (σsemester=”Spring” ^


year=2018 (section))

https://briefsketch97.wordpress.com/2021/10/04/introduction-to-databases-2-the-relational-model/ 4/6
10/26/21, 6:26 PM Introduction to Databases 2: The Relational Model – Brief Sketch

2.6.7 The Assignment Operation

The assignment operation, denoted by a left arrow (˿), works like assignment in
programming language. Sometimes it is convenient to assign a relational algebra
expression to temporary relational variables.

2.6.8 The Rename Operation


3:45
Assume that a relational-algebra expression E has arity n. Then, the expression

ρχ(A1, A2, …, An) (E)

returns the result of expression E under the name χ, and with the attributes
renamed to A1, A2, …, An.

Advertisements

Occasionally, some of your visitors may see an advertisement here,

as well as a Privacy & Cookies banner at the bottom of the page.

You can hide ads completely by upgrading to one of our paid plans.
UPGRADE NOW
DISMISS MESSAGE

Share this:

 Press This  Twitter  Facebook


Customize buttons


Reblog
Like

Be the first to like this.

Related

Introduction to Databases 1 Introduction to Databases 3.1 Introduction to Databases 6.1


October 4, 2021 – 3.7: Introduction to SQL – 6.5: Databse Design Using
In "Fall 2021" October 12, 2021 the E-R Model
In "Fall 2021" October 6, 2021
In "Fall 2021"

Guilherme Soares October 4, 2021 Uncategorized


,
Fall 2021 Introduction to Databases Edit

https://briefsketch97.wordpress.com/2021/10/04/introduction-to-databases-2-the-relational-model/ 5/6
10/26/21, 6:26 PM Introduction to Databases 2: The Relational Model – Brief Sketch

Published by Guilherme Soares


I’m a Computer Science and Public Relations senior student at Rollins College
with a passion for software engineering, healthy living practices, and social
entrepreneurship. View more posts
3:45

Leave a Reply
Enter your comment here...

Brief Sketch,
Blog at WordPress.com.

https://briefsketch97.wordpress.com/2021/10/04/introduction-to-databases-2-the-relational-model/ 6/6
10/26/21, 6:26 PM Introduction to Databases 6.1 – 6.5: Databse Design Using the E-R Model – Brief Sketch

Brief Sketch
Notes I take
3:35

Introduction to Databases 6.1 – 6.5:


Databse Design Using the E-R Model
E-R: entity relationship model

6.1 Overview of the Design Process

Creating a database application involves the design of the database schema, design
of the programs that access and update the data, and design of a security scheme
to control access to data.

6.1.1 Design Phases

1- Characterize fully the data needs of the prospective users, specify user
requirements.

2- Choose a data model and translate the user requirements into a conceptual
schema of the database. The conceptual schema specifies the entities, attributes of
entities, relationship among entities, and constraints on the entities and
relationships in the database.

3- Specify the functional requirements. The users describe the kinds of operations
or transactions that will be performed on the data.

4- Implementation:

Logical-design phase: map the conceptual schema defined using the entity-
relationship morel into a relation schema.

Physical design phase: specify the physical features of the database (form of
file organization and choice of index structures).

6.2 The Entity-Relationship Data Model

The E-R model employs three basic concepts: entity sets, relationship sets, and
attributes. The E-R model also has an associated diagrammatic representation, the
E-R diagram.

6.2.1 Entity Sets

entity: a thing or object in the real world that is distinguishable from all other

https://briefsketch97.wordpress.com/2021/10/06/introduction-to-databases-3-databse-design-using-the-e-r-model/ 1/5
10/26/21, 6:26 PM Introduction to Databases 6.1 – 6.5: Databse Design Using the E-R Model – Brief Sketch

objects. An entity has a set of properties, and the values for some set of properties
must uniquely identify an entity.

entity set: a set of entities of the same type that share the same
properties/attributes. It is represented in an E-R diagram by a rectangle.

attributes: descriptive properties possessed by each member of an entity set.


3:35
6.2.2 Relationship Sets

relationship: an association among several entities.

relationship set: a set of relationships of the same type. It is represented by a


diamond in the E-R diagram, which is linked via lines to a number of different
entity sets (rectangles).

Formally, it is a mathematical relation on n ≥ 2 entity sets.

If E1, E2, …, En are entity sets, then a relationship set R is a subset of

{(e1, e2, …, en) | e1 ∈ E1, e2 ∈ E2, …, en ∈ En}

where (e1, e2, …, en) is a relationship instance.

Ex.

44553 (Peltier) advisor 22222 (Einstein)

student entity relationship set instructor entity

(44553, 22222) ∈ advisor

The association between entity sets is referred to as participation. The entity


sets E1, E2, …, En participate in relationship set R.

relationship instance: represents an association between the named entities in


the enterprise modeled.

descriptive attributes: relationships may have descriptive attributes, which is


basically a normal attribute, but for relationships. They are represented in the E-R
diagram by an undivided rectangle, connected to the relationship diamon by a
dashed line.

degree of the relationship set: how many entity sets participate in a


relationship set. We can have binary relationship sets (of degree 2), or ternary
relationship sets (of degree 3), or more.

6.3 Complex Attributes

domain: a set of permitted values for each attribute

An attribute can be characterized by the following attribute types: simple,


composite, single-valued, multivalued, and derived.

simple attributes: do not need to be divided into more than one part

https://briefsketch97.wordpress.com/2021/10/06/introduction-to-databases-3-databse-design-using-the-e-r-model/ 2/5
10/26/21, 6:26 PM Introduction to Databases 6.1 – 6.5: Databse Design Using the E-R Model – Brief Sketch

composite attributes: can be divided into subparts. Ex. first name, last name,
etc. It is denoted by an indentation.

single-valued: one value for a particular entity

multivalued: a value that is a list of values. Ex. list of phone numbers, list of
dependants, etc. It is denoted by curly braces: { multivalued_attribute}

derived attributes: this attribute can be derived from another attribute. Ex. 3:35age,
given birth date; monthly salary, given annual salary.

null: means there is no value for it.

6.4 Mapping Cardinalities

mapping cardinalities: the number of entities to which another entity can be


associated via a relationship set. For a binary relationship set R between entity
sets A and B, the mapping cardinality must be one of the following: one-to-one,
one-to-many, many-to-one, or many-to-may.

one-to-one: An entity in A is associated with at most one entity in B, and an


entity in B is associated with at most one entity in A. Represented by a directed
line from the relationship set to both entity sets.

one-to-many: An entity in A is associated with any number of entities in B. An


entity in B can be associated with at most one entity in A. Represented by a
directed line from the relationship set to the “one” side of the relationship.

many-to-one: An entity in A is associated with at most one entity in B. An entity


in B can be associated with any number of entities in A. Represented by a directed
line from the relationship set to the “one” side of the relationship.

many-to-many: An entity in A is associated with any number of entities in B,


and an entity in B is associated with any number of entities in A. Represented by
an undirected line from the relationship set to both entity sets.

In the E-R diagram notation, we indicate cardinality constraints on a relationship


by drawing either a directed line (→) or an undirected line ( – ) between the
relationship set and the entity set in question.

We can have different levels of participation: total, or partial

total: every entity in E must participate in at least one relationship in R. Ex. every
student needs at least one advisor. Indicated by using double lines.

partial: Some entities in E do not need to participate in R. Ex. an instructor


doesn’t necessarily need to advise any student.

6.5 Primary Key

weak entity set: its existence depends on the existence of an identifying entity
set. It must relate to the identifying entity set via a total, one-to-many relationship
set from the identifying to the weak entity set. It is an entity set that does not have

https://briefsketch97.wordpress.com/2021/10/06/introduction-to-databases-3-databse-design-using-the-e-r-model/ 3/5
10/26/21, 6:26 PM Introduction to Databases 6.1 – 6.5: Databse Design Using the E-R Model – Brief Sketch

a primary key on its own. The primary key of a weak entity set is formed by the
primary key of the strong, identifying entity set, plus the weak entity set’s
discriminator. The discriminator (or partial key) of a weak entity set is the set
of attributes that distinguishes among all the entities of a weak entity set. It is
depicted by a double diamond.
3:35

Advertisements

Occasionally, some of your visitors may see an advertisement here,

as well as a Privacy & Cookies banner at the bottom of the page.

You can hide ads completely by upgrading to one of our paid plans.
UPGRADE NOW
DISMISS MESSAGE

Share this:

 Press This  Twitter  Facebook


Customize buttons


Reblog
Like
Be the first to like this.

Related

Introduction to Databases 1 Introduction to Databases 6.6 Introduction to Databases 4.1


October 4, 2021 – 6.8: Databse Design Using – 4.4: Intermediate SQL
In "Fall 2021" the E-R Model October 25, 2021
October 11, 2021 In "Fall 2021"
In "Fall 2021"

Guilherme Soares October 6, 2021 Uncategorized


,
Fall 2021 Introduction to Databases Edit

https://briefsketch97.wordpress.com/2021/10/06/introduction-to-databases-3-databse-design-using-the-e-r-model/ 4/5
10/26/21, 6:26 PM Introduction to Databases 6.1 – 6.5: Databse Design Using the E-R Model – Brief Sketch

Published by Guilherme Soares


I’m a Computer Science and Public Relations senior student at Rollins College
with a passion for software engineering, healthy living practices, and social
entrepreneurship. View more posts
3:35

Leave a Reply
Enter your comment here...

Brief Sketch,
Blog at WordPress.com.

https://briefsketch97.wordpress.com/2021/10/06/introduction-to-databases-3-databse-design-using-the-e-r-model/ 5/5
10/26/21, 6:26 PM Introduction to Databases 6.6 – 6.8: Databse Design Using the E-R Model – Brief Sketch

Brief Sketch
Notes I take
2:35

Introduction to Databases 6.6 – 6.8:


Databse Design Using the E-R Model
6.6 Removing Redundant Attributes in Entity Sets

Suppose we have entity sets instructor (with attributes including dept_name),


department and a relationship inst_dept relating instructor and department.

The attribute dept_name in the entity instructor is redundant since there is an


explicit relationship inst_dept which relates instructors to departments.

The attribute should be removed from instructor.

6.7 Reducing E-R Diagrams to Relational Schemas

6.7.1 Representation of Strong Entity Sets

Let E be a strong entity set with only simple descriptive attributes.

For schemas derived from strong entity sets, the primary key of the entity set
serves as the primary key of the resulting schema. This follows from the fact that
each tuple in a relation on this schema corresponds to one entity of the entity set
E.

6.7.2 Representation of Strong Entity Sets with Complex Attributes

When a strong entity set has nonsimple attributes, we handle composite attributes
by creating a separate attribute from each of the component attributes.

For a multivalued attribute M, we create a relation schema R with an attribute A


that corresponds to M and attributes corresponding to the primary key of the
entity set or relationship set which M is an attribute.

6.7.3 Representation of Weak Entity Sets

Let A be a weak entity set. Let B be the strong entity set on which A depends. Let
the primary key of B consist of attributes b1, b2, …, bn.

https://briefsketch97.wordpress.com/2021/10/11/introduction-to-databases-6-6-6-8-databse-design-using-the-e-r-model/ 1/4
10/26/21, 6:26 PM Introduction to Databases 6.6 – 6.8: Databse Design Using the E-R Model – Brief Sketch

We represent the entity set A by a relation schema called A with one attribute for
each member of the set:

{a1, a2, …, an} ∪ {b1, b2, …, bn}


2:35
For schemas derived from a weak entity set, the combination of the primary key of
the strong entity set and the discriminator of the weak entity set serves as the
primary key of the schema.

6.8 Extended E-R Features

In this section we discuss the extended E-R features of specialization,


generalization, higher- and lower-level entity sets, attribute inheritance, and
aggregation.

6.8.1 Specialization

An entity set may include subgroupings of entities that are distinct in some way
from other entities in the set. Ex. the entity set person may be further classified as
an employee or student.

Each of these person types is described by a set of attributes that includes all the
attributes of entity set person plus possibly additional attributes.

specialization: the process of designating subgroupings within an entity set.

In terms of an E-R diagram, specialization is depicted by a hollow arrow-head


poiting from the specialized entity to the other entity. We refer to this relationship
as the ISA relationship.

6.8.2 Generalization

To create a generalization, the attributes common between two subclasses must be


given a common name and represented with the higher-level entity.

Generalization is a simple inversion of specialization. Generalization proceeds


from the recognition that a number of entity sets share some common features.

In terms of the E-R diagram, we do not distinguish generalization from


specialization.

6.8.3 Attribute Inheritance

The attributes of the higher-level entity sets are said to be inherited by the lower-

https://briefsketch97.wordpress.com/2021/10/11/introduction-to-databases-6-6-6-8-databse-design-using-the-e-r-model/ 2/4
10/26/21, 6:26 PM Introduction to Databases 6.6 – 6.8: Databse Design Using the E-R Model – Brief Sketch

level entity sets. A subclass also inherits participation in the relationship sets in
which its superclass participates.

6.8.4 Constraints on Specializations

Constraints on which entities can be members of a given lower-level entity set.

2:35
Condition-defined (Ex. All customers over 65 years are members of senior-citizen
entity set; senior-citizen ISA person) vs. user-defined.

Constraints on whether or not entities may belong to more than one lower-level
entity set within a single generalization.

Disjoint: an entity can belong to only one lower-level entity set.

Overlapping: an entity can belong to more than one lower-level entity set.

Completeness constraint: specifies whether or not an entity in the higher-level


entity set must belong to at least one of the lower-level entity sets within a
generalization.
Total: an entity must belong to one of the lower-level entity sets.

Partial: an entity need not belong to one of the lower-level entity sets.

6.8.5 Aggregation
Aggregation: is an abstraction through which relationships are treated as
higher-level entities.

Advertisements

Occasionally, some of your visitors may see an advertisement here,

as well as a Privacy & Cookies banner at the bottom of the page.

You can hide ads completely by upgrading to one of our paid plans.
UPGRADE NOW
DISMISS MESSAGE

Share this:

 Press This  Twitter  Facebook


Customize buttons


Reblog
Like
Be the first to like this.

https://briefsketch97.wordpress.com/2021/10/11/introduction-to-databases-6-6-6-8-databse-design-using-the-e-r-model/ 3/4
10/26/21, 6:26 PM Introduction to Databases 6.6 – 6.8: Databse Design Using the E-R Model – Brief Sketch

Related

Introduction to Databases 6.1 Introduction to Databases 2: Introduction to Databases 4.1


– 6.5: Databse Design Using The Relational Model – 4.4: Intermediate SQL
the E-R Model October 4, 2021 October 25, 2021
October 6, 2021 In "Fall 2021" In "Fall 2021" 2:35
In "Fall 2021"

Guilherme Soares October 11, 2021 Uncategorized


Fall 2021, Introduction to Databases Edit

Published by Guilherme Soares


I’m a Computer Science and Public Relations senior student at Rollins College
with a passion for software engineering, healthy living practices, and social
entrepreneurship. View more posts

Leave a Reply
Enter your comment here...

Brief Sketch,
Create a free website or blog at WordPress.com.

https://briefsketch97.wordpress.com/2021/10/11/introduction-to-databases-6-6-6-8-databse-design-using-the-e-r-model/ 4/4
10/26/21, 6:26 PM Introduction to Databases 3.1 – 3.7: Introduction to SQL – Brief Sketch

Brief Sketch
Notes I take
5:44

Introduction to Databases 3.1 – 3.7:


Introduction to SQL
3.2 Data Definition

The set of relations in a database are specified using a data-definition language


(DDL).

3.2.1 Basic Types

The SQL standard supports a variety of built-in types, including:

char(n): A fixed-length character string with user-specified length n.

varchar(n): A variable-length character string with user-specified maximum


length n.

int: An integer

smallint: A small integer

numeric(p, d): A fixed-point number with user-specified precision. The number


consists of p digits (plus a sign), and d of the p digits are to the right of the decimal
point. Thus, numeric(3, 1) allows 44.5 to be stored exactly, but neither 444.5 nor
0.32 can be stored exactly in a field of this type.

real, double precision: Floating-point and double precision floating-point


numbers with machine-dependent precision

float(n): A floating-point number with precision of at least n digits.

3.2.2 Basic Schema Definition

We define an SQL relation by using the create table command. The following
command creates a relation department in the database:

1 create table department


2    (dept_name   varchar(20),
3     building    varchar(15),
4     budget      numeric(12, 2),
5     primary key (dept_name));

https://briefsketch97.wordpress.com/2021/10/12/introduction-to-databases-3-introduction-to-sql/ 1/10
10/26/21, 6:26 PM Introduction to Databases 3.1 – 3.7: Introduction to SQL – Brief Sketch

The general form of the create table command is:

create table r

(A1 D1,

A2 D2,

…,

An Dn,
5:44
<integrity-constraint1>,

…,

<integrity-constraintk>);

where

r is the name of the relation,

Ai is the name of an attribute in the schema,

Di is the domain of attribute Ai.

SQL supports a number of integrity constraints. For example:

primary key (Aj1, Aj2, …, Ajm): The primary key specification attributes are
required to be nonnull and unique;

foreign key (Aj1, Aj2, …, Ajm) references s: The values of the attributes for any
tuple in the relation must correspond to values of the primary key attributes on
some tuple in relation s.

not null: specifies that the null value is not allowed for that attribute.

Updates to tables:

insert into r values (A1, A2, …, Am)

drop table r; : removes a relation from an SQL database

delete from r; : retains relation r but deletes all tuples in r.

alter table r add A D; : adds attributes to an existing relation. All tuples in the
relation are assigned null as the value for the new attribute

alter table r drop A; : deletes an attribute from a table.

3.3 Basic Structure of SQL Queries

The basic structure of an SQL query consists of three clauses: select, from, and
where. A query takes as its input relations listed in the from clause, operates on
them as specified in the where and select clauses, and then produces a relation
as the result.

A typical SQL query has the form:

1 select A1, A2, ..., An


2 from r1, r2, ..., rm
3 where P

https://briefsketch97.wordpress.com/2021/10/12/introduction-to-databases-3-introduction-to-sql/ 2/10
10/26/21, 6:26 PM Introduction to Databases 3.1 – 3.7: Introduction to SQL – Brief Sketch

Ai: an attribute

Ri: a relation

P: a predicate

The select Clause

The select clause lists the attributes desired in the result of a query. Ex. find5:44
the
names of all instructors:

1 select name
2 from instructor

SQL names are case sensitive.

To force the elimination of duplicates, insert the keyword distinct after select

1 select distinct dept_name


2 from instructor

The keyword all specifies that duplicates should not be removed.

1 select all dept_name


2 from instructor

An asterisk in the select clause denotes “all attributes”

1 select *
2 from instructor

An attribute can be a literal with no from clause. The result is a table with one
column and a single row with value “X”. We can give the column a name using

1 select '437' as FOO

An attribute can be a literal with from clause. The result is a table with one
column and N rows (number of tuples in instructors table), each row with value
“A”

1 select 'A'
2 from instructor

The select clause can contain arithmetic expressions involving the operations +, -,
*, and /, and operating on constants or attributes of tuples.

https://briefsketch97.wordpress.com/2021/10/12/introduction-to-databases-3-introduction-to-sql/ 3/10
10/26/21, 6:26 PM Introduction to Databases 3.1 – 3.7: Introduction to SQL – Brief Sketch

1 select ID, name, salary/12


2 from instructor

We can rename “salary/12” using the as clause

1 select ID, name, salary/12 as monthly_salary 5:44


2 from instructor

The where Clause

The where clause specifies conditions that the result must satisfy. Ex. to find all
instructors in the Computer Science department

1 select name
2 from instructor
3 where dept_name = "Computer Science"

Comparison results can be combined using the logical connectives and, or, and
not. Ex. To find all instructors in the Computer Science department with salary
greater than $80,0000

1 select name
2 from instructor
3 where dept_name = "Computer Science" and salary > 80000

The from Clause

The from clause lists the relations involved in the query. Ex. Find the Cartesian
product instructor X teaches

1 select *
2 from instructor, teaches

The Cartesian product is not very useful by itself, but it is useful when combined
with the where clause condition. Ex. Find the names of all instructors who have
taught some course, and the course_id

1 select name, course_id


2 from instructor, teaches
3 where instructor.ID = teaches.ID

Ex. Find the names of all instructors in the Art department who have taught some
course and the course_id

https://briefsketch97.wordpress.com/2021/10/12/introduction-to-databases-3-introduction-to-sql/ 4/10
10/26/21, 6:26 PM Introduction to Databases 3.1 – 3.7: Introduction to SQL – Brief Sketch

1 select name, course_id


2 from instructor, teaches
3 where instructor.ID = teaches.ID and instructor.dept_nam

3.4 Additional Basic Operations

Pattern matching

5:44
Pattern matching can be performed on strings using the operator like. We
describe patterns by using two special characters:

Percent (%): The % character matches any substring

Underscore ( _ ): The _ character matches any character.

Patterns are case sensitive.

Consider the following examples:

“Intro%” matches any string beginning with “Intro”

“%Comp%” matches any string containing “Comp” as a substring, for example,


“Intro to Computer Science” and “Computational Biology”

“___” matches any string with exactly three caracters.

“___%” matches any string of at least three characters

like “ab\%cd%” escape “\” matches all strings beginning with “ab%cd”

like “ab\\cd%” escape matches all strings beginning with “ab\cd”.

Ordering the Display of Tuples

The order by clause causes the tuples in the result of a query to appear in sorted
order. To list in alphabetic order all instructors in the Physics department, we
write:

1 select name
2 from instructor
3 where dept_name = "Physics"
4 order by name;

By default, the order by clause lists items in ascending order. To specify the sort
order, we may specify desc for descending order and asc for ascending order.

1 select *
2 from instructor
3 order by salary desc, name asc

Where-Clause Predicates

SQL includes a between comparison operator. Ex. Find the names of all
instructors with salary between $90,000 and $100,000 (that is, >= $90,000 and
<= $100,000)

https://briefsketch97.wordpress.com/2021/10/12/introduction-to-databases-3-introduction-to-sql/ 5/10
10/26/21, 6:26 PM Introduction to Databases 3.1 – 3.7: Introduction to SQL – Brief Sketch

1 select name
2 from instructor
3 where salary between 90000 and 100000

3.5 Set Operations


5:44
The SQL operations union, interset, and except operate on relations and
correspond to the mathematical set operations ∪, ∩, and -.

union: the set of all courses taught in either the Fall of 2017 or in Spring 2018, or
both:

1 (select course_id
2 from section
3 where semester = "Fall" and year = 2017)
4 union
5 (select course_id
6 from section
7 where semester = "Spring" and year = 2018);

The union operation automatically eliminates duplicates. If we want to retain all


duplicates, we must write union all in place of union.

intersect: the set of all courses taught in both the Fall 2017 and Spring 2018:

1 (select course_id
2 from section
3 where semester = "Fall" and year = 2017)
4 intersect
5 (select course_id
6 from section
7 where semester = "Spring" and year = 2018);

If we want to retain duplicates, we must write intersect all in place of intersect.

except: the courses taught in the Fall 2017 semester but not in the Spring 2018
semester

https://briefsketch97.wordpress.com/2021/10/12/introduction-to-databases-3-introduction-to-sql/ 6/10
10/26/21, 6:26 PM Introduction to Databases 3.1 – 3.7: Introduction to SQL – Brief Sketch

1 (select course_id
2 from section
3 where semester = "Fall" and year = 2017)
4 except
5 (select course_id
6 from section
7 where semester = "Spring" and year = 2018); 5:44

If we want to retain duplicates, we must write except all in place of except.

3.7 Aggregate Functions

Aggregate functions are functions that take a collection (a set or multiset) of


values as input and return a single value. SQL offers five standard aggregate
functions:

Average: avg

Minimum: min

Maximum: max

Total: sum

Count: count

Find the average salary in each department

1 select dept_name, avg(salary) as avg_salary


2 form instructor
3 group by dept_name;

Sometimes we want to eliminate duplicates when we use an aggregate function.


For this, we use the word distinct in the aggregate expression.

Ex: Find the total number of instructors who teach a course in the Spring 2018
semester.

1 select count (distinct ID)


2 from teaches
3 where semester = "Spring" and year = 2018

Because we wrote the word distinct, the instructors that teach more than one
course in that semester will count as only 1.

To find the number of tuples in a relation we write

1 select count(*)
2 from course

https://briefsketch97.wordpress.com/2021/10/12/introduction-to-databases-3-introduction-to-sql/ 7/10
10/26/21, 6:26 PM Introduction to Databases 3.1 – 3.7: Introduction to SQL – Brief Sketch

Aggregation with Grouping

We may want to apply an aggregate function to a group of sets of tuples. The


attribute(s) given in the group by clause are used to form groups. Tuples with the
same value on all attributes are placed in one group.

Attributes in select clause outside of aggregate functions must appear in group


5:44
by list.

Find the number of instructors in each department who teach a course in the
Spring 2018 semester

1 select dept_name, count(distinct ID) as instr_count


2 from instructor, teaches
3 where instructor.ID = teaches.ID and semester = "Spring"
4 group by dept_name;

Find the number of instructors in each department who teach a course in the
Spring 2018 semester. For this, we need to join the teaches and instructor
relations.

1 select dept_name, count(distinct ID) as instr_count


2 from instructor, teaches
3 where instructor.ID = teaches.ID and semester = "Spring"
4 group by dept_name

The having Clause

When we want conditions to apply to groups, not to tuples. The having clause is
applied when a condition does not apply to a single tuple, but rather applies to
each group constructed by the group by clause.

SQL applies predicates in the having clause after groups have been formed.

For example, we might be interested only in the departments that have an average
salary higher than $42,000.

1 select dept_name, avg(salary) as avg_salary


2 from instructor
3 group by dept_name
4 having avg(avg_salary) > 42000;

As with the select clause, any attribute that is present in the having clause
without being aggregated must appear in the group by clause, otherwise the

https://briefsketch97.wordpress.com/2021/10/12/introduction-to-databases-3-introduction-to-sql/ 8/10
10/26/21, 6:26 PM Introduction to Databases 3.1 – 3.7: Introduction to SQL – Brief Sketch

query is erroneous.

To illustrate the use of both a having and a where clause in the same query, we
consider: “For each course section offered in 2017, find the average total credits
(tot_cred) of all students enrolled in the section, if the section has at least 2
students” 5:44

1 select course_id, semester, year, avg(tot_cred)


2 from student, takes
3 where student.ID = takes.ID and year = 2017
4 group by course_id, semester, year
5 having count(ID) >= 2

Aggregation with Null and Boolean Values

The SQL standard says that the aggregate operators should ignore null values in
its input.

Advertisements

Occasionally, some of your visitors may see an advertisement here,

as well as a Privacy & Cookies banner at the bottom of the page.

You can hide ads completely by upgrading to one of our paid plans.
UPGRADE NOW
DISMISS MESSAGE

Share this:

 Press This  Twitter  Facebook


Customize buttons


Reblog
Like
Be the first to like this.

Related

Introduction to Databases 4.1 Introduction to Databases 1 Introduction to Databases 6.1


– 4.4: Intermediate SQL October 4, 2021 – 6.5: Databse Design Using
October 25, 2021 In "Fall 2021" the E-R Model
In "Fall 2021" October 6, 2021
In "Fall 2021"

https://briefsketch97.wordpress.com/2021/10/12/introduction-to-databases-3-introduction-to-sql/ 9/10
10/26/21, 6:26 PM Introduction to Databases 3.1 – 3.7: Introduction to SQL – Brief Sketch

Guilherme Soares October 12, 2021 Uncategorized


,
Fall 2021 Introduction to Databases Edit

5:44
Published by Guilherme Soares
I’m a Computer Science and Public Relations senior student at Rollins College
with a passion for software engineering, healthy living practices, and social
entrepreneurship. View more posts

Leave a Reply
Enter your comment here...

Brief Sketch,
Create a free website or blog at WordPress.com.

https://briefsketch97.wordpress.com/2021/10/12/introduction-to-databases-3-introduction-to-sql/ 10/10
10/26/21, 6:26 PM Introduction to Databases 3.8 – 3.9: Introduction to SQL – Brief Sketch

Brief Sketch
Notes I take
6:30

Introduction to Databases 3.8 – 3.9:


Introduction to SQL
3.8 Nested Subqueries

A subquery is a select-from-where expression that is nested within another


query.

A common use of subqueries is to perform tests for set memberbership, make set
comparisons, and determine set cardinality by nesting subqueries in the where
clause.

3.8.1 – 3.8.4: nested subqueries in the where clause

3.8.5: nested subqueries in the from clause

3.8.7: scalar subqueries and how they can appear wherever an expression
returning a value can occur

3.8.1 Set Membership

SQL allows testing tuples for membership in a relation.

in: The in connective tests for set membership, where the set is a collection of
values produced by a select clause.

Ex. Find all the courses taught in both the Fall 2017 and Spring 2018 semesters.

We can take the approach of finding all courses taught in Fall 2017 and that are
also members of the set of courses taught in Spring 2018. We do this by nesting a
subquery in the where clause of an outer query.

https://briefsketch97.wordpress.com/2021/10/15/introduction-to-databases-3-8-3-9-introduction-to-sql/ 1/12
10/26/21, 6:26 PM Introduction to Databases 3.8 – 3.9: Introduction to SQL – Brief Sketch

1 select distinct course_id


2 from section
3 where semester = "Fall" and year = 2017 and
4   course_id in (select course_id
5     from section
6     where semester = "Spring" and year = 2018)
6:30
We can also use the not it construct to achieve similar results.

Ex. Find all the courses taught in the Fall 2017 semester but not in the Spring 2018
semester

1 select distinct course_id


2 from section
3 where semester = "Fall" and year = 2017 and
4   course_id not in (select course_id
5     from section
6     where semester = "Spring" and year = 2018)

We can also use the in and not in operators on enumerated sets.

Ex. Find the instructors who are neither Mozart nor Einstein

1 select distinct name


2 from instructor
3 where name not in ("Mozart", "Einstein")

In the preceding examples, we tested membership in a one-attribute relation. We


can also test for membership in an arbitrary relation in SQL.

Ex. Find the total number of distinct students who have taken course sections
taught by the instructor with ID 110011

1 select count(distinct ID)


2 from takes
3 where (course_id, sec_id, semester, year )
4   in (select course_id, sec_id, semester, year
5       from teaches
6       where teaches.ID = "110011")

3.8.2 Set Comparison


Consider “Find the names of all instructors whose salary is greater than at least
one instructor in the Biology department”.

https://briefsketch97.wordpress.com/2021/10/15/introduction-to-databases-3-8-3-9-introduction-to-sql/ 2/12
10/26/21, 6:26 PM Introduction to Databases 3.8 – 3.9: Introduction to SQL – Brief Sketch

The phrease “greater than at least one” is represented in SQL by “> some“.

This construct allows us to rewrite the query in a form that resembles closely our
formulation of the query in English

1 select name 6:30


2 from instructor
3 where salary > some (select salary
4                      from instructor
5                      where dept_name = "Biology")

That subquery generates the set of all salary values of all instructors in the Biology
department.

The > some comparison in the where clause is true if the salary value of the
tuple is greater than at least one member of the set of all salary values for
instructors in Biology.

SQL also allows < some, <= some, >= some, = some, and <> some
comparisons, where = some is identical to in.

Now let’s find the names of all instructors that have a salary value greater than
that of each instructor in the Biology department.

The construct > all corresponds to the phrase “greater than all”.

1 select name
2 from instructor
3 where salary > all (select salary
4                      from instructor
5                      where dept_name = "Biology")

As for some, SQL allows < all, <= all, >= all, = all, and <> all comparisons,
where <> all is identical to not in.

Another examples of set comparisons is: “Find the departments that have the
highest average salary”.

We begin by finding tall average salaries, and then nest it as a subquery of a larger
query that finds those departments for which the average salary is greater than or
equal to all average salaries:

https://briefsketch97.wordpress.com/2021/10/15/introduction-to-databases-3-8-3-9-introduction-to-sql/ 3/12
10/26/21, 6:26 PM Introduction to Databases 3.8 – 3.9: Introduction to SQL – Brief Sketch

1 select dept_name
2 from instructor
3 group by dept_name
4 having avg(salary) >= all (select avg(salary)
5                            from instructor
6                            group by dept_name)
6:30
3.8.3 Test for Empty Relations

SQL includes a construct for testing whether a subquery has any tuples in its
result.

exists: returns true if the argument subquery is nonempty.

Using the exists construct, we can write the query: “Find all courses taught in
both the Fall 2017 semester and in the Spring 2018 semester” in still another way:

1 select course_id
2 from section as S
3 where semester = "Fall" and year = 2017 and
4   exists (select *
5     from section as T
6     where semester = "Spring" and year = 2018 and
7       S.course_id = T.course_id)

A correlation name from an outer query (S in the above query), can be used in a
subquery in the where clause.

correlated subquery: a subquery that uses a correlation name from an outer


query.

To illustrate the not exists operator, consider the query “Find all students who
have taken all courses offered in the Biology department”.

1 select S.ID, S.name


2 from student as S
3 where not exists ((select course_id
4                    from course
5                    where dept_name = "Biology")
6                    except
7                   (select T.course_id
8                    from takes as T
9                    where S.ID = T.ID))

https://briefsketch97.wordpress.com/2021/10/15/introduction-to-databases-3-8-3-9-introduction-to-sql/ 4/12
10/26/21, 6:26 PM Introduction to Databases 3.8 – 3.9: Introduction to SQL – Brief Sketch

The first subquery finds the set of all courses offered in the Biology department.

The second subquery fids all the courses that student S.ID has taken.

The outer select takes each student and tests whether the set of all courses that
the student has taken contains the set of all courses offered in the Biology 6:30
department.

Ex. Find the total number of (distinct) students who have taken course sections
taught by the instructor with ID 110011

1 select count (distinct ID)


2 from takes
3 where exists (select course_id, sec_id, semester, year
4               from teaches
5               where teaches.ID = "110011"
6                 and takes.course.id = teaches.course_id
7                 and takes.sec_id = teaches.sec_id
8                 and takes.semester = teaches.semester
9                 and takes.year = teaches.year
10               )

3.8.4 Test for the Absence of Duplicate Tuples

SQL includes a Boolean function for testing whether a subquery has duplicate
tuples in its result. The unique construct returns the value true if the argument
subquery contains no duplicate tuples.

Ex. Find all courses that were offered at most once in 2017

1 select T.course_id
2 from course as T
3 where unique (select R.course_id
4               from section as R
5               where T.course_id = R.course_id and
6               R.year = 2017)

If a course was not offered in 2017, the subquery would return an empty result,
and the unique predicate would evaluate to true on the empty set.

We can test for the existence of duplicate tuples in a subquery by using the not
unique construct.

Ex. Find all courses that were offered at least twice in 2017

https://briefsketch97.wordpress.com/2021/10/15/introduction-to-databases-3-8-3-9-introduction-to-sql/ 5/12
10/26/21, 6:26 PM Introduction to Databases 3.8 – 3.9: Introduction to SQL – Brief Sketch

1 select T.course_id
2 from course as T
3 where not unique (select R.course_id
4                   from section as R
5                   where T.course_id = R.course_id and
6                   R.year = 2017)
6:30
3.8.5 Subqueries in the From Clause

SQL allows a subquery expression to be used in the from clause.

Ex. Find the average instructors’ salaries of those departments where the average
salary is greater than $42,000

1 select dept_name, avg_salary


2 from (select dept_name, avg(salary) as avg_salary
3       from instructor
4       group by dept_name)
5       as dept_avg(dept_name, avg_salary)
6 where avg_salary > 42000

The subquery generates a relation consisting of the names of all departments and
their corresponding average instructors’ salaries. The attributes of the subquery
result can be used in the outer query.

We can also give the subquery result relation a name, and rename the attributes,
using the as clause.

Another example: Find the maximum across all departments of the total of all
instructors’ salaries in each department

1 select max(tot_salary)
2 from (select dept_name, sum(salary)
3       from instructor
4       group by dept_name)
5       as dept_total(dept_name, tot_salary)

3.8.6 The With Clause

The with clause provides a way of defining a temporary relation whose definition
is available only to the query in which the with clause occurs.

Ex. Find those departments with the maximum budget

https://briefsketch97.wordpress.com/2021/10/15/introduction-to-databases-3-8-3-9-introduction-to-sql/ 6/12
10/26/21, 6:26 PM Introduction to Databases 3.8 – 3.9: Introduction to SQL – Brief Sketch

1 with max_budget(value) as
2      (select max(budget)
3       from department)
4 select budget
5 from department, max_budget
6 where department.budget = max_budget.value;
6:30
The with clause in the query defines the temporary relation max_budget
containing the results of the subquery defining the relation.

Another example: Find all departments where the total salary is greater than the
average of the total salary at all departments

1 with dept_total (dept_name, value) as


2   (select dept_name, sum(salary)
3    from instructor
4    group by dept_name),
5  dept_total_avg(value) as
6    (select avg(value)
7    from dept_total)
8 select dept_name
9 from dept_total, dept_total_avg
10 where dept_total.value > dept_total value.

3.8.7 Scalar Subqueries

Subqueries in the select clause.

SQL allows subqueries to occur wherever an expression returning a value is


permitted, provided the subquery returns only one tuple containing a single
attribute.

Ex. List all departments along with the number of instructors in each department

1 select dept_name,
2    (select count(*)
3     from instructor
4     where department.dept_name = instructor.dept_name)
5     as num_instructors
6 from department

correlation variables: attributes of relations in the from clause of the outer


query.

https://briefsketch97.wordpress.com/2021/10/15/introduction-to-databases-3-8-3-9-introduction-to-sql/ 7/12
10/26/21, 6:26 PM Introduction to Databases 3.8 – 3.9: Introduction to SQL – Brief Sketch

3.9 Modification of the Database

3.9.1 Deletion

We cannot delete particular attributes, we can only delete tuples.

SQL expresses a deletion by


6:30
1 delete from r
2 where P;

P: a predicate

r: a relation

delete: finds all tuples t in r for which P(t) is true, and then deletes them from r.

If the where clause is omitted, all tuples in r are deleted.

Ex. Delete all instructors

1 delete form instructor

Ex. Delete all tuples in the instructor relation pertaining to instructors in the
Finance department

1 delete from instructor


2 where dept_name = "Finance";

Ex. Delete all instructors with a salary between $13,000 and $15,000

1 delete from instructor


2 where salary between 13000 and 15000

Ex. Delete all tuples in the instructor relation for those instructors associated with
a department located in the Watson building.

1 delete from instructor


2 where dept_name in (select dept_name
3                     from department
4                     where building = "Watson")

This delete request first finds all departments located in Watson and then deletes
all instructor tuples pertaining to those departments.

3.9.2 Insertion

To insert data into a relation, we either specify a tuple to be inserted or write a

https://briefsketch97.wordpress.com/2021/10/15/introduction-to-databases-3-8-3-9-introduction-to-sql/ 8/12
10/26/21, 6:26 PM Introduction to Databases 3.8 – 3.9: Introduction to SQL – Brief Sketch

query whose result is a set of tuples to be inserted.

Ex. Add a new tuple to course

1 insert into course


2 values ('CS-473', 'Database Systems', 'Comp. Sci.', 4)
6:30

Or, equivalently

1 insert into course(course_id, title, dept_name, credits)


2 values ('CS-473', 'Database Systems', 'Comp. Sci.', 4)

More generally, we might want to insert tuples on the bases of the result of a
query.

Ex. Make each student in the Music department who has earned more than 144
credit hours an instructor in the Music department with a salary of $18,000.

1 insert into instructor


2    select ID, name, dept_name, 18000
3    from student
4    where dept_name = "Music" and total_cred > 144

3.9.3 Updates

In certain situations, we may wish to change a value in a tuple without changing


all values in the tuple.

Ex. Give everyone a 5% raise

1 update instructor
2 set salary = salary * 1.05

The preceding update is applied once to each of the tuples in the instructor
relation.

Another ex. Increase salary only to instructors with a salary of less than $70,000.

1 update instructor
2 set salary = salary * 1.05
3 where salary < 70000

As with insert and delete, a nested select within an update statement may
reference the relation that is being updated.

https://briefsketch97.wordpress.com/2021/10/15/introduction-to-databases-3-8-3-9-introduction-to-sql/ 9/12
10/26/21, 6:26 PM Introduction to Databases 3.8 – 3.9: Introduction to SQL – Brief Sketch

Another ex. Give a 5% raise to instructors whose salary is less than average

1 update instructor
2 set salary = salary * 1.05
3 where salary < (select avg(salary) 6:30
4                 from instructor)

case: SQL provides a case construct that we can use to perform multiple updates,
avoiding false updates

1 update instructor
2 set salary = case
3                 when salary <= 10000 then salary * 1.05
4                 else salary * 1.03
5              end

The general form of the case statement is

1 case
2    when pred1 then result1
3    when pred2 then result2
4    ...
5    when predn then resultn
6    else result0
7 end

Updates and subqueries

Ex. Set the tot_cred attribute of each student tuple to the sum of the credits of
courses successfully completed by the student.

1 update student
2 set tot_cred = (
3    select sum(credits)
4    from takes, course
5    where student.ID = takes.ID and
6       takes.course_id = course.course_id and
7       takes.grade <> 'F' and
8       takes.grade is not null)

https://briefsketch97.wordpress.com/2021/10/15/introduction-to-databases-3-8-3-9-introduction-to-sql/ 10/12
10/26/21, 6:26 PM Introduction to Databases 3.8 – 3.9: Introduction to SQL – Brief Sketch

Advertisements

Occasionally, some of your visitors may see an advertisement here,

as well as a Privacy & Cookies banner at the bottom of the page.

You can hide ads completely by upgrading to one of our paid plans.
UPGRADE NOW
DISMISS MESSAGE
6:30

Share this:

 Press This  Twitter  Facebook


Customize buttons


Reblog
Like

Be the first to like this.

Related

Introduction to Databases 4.1 Introduction to Databases 3.1 Introduction to Databases 2:


– 4.4: Intermediate SQL – 3.7: Introduction to SQL The Relational Model
October 25, 2021 October 12, 2021 October 4, 2021
In "Fall 2021" In "Fall 2021" In "Fall 2021"

Guilherme Soares October 15, 2021 Uncategorized


,
Fall 2021 Introduction to Databases Edit

Published by Guilherme Soares


I’m a Computer Science and Public Relations senior student at Rollins College
with a passion for software engineering, healthy living practices, and social
entrepreneurship. View more posts

https://briefsketch97.wordpress.com/2021/10/15/introduction-to-databases-3-8-3-9-introduction-to-sql/ 11/12
10/26/21, 6:26 PM Introduction to Databases 3.8 – 3.9: Introduction to SQL – Brief Sketch

Leave a Reply
Enter your comment here...

6:30

Brief Sketch,
Create a free website or blog at WordPress.com.

https://briefsketch97.wordpress.com/2021/10/15/introduction-to-databases-3-8-3-9-introduction-to-sql/ 12/12
10/26/21, 6:27 PM Introduction to Databases 4.1 – 4.4: Intermediate SQL – Brief Sketch

Brief Sketch
Notes I take
3:18

Introduction to Databases 4.1 – 4.4:


Intermediate SQL
Intermediate SQL

More complex forms of SQL queries, view definition, transactions, integrity


constraints, more details regarding SQL data definition, and authorization.

4.1 Join Expressions

4.1.1 The Natural Join

The natural join operation operates on two relations and produces a reliation as
the result.

The natural join considers only those pairs of tuples with the same value on those
attributes that appear in the schemas of both relations.

So,

1 select name, course_id


2 from student, takes
3 where student.ID = takes.ID;

is the same as, *assuming student and takes have no other common attribute
except for ID.

1 select name, course_id


2 from student natural join takes;

There is a danger, however, of using natural join, which is when more than one
column attribute names match.

join … using

When we use the using keyword, we specify which attributes we want to join in,

https://briefsketch97.wordpress.com/2021/10/25/introduction-to-databases-4-1-4-4-intermediate-sql/ 1/6
10/26/21, 6:27 PM Introduction to Databases 4.1 – 4.4: Intermediate SQL – Brief Sketch

and all others are ignored.

1 select name, title


2 from (student natural join takes) join course using (cou

4.1.2 Join Conditions


3:18
The on condition allows a general predicate over the relations being joined.

This predicate is written like a where clause predicate.

1 select *
2 from student join takes on student.ID = takes.ID

4.1.3 Outer Joins

The outer join operation preserves the tuples that would be lost in a join by
creating tuples in the result containing null values.

left outer join preserves tuples only in the relation named before the left outer
join operation.

right outer join preserves tuples only in the relation named after the right
outer join operation.

4.1.4 Join Types and Conditions

inner join is the same as join.

Join types Join conditions

(inner) join natural

left outer join on < predicate >

right outer join using (A1, A2, …, An)

(full) outer join

4.2 Views

4.2.1 View Definition

We define a view in SQL by using the create view command.

To define a view, we must give the view a name and state the query that computes

https://briefsketch97.wordpress.com/2021/10/25/introduction-to-databases-4-1-4-4-intermediate-sql/ 2/6
10/26/21, 6:27 PM Introduction to Databases 4.1 – 4.4: Intermediate SQL – Brief Sketch

the view.

The form of the create view command is:

create view v as < query expression >;

Consider how a clerk needs to access all data in the instructor relation, except
3:18
salary. A view of relation faculty can be made available to the clerk, with the view
defined as follows:

1 create view faculty as


2 select ID, name, dept_name
3 from instructor;

The view relation conceptually contains the tuples in the query result, but it is not
precomputed and stored. Instead, the database stores the query expression
associated with the view relation.

4.2.2 Using Views in SQL Queries

View names may appear in a query any place where a relation name may appear.

The attribute names of a view can be specified explicitly as follows:

1 create view departments_total_salary(dept_name, total_sa


2 select dept_name, sum(salary)
3 from instructor
4 group by dept_name;

4.2.3 Materialized Views

If a tuple is added or deleted from a relation, the result of the query defining the
view would change, and the materialized view’s contents must be updated.

The process of keeping the materialized view up-to-date is called materialized


view maintenance (or view maintenance).

4.2.4 Update of a View

In general, an SQL view is said to be updatable if the following conditions are all
satisfied by the query defining the view:

– The from clause has only one database relations

– The select clause contains only attribute names of the relation and does not
have any axpressions, aggregates, or distinct specificiation.

– Any attribute not listed in the select clause can be set to null.

– The query does not have a group by or having clause.

https://briefsketch97.wordpress.com/2021/10/25/introduction-to-databases-4-1-4-4-intermediate-sql/ 3/6
10/26/21, 6:27 PM Introduction to Databases 4.1 – 4.4: Intermediate SQL – Brief Sketch

4.3 Transactions

A transaction consists of a sequence of query and/or update statements. The


SQL standard specifies that a transaction begins implicitly when an SQL statement
is executed.

Atomic transaction
3:18
Either fully executed or rolled back as if it never occured.

4.4 Integrity Constraints

Integrity constraints ensure that changes made to the database by authorized


users so not result in a loss of data consistency.

4.4.1 Constraints on a Sing Relation

In addition to the primary-key constraint, there are a number of other ones that
can be included in the create table command.

The allowed integrity constraints include

– not null

– unique

– check( < predicate >)

4.4.2 Not Null Constraint

name varchar(20) not null

4.4.3 Unique Constraint

unique(Aj1, Aj2, …, Ajm)

The unique specification says that attributes Aj1, Aj2, …, Ajm form a superkey; that
is, no two tuples in the relation can be equal on all the listed attributes.

4.4.4 The Check Clause

check (semester in (‘Fall’, ‘Winter’, ‘Spring’, ‘Summer’));

The clause check( P ) specifies a predicate P that must be satisfied by every tuple
in a relation.

A common use of check is to ensure that attribute values satisfy specified


conditions.

4.4.5 Referential Integrity

foreign key (dept_name) references department

https://briefsketch97.wordpress.com/2021/10/25/introduction-to-databases-4-1-4-4-intermediate-sql/ 4/6
10/26/21, 6:27 PM Introduction to Databases 4.1 – 4.4: Intermediate SQL – Brief Sketch

Foreign keys can be specified as part of the SQL create table statement by using
the foreign key clause.

Ensures that a value that appears in one relation for a given set of attributes also
appears for a certain set of attributes in another relation.
3:18

Ex: If Biology is a department name appearing in one of the tuples in the


instructor relation, then there exists a tuple in the department relation for
Biology.

Let A be a set of attributes.

Let R and S be two relations that contain attributes A and where A is the primary
key of S.

A is said to be a foreign key of R if for any values of A appearing in R these values


also appear in S.

Advertisements

Occasionally, some of your visitors may see an advertisement here,

as well as a Privacy & Cookies banner at the bottom of the page.

You can hide ads completely by upgrading to one of our paid plans.
UPGRADE NOW
DISMISS MESSAGE

Share this:

 Press This  Twitter  Facebook


Customize buttons


Reblog
Like
Be the first to like this.

Related

Introduction to Databases 3.8 Introduction to Databases 3.1 Introduction to Databases 2:


– 3.9: Introduction to SQL – 3.7: Introduction to SQL The Relational Model
October 15, 2021 October 12, 2021 October 4, 2021
In "Fall 2021" In "Fall 2021" In "Fall 2021"

https://briefsketch97.wordpress.com/2021/10/25/introduction-to-databases-4-1-4-4-intermediate-sql/ 5/6
10/26/21, 6:27 PM Introduction to Databases 4.1 – 4.4: Intermediate SQL – Brief Sketch

Guilherme Soares October 25, 2021 Uncategorized


Fall 2021, Introduction to Databases Edit

Published by Guilherme Soares 3:18

I’m a Computer Science and Public Relations senior student at Rollins College
with a passion for software engineering, healthy living practices, and social
entrepreneurship. View more posts

Leave a Reply
Enter your comment here...

Brief Sketch,
Blog at WordPress.com.

https://briefsketch97.wordpress.com/2021/10/25/introduction-to-databases-4-1-4-4-intermediate-sql/ 6/6

You might also like