Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
23 views63 pages

Advance Database Topics

This document serves as a learning packet for students to become proficient in Database Administration, covering topics such as database management systems, data hierarchy, and SQL operations. It outlines the structure of the course, including online and offline schedules, and provides detailed information on the advantages and disadvantages of physical versus electronic databases. Additionally, it introduces key concepts like entity-relationship diagrams and the functions of a DBMS, emphasizing the importance of data organization and management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views63 pages

Advance Database Topics

This document serves as a learning packet for students to become proficient in Database Administration, covering topics such as database management systems, data hierarchy, and SQL operations. It outlines the structure of the course, including online and offline schedules, and provides detailed information on the advantages and disadvantages of physical versus electronic databases. Additionally, it introduces key concepts like entity-relationship diagrams and the functions of a DBMS, emphasizing the importance of data organization and management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

People will crave for knowledge but

INTRODUCTION
it’s not enough. You must crave for This learning packet will guide the
wisdom more than any other thing student/learner how to become a Database
but not bigger than love for love is Administrator (DBA) a person who will
not a thing, its divine. organize, store and retrieve data.
-R. Orquesta

Database Management System


TOPIC PAGE

The concept of storing and retrieving 3

The purpose of database and its types 4

The advantages and disadvantages of Physical and Electronic Database 5

Database Management 7

Entity Relationship Diagram 8

The concept of Primary Key and Foreign Key and Data Types 14

Different types of relationship 19

Structured Query Language as general electronic database language 33

SQL : Insert = Inserting or adding new information into the electronic database 35

SQL : Select = Retrieving or viewing information from the electronic database 38

SQL : Update = Editing an existing record in the electronic database 37

SQL : Delete = Removing specific record/s from the electronic database 37

Other Structured Query 38

1
General Instructions

This course adapts the Blended Learning Modality of each students shall attend online classes and shall
submit their output and present the same online or through pre-recorded means. In the event that the
circumstances require the students to attend in a physical class, they will be scheduled by batch subject to
health and security protocols being implemented by the school.

As such this Learner’s Manual was prepared in order to facilitate the delivery of this course. The following
symbols will be used to identify the phases of learning.

When you see this symbol it means you have to read a Text File or PDF on your drive or online
for additional instructions and learning.

When you see this symbol it means you have to watch a Video File on your drive or online for
additional instructions and learning.

When you see this symbol it means you have to self-study on a given learning materials for a
possible oral recitation or a quiz on the next face to face or online session.

When you see this symbol it means you have to attend an online session for additional class
discussion or learning instructions. (Refer to the schedule given in your class schedules)

When you see this symbol it means you have to attend a face to face session for additional class
discussion or learning instructions. (Refer to the schedule given in your class schedules)

When you see this symbol it means you have to answer an assessment quiz or activity to test
your learning and capability in terms of skill if the subject is a specialized subject.

When you see this symbol you have to attend a Major Exam or Periodical Exam.

NOTE SCHEDULES

ONLINE SCHEDULE: MWF 2:20-3:40 PM every Second and Fourth Week of the month

OFFLINE SCHEDULE: MWF 2:20-3:40 PM every First and Third Week of the month

2
Quarter 1 - Prelim

Q1/WEEK1 : THE CONCEPT OF STORING AND RETRIEVING

Storing and retrieving is a two part process which involves the storage of data on some kind
of storage medium so it can be preserved and then later retrieved for use by another
process at a later time. Typically when data is stored, the method of data representation
changes, e.g. data from the computer in electrical form is stored onto the hard disk in
magnetic form. This is also true for retrieving as data may be converted back from magnetic
data into electrical signals for use by the computer (IPTCREWKB, 2020).

A DBMS makes it possible for end users to create, read, update and delete data in a
database. The DBMS essentially serves as an interface between the database and end users
or application programs, ensuring that data is consistently organized and remains easily
accessible. The DBMS manages three important things: the data, the database engine that
allows data to be accessed, locked and modified -- and the database schema, which defines
the database’s logical structure.

DATA AND DATA HIERARCHY

What is Data?
is a collection of facts, such as numbers, words, measurements, observations or even just
descriptions of things.

What is Information?
a collection of pieces of data that is organized and used on a computer as record.

What is Database?
is a collection of information that is organized so that it can easily be accessed, managed, and
updated.

DATA HIERARCHY
1. Bit
2. Byte
3. Field
4. Record
5. Database
6. File

3
A bit (short for binary digit) is the smallest unit of data in a computer. A bit has a single binary value,
either 0 or 1.

A byte is a unit of measurement used to measure data. One byte contains eight binary bits, or a
series of eight zeros and ones.

A fields are the smallest units of information in the application system. In the structure of a
database, the smallest component under which data is entered through data capture or data entry.

A record is a collection of data items or elements, possibly of different data types, typically in fixed
number and sequence that arranged for processing by a program.

A Database is a collection of information that is organized so that it can easily be accessed,


managed, and updated.

A File is an object on a computer that stores data, information, settings, or commands that are used
with a computer program. In a graphical user interface (GUI) such as Microsoft Windows, files are
shown as unique icons that relate to the program that opens the file.

Q1/WEEK2 : THE PURPOSE OF DATABASE AND ITS TYPES.

Database
Any storage of data or information, a bank of files or tools and equipment is called a database.

Two types of Database


1. Physical Database = a database accessible through physical interaction like a storage room.
2. Electronic Database = a database accessible through software or application installed in
a computing device.

Example of databases:
1. A storage room
2. A drive in a computer

Database Management Software = are third party software used to store, access, manage
information in an electronic database.

4
Example:
1. MySQL Administrator
2. PostgreSQL
3. Firebird
4. SQLYog
5. Navicat

Management = a term that describes an action taken to properly store, access, secure and maintain
the integrity of information in the database.

System = a set of laws and rules followed in order properly execute a course of actions to deliver an
outcome.

Q1/WEEK3 : THE ADVANTAGES AND DISADVANTAGES

Data Security (Gregory, 2018)


Traditional file organization has security advantages over electronic filing, but it also has its
disadvantages. Electronic files are usually accessible on a network, which means it's possible for an
unauthorized person to gain access to electronic data over the Internet through hacking methods.
Electronic data can also be damaged by software security problems like computer viruses. On the
other hand, paper files can be lost in fires and floods, but electronic data is easy to backup in multiple
locations, reducing the potential for permanent data loss.

Complexity (Gregory, 2018)


A traditional file approach is less complex than electronic systems, which can make it easier for
untrained people to access and manipulate data. Anyone can look through alphabetized filing
cabinets to find a file. Locating and manipulating an electronic database information may require
technical training, and user error can result in unintended alterations or data loss.

Access Time in a Traditional File Environment (Gregory, 2018)


One of the primary disadvantages of an traditional file environment is the time it takes to access data.
It can take minutes if not hours to locate a few files in a large paper filing system. Electronic
databases allow for almost instantaneous access to information. Faster data access time can increase
the productivity of managers, analysts, accountants and other workers who use data on a regular
basis.

5
Editing and Communication (Gregory, 2018)
A traditional file system is cumbersome in that it does not allow users to easily edit files or send
information to others. Paper files often cannot be edited directly, forcing users to make new copies to
update old files. To distribute data on paper files, users must mail, fax or scan the data. Databases
allow users to edit information fields directly, and because information is stored digitally, it is already
in a form that can be easily transmitted.

Order of Data (Gregory, 2018)


Data can get out of order in traditional filing systems. If someone accidentally puts a file in the wrong
place, or takes a file out of a cabinet and forgets to put it back, it can lead to lost data or the creation
of additional copies of files. Electronic filing systems allow users to quickly check whether information
already exists somewhere in the system, which helps avoid problems like redundant files and data
loss.

PHYSICAL DATABASE
Advantages
• Fixed and Final
• Incorruptible with electronic viruses
• Easy to detect any physical alteration
Disadvantages
• It’s hard to find
• Someone can steal it easily
• If you lose its harder to regain it. (it’s harder than electronic storage)
ELECTRONIC DATABASE (CL500, 2020)
Advantages
• Reduced data redundancy
• Reduced updating errors and increased consistency
• Greater data integrity and independence from applications programs
• Improved data access to users through use of host and query languages
• Improved data security
• Reduced data entry, storage, and retrieval costs
• Facilitated development of new applications program
Disadvantages
• Database systems are complex, difficult, and time-consuming to design
• Substantial hardware and software start-up costs
• Damage to database affects virtually all applications programs
• Extensive conversion costs in moving form a file-based system to a database system
• Initial training required for all programmers and users

6
Activities:

Quiz 1
• Get the instruction here: https://tinyurl.com/y4zhumyk
• For submission you may send a copy to this e-mail: [email protected]
• Or upload it in this link https://tinyurl.com/y2tzfdhz
• Or you may submit a printed copy during the scheduled face to face session.

Q1/WEEK4 : DATABASE MANAGEMENT

A database management system (DBMS) is system software for creating and managing databases. A
DBMS makes it possible for end users to create, read, update and delete data in a database. The most
prevalent type of data management platform, the DBMS essentially serves as an interface between
databases and end users or application programs, ensuring that data is consistently organized and remains
easily accessible.

Functions of a DBMS
The DBMS manages three important things: the data, the database engine that allows data to
be accessed, locked and modified, and the database schema, which defines the database's logical
structure. These three foundational elements help provide concurrency, security, data integrity and
uniform data administration procedures. Typical database administration tasks supported by the
DBMS include change management, performance monitoring and tuning, security, and backup and
recovery. Many database management systems are also responsible for automated rollbacks and
restarts as well as the logging and auditing of activity in databases.

Advantages of using a DBMS


Using a DBMS to store and manage data comes with advantages, but also processing
overhead. One of the biggest advantages of using a DBMS is that it lets end users and application
programmers access and use the same data while managing data integrity. Data is better protected
and maintained when it can be shared using a DBMS instead of creating new iterations of the same
data stored in new files for every new application. The DBMS provides a central store of data that can
be accessed by multiple users in a controlled manner (Rouse, Mullins, & Christiansen, 2020).

Central storage and management of data within the DBMS provides:


• Data abstraction and independence.
• Data security.
• A locking mechanism for concurrent access.
• An efficient handler to balance the needs of multiple applications using the same data.
• The ability to swiftly recover from crashes and errors, including restartability and recoverability.
• Robust data integrity capabilities.
• Logging and auditing of activity.

7
• Simple access using a standard API.
• Uniform administration procedures for data.

Another advantage of a DBMS is that it can be used to impose a logical, structured


organization on the data. A DBMS delivers economy of scale for processing large amounts of data
because it is optimized for such operations (Rouse, Mullins, & Christiansen, 2020).

A DBMS can also provide many views of a single database schema. A view defines what data
the user sees and how that user sees the data. The DBMS provides a level of abstraction between the
conceptual schema that defines the logical structure of the database and the physical schema that
describes the files, indexes and other physical mechanisms used by the database. When a DBMS is
used, systems can be modified much more easily when business requirements change. New
categories of data can be added to the database without disrupting the existing system and
applications can be insulated from how data is structured and stored (Rouse, Mullins, & Christiansen,
2020).

However, a DBMS must perform additional work to provide these advantages, thereby
bringing with it the overhead. A DBMS will use more memory and CPU than a simple file storage
system, and different types of DBMSes will require different types and levels of system resources
(Rouse, Mullins, & Christiansen, 2020).

STORE
The act of adding, creating new record in the database.

ARRANGE
Defining database schema, relationships between table/s using primary and foreign key.

UPDATE
Changing data or information with new details. It could be the value of a field, the table or the
schema.
RETRIEVE
Getting record from the database or a single data, search and pull action to display specific
information currently saved in the database tables with specific format and presentation.

REMOVE
Deleting a single data or information from the database table/s.

Q1/WEEK5 : ENTITY RELATIONSHIP DIAGRAM

An entity-relationship diagram (ERD), also known as an entity-relationship model, is a graphical


representation of an information system that depicts the relationships among people, objects, places,
concepts or events within that system. An ERD is a data modeling technique that can help define business
processes and be used as the foundation for a relational database (Rouse, Ferguson, Biscobing, & Aberle,
2019)

8
Importance of ERDs and their uses

Entity-relationship diagrams provide a visual starting point for database design that can also be used to help
determine information system requirements throughout an organization. After a relational database is rolled
out, an ERD can still serve as a referral point, should any debugging or business process re-engineering be
needed later.

However, while an ERD can be useful for organizing data that can be represented by a relational structure, it
can't sufficiently represent semi-structured or unstructured data. It's also unlikely to be helpful on its own in
integrating data into a pre-existing information system.

Main components of an ERD

ERDs are generally depicted in one or more of the following models:

1. A conceptual data model, which lacks specific detail but provides an overview of the scope of the
project and how data sets relate to one another.
2. A logical data model, which is more detailed than a conceptual data model, illustrating specific
attributes and relationships among data points. While a conceptual data model does not need to be
designed before a logical data model, a physical data model is based on a logical data model.
3. A physical data model, which provides the blueprint for a physical manifestation -- such as a
relational database -- of the logical data model. One or more physical data models can be
developed based on a logical data model.

There are three basic components of an entity-relationship diagram:

1. Entities, which are objects or concepts that can have data stored about them.

Example:

2. Attributes, which are properties or characteristics of entities. An ERD attribute can be denoted as a
primary key, which identifies a unique attribute, or a foreign key, which can be assigned to multiple
attributes.

9
Example:

3. The relationships between and among those entities.

Example:

For example, an ERD representing the information system for a company's sales department might start with
graphical representations of entities such as the sales representative, the customer, the customer's address,
the customer's order, the product and the warehouse. Then lines or other symbols can be used to represent
the relationship between entities, and text can be used to label the relationships.

A cardinality notation can then define the attributes of the relationship between the entities. Cardinalities
can denote that an entity is optional (for example, a sales rep could have no customers or could have many)
or mandatory (for example, there must be at least one product listed in order.)

10
While there are tools to help draw entity relationship diagrams, such as computer-aided software engineering
(CASE) tools, some relational database management systems also have design capabilities built-in.

Most Complete Cardinality based on Information Engineering (IE), Martin and Crow’s Foot has the following:

11
Data Structure

— Database has two parts:


1. Data
2. Data Structure: how the data is organized.

Data Model:
Representation of entities and their relationships to the real world

Primary Key:
• a unique identifier in the database
• one or more fields

Data Type

Each field in the database needs to be of a certain type

Examples: text, number, dates

Database Management Systems Approaches

• Database Models
• The Hierarchical Model
• The Network Model
• Relational Model
• Normalization
• Associations

Database Models: Hierarchical Model

In a hierarchical database, data is organized like a family tree or organization chart, with branches
representing parent records and child records

Example:

Records in parent entities can have many child records, but each child can have only one parent.

12
Database Models:

1. Network Model
A network database resembles a hierarchical design but provides somewhat more flexibility

Example: In this case you can have multiple children and parents

2. Relational Model
The relational model was introduced during the 1970s and became popular because it was flexible
and powerful. Because all the tables are linked, a user can request data that meets specific
conditions. New entities and attributes can be added at any time without restructuring the entire
database

A good relational database design eliminates unnecessary data duplications and is, therefore, easier
to maintain

13
Relationship: joining two tables on a common field

PARENT TABLE
A parent table is the main table which could be link to one or more child table. It acts like the
main information table which holds the key to another information or additional data. Has primary key.

CHILD TABLE
Usually a supplementary table which holds additional data or information for the primary data in
parent table. Primary key is not a must but it could still own a unique key and a foreign key.

Q1/WEEK6 : THE CONCEPT OF PRIMARY KEY AND FOREIGN KEY AND DATA TYPES.

A primary key is a minimal set of attributes (columns) in a table that uniquely identifies tuples (rows) in that
table (Singh, 2020). Primary key works as the unique ID, Identifier of a single row of information in a table.

Points to Note regarding Primary Key


• We denote usually denote it by underlining the attribute name (column name).
• The value of primary key should be unique for each row of the table. The column(s) that makes
the key cannot contain duplicate values.
• The attribute(s) that is marked as primary key is not allowed to have null values.
• Primary keys are not necessarily to be a single attribute (column). It can be a set of more than
one attributes (columns). For example {Stu_Id, Stu_Name} collectively can identify the tuple
in the above table, but we do not choose it as primary key because Stu_Id alone is enough to
uniquely identifies rows in a table and we always go for minimal set. Having that said, we
should choose more than one columns as primary key only when there is no single column
that can uniquely identify the tuple in table.

14
What is the difference between a Primary Key and a Foreign Key?
(Adopted from: essentialSQL: Kris Wenzel (Wenzel, 2020))

Before we can dig into the difference, let’s first explore primary and foreign key characteristics.
Let’s start out by learning about primary keys.

Primary Keys

In order for a table to qualify as a relational table, it must have a primary key.

The primary key consists of one or more columns whose data contained within are used to
uniquely identify each row in the table. You can think of them as an address. If the rows in a
table were mailboxes, then the primary key would be the listing of street addresses.

When a primary key is composed of multiple columns, the data from each column is used to
determine whether a row is unique.

In order to be a primary key, several conditions must hold true. First, as we mentioned, the
columns must be unique. To clarify, we’re referring to the data within the rows, not the
column names themselves. Also, no value in the columns can be blank or NULL.

When defining a table you specify the primary key. A table has just one primary key, and its
definition is mandatory.

The primary key for each table is stored in an index. The index is used to enforce the
uniqueness requirement. It also makes it easy for foreign key values to refer back to
corresponding primary key values, as we will learn about in the following section.

Foreign Keys

A foreign key is a set of one or more columns in a table that refers to the primary key in
another table. There aren’t any special code, configurations, or table definitions you need to
place to officially “designate” a foreign key.

In the diagram below look at the SalesOrderHeader table. The column


SalesOrderHeader.CurrencyRateID is a foreign key since it is related to
the

15
CurrencyRate.CurrencyRateID. This column CurrencyRate.CurrencyRateID is the primary key
of the CurrencyRate table.

Example of Foreign Key

Foreign Keys as Part of Primaries

Look at the following diagram. Which column is the foreign key?

16
Foreign Key Value That is Part of PK

If you said it was PersonPhone.BusinessEntityID then you are correct. The reason it is a foreign key is
that it is referring to a primary key, Person.BusinessEntityID, on the other table.

Coincidentally, PersonPhone.BusinessEntityID is not only a foreign key but is also part of


PersonPhone’s primary key. The PersonPhone table’s primary key is the combination of
BusinessEntityID, PhoneNumber, and PhoneNumberTypeID.

I agree this is confusing, but it is allowed and not a bad practice.

Unlike primary keys, foreign keys can contain duplicate values. Also, it is OK for them to contain NULL
values.

Indexes aren’t automatically created for foreign keys; however, as a DBA, you can define them.
A table is allowed to contain more than one foreign key. In the PersonPhone table can you find the
other foreign key (see the answer at end of the article)?

Foreign Key Constraints

Some database management systems, such as SQL Server allow you to set up foreign key
constraints. These help to enforce referential integrity. In their simplest form, a foreign key
constraint stops you from entering values that aren’t found in the related table’s primary key.

Using the first diagram as our example, you can’t enter the SalesOrderHeader.CurrencyRateID if it
doesn’t
already exist in the CurrencyRate table.

17
These constraints come into effect in several ways:

They bar you from changing the foreign key value to one which doesn’t exist as a value in the
related table’s primary key.

They stop you from deleting a row from the primary key table. This stops you from creating orphan
records.
Orphan records are described as “child records with no parents.”
They stop you from adding a foreign key value that doesn’t exist in the primary key.

In summary, the constraints enforce the relationship between the primary and foreign key tables.

Comparison of Primary Keys to Foreign Keys


To summarize here is a comparison of Primary to Foreign Keys

Data Types (Adopted from (TEACH COMPUTER SCIENCE, 2020))

A database data type refers to the format of data storage that can hold a distinct type or range of
values. When computer programs store data in variables, each variable must be designated a distinct data
type. Some common data types are as follows: integers, characters, strings, floating point numbers and
arrays. More specific data types are as follows: varchar (variable character) formats, Boolean values, dates
and timestamps.
18
Database applications use data types. Database fields require distinct type of data to be entered. For
example, school record for a student may use a string data type for student’s first and last name. The
student’s date of birth would be stored in a date format and the student’s GPA can be stored as decimal.
By ensuring that the data types are consistent across multiple records, database applications can easily
perform calculations, comparisons, searching and sorting of fields in different records.

Common Database Data Types

• Integer – is a whole number that can have a positive, negative or zero value. It cannot be a fraction
nor can have decimal places. It is commonly used in programming especially for increasing values.
Addition, subtraction and multiplication of two integers results to an integer. But division of two
integers may result to an integer or a decimal. The resulting decimal can be rounded off or truncated
to produce an integer.
• Character – refers to any number, letter, space or symbol that can be entered in a computer. Each
character occupies one byte of space.
• String – is used to represent text. It is composed of a set of characters that can have spaces and
numbers. Strings are enclosed in quotation marks to identify the data as string and not a variable
name nor a number.
• Floating Point Number – is a number that contains decimals. Numbers that contain fractions are
also considered as floating point numbers.
• Array – contains a group of elements which can be of the same data type like an integer or string. It is
used to organise data for easier sorting and searching of related set of values.
• Varchar – as the name implies is variable character as the memory storage has variable length.
Each character occupies one byte of space plus 2 bytes for length information.Note: Use Character for
data entries with fixed length, like phone number. Use Varchar for data entries with variable length,
like address.
• Boolean – is used for creating true or false statements. To compare values the following operators
are being used: AND, OR, XOR, and NOT.

BOOLEAN OPERATOR RESULT CONDITION


X and Y True If both x and y are True
X and Y False If either x or y is False
X or Y True If either x or y, or both x and y are True
X or Y False If both x and y are False
X xor Y True If only x or y is True
X xor Y False If x and y are both True or both False

19
Not X True If x is False
Not X False If x is True

• Date, Time and Timestamp – these data types are used to work with data containing dates and
times.

Q1/WEEK7 : DIFFERENT TYPES OF RELATIONSHIP (Adopted from (eTutorials.org, 2008))

Before you begin to establish relationships between tables in the database, you must know what
types of relationships can exist between a given pair of tables. Knowing how to identify them properly is an
invaluable skill for designing a database successfully.

There are three specific types of relationships that can exist between a pair of tables: one-to-one,
one- to-many, and many-to-many. The tables participate in only one type of relationship at any given time.
(You'll rarely need to change the type of relationship between a pair of tables. Only major changes in either
of the table's structures could cause you to change the relationship.)

Note:

The discussion for each type of relationship begins with a generic example of the relationship.
Learning how to visualize a relationship generically enables you to understand the principle behind the
relationship itself. Once you understand how and why the relationship works, you'll be able to determine
whether it exists between a given pair of tables quite easily.

Each discussion also includes an example of how to diagram the relationship. I provide special
instructions pertaining to the diagramming process where appropriate and explain the symbols incorporated
within the diagram as necessary. This allows you to learn the diagramming method at a reasonable pace and
keeps you from having to memorize the entire set of diagram symbols all at once.

Figure 10.2 shows the first symbols you will use to diagram a table relationship

One-to-One Relationships

20
A pair of tables bears a one-to-one relationship when a single record in the first table is related to only one
record in the second table, and a single record in the second table is related to only one record in the first
table. Figure
10.3 shows a generic example of a one-to-one relationship.

Figure 10.3. A generic example of a one-to-one relationship

As you can see, a single record in TABLE A is related to only one record in TABLE B, and a single record in
TABLE B is related to only one record in TABLE A. A one-to-one relationship usually (but not always) involves
a subset table. Figure 10.4 shows an example of a typical one-to-one relationship that you might find in a
database for an organization's human resources department. This example also illustrates a situation where
neither of the tables is a subset table.

Figure 10.4. A typical example of a one-to-one relationship.

Although the fields in these tables could be combined into a single table, the database designer chose to
place the fields that can be viewed by anyone in the organization in the EMPLOYEES table and the fields that
can be viewed only by authorized personnel in the COMPENSATION table. Only one record is required to store
the compensation data for a given employee, so there is a distinct one-to-one relationship between a record
in the EMPLOYEES table and a record in the COMPENSATION table.

21
A one-to-one relationship usually (but not always) involves a subset table. (Indeed, neither of the tables in
Figure 10.4 is a subset table.) Figure 10.5 shows a generic example of how you create a relationship diagram
for a one- to-one relationship.

Figure 10.5. Diagramming a one-to-one relationship

The line that appears between the tables in the diagram indicates the type of relationship, and there is a
particular line that you use for each type. Later in this chapter, you'll learn how to modify the line to show the
characteristics of the relationship as well. Figure 10.6 shows the relationship diagram for the EMPLOYEES
and COMPENSATION tables in Figure 10.4. (Note that a Data Table symbol represents each table.)

Figure 10.6. The relationship diagram for the EMPLOYEES and COMPENSATION tables

One-to-Many Relationships

22
A one-to-many relationship exists between a pair of tables when a single record in the first table can be
related to one or more records in the second table, but a single record in the second table can be related to
only one record in the first table. Let's look at a generic example of this type of relationship.

Say you're working with two tables, TABLE A and TABLE B, that have a one-to-many relationship between
them. Because of the relationship, a single record in TABLE A can be related to one or more records in TABLE
B. Figure
10.7 shows the relationship from the perspective of TABLE A.

Figure 10.7. A one-to-many relationship from the perspective of TABLE A

Conversely, a single record in the TABLE B can be related to only one record in TABLE A. Figure 10.8 shows
the relationship from the perspective of TABLE B.

Figure 10.8. A one-to-many relationship from the perspective of TABLE B

This is by far the most common relationship that exists between a pair of tables in a database, and it is the
easiest to identify. It is crucial from a data-integrity standpoint because it helps to eliminate duplicate data
and to keep redundant data to an absolute minimum. Figure 10.9 shows a common example of a one-to-
many relationship that you might find in a database for a video rental store.

23
Figure 10.9. A typical example of a one-to-many relationship

A customer can check out any number of videos, so a single record in the CUSTOMERS table can be related to
one or more records in the CUSTOMER RENTALS table. A single video, however, is associated with only one
customer at any given time, so a single record in the CUSTOMER RENTALS table is related to only one record
in the CUSTOMERS table.

Figure 10.10 shows a generic example of how you create a relationship diagram for a one-to-many
relationship.

Figure 10.10. Diagramming a one-to-many relationship

Note that the crow's foot symbol is always located next to the table on the "many" side of the relationship.
Figure
10.11 shows the relationship diagram for the CUSTOMERS and CUSTOMER RENTALS tables in Figure 10.9.

Figure 10.11. The relationship diagram for the CUSTOMERS and CUSTOMER RENTALS tables

24
Many-to-Many Relationships

A pair of tables bears a many-to-many relationship when a single record in the first table can be related to
one or more records in the second table and a single record in the second table can be related to one or more
records in the first table.

Assume once again that you're working with TABLE A and TABLE B and that there is a many-to-many
relationship between them. Because of the relationship, a single record in TABLE A can be related to one or
more records (but not necessarily all) in TABLE B. Conversely, a single record in the TABLE B can be related to
one or more records (but not necessarily all) in TABLE A. Figure 10.12 shows the relationship from the
perspective of each table.

Figure 10.12. A many-to-many relationship from the perspective of both TABLE A and TABLE B

This is the second most common relationship that exists between a pair of tables in a database. It can be a
little more difficult to identify than a one-to-many relationship, so you must be sure to examine the tables
carefully. Figure 10.13 shows a typical example of a many-to-many relationship that you might find in a
school database, which happens to be a classic example of this type of relationship (no pun intended!).

Figure 10.13. A typical example of a many-to-many relationship

25
A student can attend one or more classes during a school year, so a single record in the STUDENTS table can
be related to one or more records in the CLASSES table. Conversely, one or more students will attend a given
class, so a single record in the CLASSES table can be related to one or more records in the STUDENTS table.

Figure 10.14 shows a generic example of how you create a relationship diagram for a many-to-many
relationship.

Figure 10.14. Diagramming a many-to-many relationship

In this case, there is a crow's foot symbol located next to each table. Figure 10.15 shows the relationship
diagram for the STUDENTS and CLASSES tables in Figure 10.13.

Figure 10.15. The relationship diagram for the STUDENTS and CLASSES tables

26
Problems with Many-to-Many Relationships

A many-to-many relationship has an inherent peculiarity that you must address before you can effectively
use the data from the tables involved in the relationship. The issue is this: How do you easily associate
records from the first table with records in the second table in order to establish the relationship? This is an
important question because you'll encounter problems such as these if you do not establish the relationship
properly:

It will be tedious and somewhat difficult to retrieve information from one of the tables.

One of the tables will contain a large amount of redundant data.

Duplicate data will exist within both tables.

It will be difficult for you to insert, update, and delete data.

There are two common methods that novice and inexperienced developers use in a futile attempt to address
this situation. I'll demonstrate how you might apply these methods using the STUDENTS and CLASSES tables
in Figure 10.16 as examples.

Figure 10.16. Structures of the STUDENTS and CLASSES tables

27
Note

As this example unfolds, keep in mind that every many-to-many relationship you encounter will exhibit these
same issues.

As you can see, there is no actual connection between the two tables, so you have no way of associating
records in one table with records in the other table. The first method you might use to attempt to establish a
connection involves taking a field from one table and incorporating it a given number of times within the
other table. (This approach usually appeals to people who are accustomed to working with spreadsheets.)
For example, you could take the STUDENT ID field from the STUDENTS table and incorporate it within the
CLASSES table structure, creating as many copies of the field as you need to represent the maximum
number of students that could attend any class. Figure 10.17 shows the revised version of the CLASSES table
structure.

Figure 10.17. Incorporating STUDENT ID fields within the CLASSES table structure

28
This structure is likely to be problematic, so you might try taking the CLASS ID field from the CLASSES table
and incorporating it within the STUDENTS table structure instead. Figure 10.18 shows the revised version of
the STUDENTS table structure.

Figure 10.18. Incorporating CLASS ID fields within the STUDENTS table structure

Do these structures look (vaguely) familiar? They should. All you've done using this method is introduce a
"flattened" multivalued field into the table structure. In doing so, you've also introduced the problems
associated with a multivalued field. (If necessary, review Chapter 7.) Although you know how to resolve a
multivalued field, this is not a good or proper way to establish the relationship.

29
The second method you might attempt to use is simply a variation of the first method. In this case, you take
one or more fields from one table and incorporate a single instance of each field within the other table. For
example, you could take the CLASS ID, CLASS NAME, and INSTRUCTOR ID fields from the CLASSES table and
incorporate them into the STUDENTS table in order to identify the classes in which a student is currently
enrolled. This may seem to be a distinct improvement over the first method, but you'll see that there are
problems that arise from such modifications when you load the revised STUDENTS table with sample data.

Figure 10.19 clearly illustrates the problems you'll encounter using this method.

• The table contains unnecessary duplicate fields. You learned all about unnecessary duplicate fields
and the problems they pose back in Chapter 7, so you know that using them here is not a good idea.
Besides, it is very likely that the CLASS NAME and INSTRUCTOR ID fields are not appropriate in the
STUDENTS tablethe CLASS ID field identifies the class sufficiently, and it is really all you need to
identify the classes a student is taking.

• There is a large amount of redundant data. Even if you remove the CLASS NAME and INSTRUCTOR ID
fields from the STUDENTS table, the CLASS ID field will still produce a lot of redundant data.

• It is difficult to insert a new record. If you enter a record in the STUDENTS table for a new class
(instead of entering it in the CLASSES table) without also entering student data, the fields pertaining
to the student will be nullincluding the primary key of the STUDENTS table (STUDENT ID). This will
automatically trigger a violation of the Elements of a Primary Key because the primary key cannot be
null; therefore, you cannot insert the record into the table until you can provide a proper primary key
value.

• It is difficult to delete a record. This is especially true if the only data about a new class has been
recorded in the particular student record you want to delete. Note the record for Diana Barlet, for
example. If Diana decides not to attend any classes this year and you delete her record, you will lose
the data for the "Introduction to Database Design" class. That might not create a serious
problemunless someone neglected to enter the data about this class into the CLASSES table as well.
Once you delete Diana's record, you'll have to re-enter all of the data for the class in the CLASSES
table.

Figure 10.19. The revised STUDENTS table with sample data

30
Fortunately, you will not have to worry about any of these problems because you're going to learn the proper
way to establish a many-to-many relationship.

Self-Referencing Relationships
This particular type of relationship does not exist between a pair of tables, which is why it isn't mentioned at
the beginning of this section. It is instead a relationship that exists between the records within a table.
Ironically, you'll still regard this throughout the design process as a table relationship.

A table bears a self-referencing relationship (also known as a recursive relationship) to itself when a given
record in the table is related to other records within the table. Similar to its dual-table counterpart, a self-
referencing relationship can be one-to-one, one-to-many, or many-to-many.

One-to-One
A self-referencing one-to-one relationship exists when a given record in the table can be related to only one
other record within the table. The MEMBERS table in Figure 10.20 is an example of a table with this type of
relationship. In this case, a given member can sponsor only one other member within the organization; the
SPONSOR ID field stores the member identification number of the member acting as a sponsor. Note that
Susan McLain is Tom Wickerath's sponsor.

Figure 10.20. Example of a self-referencing one-to-one relationship

31
Figure 10.21 shows how you diagram this type of relationship
Figure 10.21. Diagramming a self-referencing one-to-one
relationship

One-to-Many
A table bears a self-referencing one-to-many relationship to itself when a given record in the table can be
related to one or more other records within the table. Figure 10.22 shows an example in which a given
customer can refer other customers to the organization. The REFERRED BY field stores the customer
identification number of the customer making the referral. Note that Paul Litwin referred both Andy Baron
and Mary Chipman.

Figure 10.22. Example of a self-referencing one-to-many relationship

Figure 10.23 shows how you diagram a self-referencing one-to-many relationship.


Figure 10.23. Diagramming a self-referencing one-to-many relationship.

32
Many-to-Many
A self-referencing many-to-many relationship exists when a given record in the table can be related to one or
more other records within the table and one or more records can themselves be related to the given record.
This may sound somewhat confusing at first, but the example in Figure 10.24 should help clarify the matter.

In this case, a particular part can comprise several different component parts, and it can itself be a
component of other parts. For example, a clamp assembly (Part ID 704) is composed of a fastening bolt (Part
ID 703), a bottom clamp (Part ID 702), and a top clamp (Part ID 701). Additionally, the clamp assembly is
itself a component of a seat assembly (Part ID 707) and a frame assembly (Part ID 711). Figure 10.25 shows
how you diagram this type of relationship.

Figure 10.25. Diagramming a self-referencing many-to-many relationship

33
Figure 10.24. Example of a self-referencing many-to-many relationship

Activities:

Activity 1: Create a Database Design for a Pyramiding Business Scheme


• Get the instruction here: https://tinyurl.com/y4duh2lp
• For submission you may send a copy to this e-mail: [email protected]
• Or upload it in this link https://tinyurl.com/y5kn32j8
• Or you may submit a printed copy during the scheduled face to face session.

Q1/WEEK8 : STRUCTURED QUERY LANGUAGE AS GENERAL ELECTRONIC DATABASE LANGUAGE

What is SQL? (Adopted from (eWEEK, 2020))

SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to communicate
with a database. According to ANSI (American National Standards Institute), it is the standard
language for relational database management systems. SQL statements are used to perform tasks
such as update data on a database, or retrieve data from a database. Some common relational
database management systems that use SQL are: Oracle, Sybase, Microsoft SQL Server, Access,
Ingres, etc. Although most database systems use SQL, most of them also have their own additional
proprietary extensions that are usually only used on their system. However, the standard SQL
commands such as "Select", "Insert", "Update", "Delete", "Create", and "Drop" can be used to
accomplish almost everything that one needs to do with a database. This tutorial will provide you with
the instruction on the basics of each of these commands as well as allow you to put them to practice
using the SQL Interpreter.

Table Basics
A relational database system contains one or more objects called tables. The data or information for
the database are stored in these tables. Tables are uniquely identified by their names and are
comprised of columns and rows. Columns contain the column name, data type, and any other
attributes for the column. Rows contain the records or data for the columns. Here is a sample table
called "weather".

34
City, State, High, and Low are the columns. The rows contain the data for this table:
WEATHER
CITY STATE HIGH LOW
Phoenix Arizona 105 90
Tucson Arizona 101 92
Flagstaff Arizona 88 69
San Diego California 77 60
Albuquerque New Mexico 80 72

Q1/WEEK9 : SQL (INSERT) = INSERTING OR ADDING NEW INFORMATION INTO THE ELECTRONIC
DATABASE.
Adopted from (eWEEK, 2020)

Inserting into a Table


The insert statement is used to insert or add a row of data into the table.

To insert records into a table, enter the key words insert into followed by the table name, followed by
an open parenthesis, followed by a list of column names separated by commas, followed by a closing
parenthesis, followed by the keyword values, followed by the list of values enclosed in parenthesis.
The values that you enter will be held in the rows and they will match up with the column names that
you specify. Strings should be enclosed in single quotes, and numbers should not.

insert into "tablename" (first_column,...last_column) values


(first_value,...last_value);

In the example below, the column name first will match up with the value 'Luke', and the column
name state will match up with the value 'Georgia'.

Example:

insert into employee (first, last, age, address, city, state) values ('Luke', 'Duke',
45, '2130 Boars Nest', 'Hazard Co', 'Georgia');

Note: All strings should be enclosed between single quotes: 'string'

Activities:

Activity 2: (HANDS ON) During the Face to Face Schedule

35
Q1/WEEK10 : QUARTERLY EXAMINATION

Q2/WEEK1 : SQL (SELECT) = RETRIEVING OR VIEWING INFORMATION FROM THE ELECTRONIC


DATABASE. Q2/WEEK2 : SQL (SELECT) = RETRIEVING OR VIEWING INFORMATION FROM THE
ELECTRONIC DATABASE.
Adopted from (eWEEK, 2020)

Selecting Data
The select statement is used to query the database and retrieve selected data that match the
criteria that you specify. Here is the format of a simple select statement:

select "column1"
[,"column2",etc]
from "tablename"
[where "condition"];
[] = optional

The column names that follow the select keyword determine which columns will be returned in the
results. You can select as many column names that you'd like, or you can use a " * " to select all
columns.

The table name that follows the keyword from specifies the table that will be queried to retrieve
the desired results.

The where clause (optional) specifies which data values or rows will be returned or displayed, based
on the criteria described after the keyword where.

Conditional selections used in the where clause:

= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> Not equal to
LIKE * See note below

The LIKE pattern matching operator can also be used in the conditional selection of the where clause.
Like is a very powerful operator that allows you to select only rows that are "like" what you specify.
The
36
percent sign "%" can be used as a wild card to match any possible character that might appear before
or after the characters specified. For example:

select first, last, city from empinfo where first LIKE 'Er%';

This SQL statement will match any first names that start with 'Er'. Strings must be in single quotes.

Or you can specify,

select first, last from empinfo where last LIKE '%s';

This statement will match any last names that end in a 's'.

select * from empinfo where first = 'Eric';

This will only select rows where the first name equals 'Eric' exactly. (See table on the next page…)

Enter the following sample select statements in the SQL Interpreter Form at the bottom of this page.
Before you press "submit", write down your expected results. Press "submit", and compare the results.

select first, last, city from empinfo;

select last, city, age from empinfo where age > 30;

select first, last, city, state from empinfo where first LIKE 'J%';

select * from empinfo;

select first, last, from empinfo where last LIKE '%s';

37
select first, last, age from empinfo where last LIKE '%illia%';

select * from empinfo where first = 'Eric';

Activities:

Activity 3: (HANDS ON) During the Face to Face Schedule

Q2/WEEK3 : SQL (UPDATE) = EDITING AN EXISTING RECORD IN THE ELECTRONIC


DATABASE. Q2/WEEK4 : SQL (UPDATE) = EDITING AN EXISTING RECORD IN THE
ELECTRONIC DATABASE.
Adopted from (eWEEK, 2020)

Updating Records
The update statement is used to update or change records that match a specified criteria. This is
accomplished by carefully constructing a where clause.

update "tablename" set "columnname" = "newvalue" [,"nextcolumn" = "newvalue2"...]


where "columnname" OPERATOR "value" [and|or "column" OPERATOR "value"];

[ ] = optional

Examples:

update phone_book set area_code = 623 where prefix = 979;

update phone_book set last_name = 'Smith', prefix=555, suffix=9292 where last_name


= 'Jones';

update employee set age = age+1 where first_name='Mary' and last_name='Williams';

Activities:

Activity 4: (HANDS ON) During the Face to Face Schedule

Q2/WEEK5 : SQL (DELETE) = REMOVING SPECIFIC RECORD/S FROM THE ELECTRONIC


DATABASE. Q2/WEEK6 : SQL (DELETE) = REMOVING SPECIFIC RECORD/S FROM THE
ELECTRONIC DATABASE.
Adopted from (eWEEK, 2020)

Deleting Records
The delete statement is used to delete records or rows from the table.

38
delete from "tablename" where "columnname" OPERATOR "value" [and|or "column"
OPERATOR "value"];

[ ] = optional

Examples:

delete from employee;

Note: if you leave off the where clause, all records will be deleted!

delete from employee where lastname = 'May';

delete from employee where firstname = 'Mike' or firstname = 'Eric';

To delete an entire record/row from a table, enter "delete from" followed by the table name,
followed by the where clause which contains the conditions to delete. If you leave off the where
clause, all records will be deleted.

Activities:

Activity 5: (HANDS ON) During the Face to Face Schedule

Q2/WEEK7 : OTHER STRUCTURED


QUERY Q2/WEEK8 : OTHER
STRUCTURED QUERY Q2/WEEK9 :
OTHER STRUCTURED QUERY
Adopted from (eWEEK, 2020)

SELECT Statement
The SELECT statement is used to query the database and retrieve selected data that match the criteria
that you specify.

The SELECT statement has five main clauses to choose from, although, FROM is the only required
clause. Each of the clauses have a vast selection of options, parameters, etc. The clauses will be
listed below, but each of them will be covered in more detail later in the tutorial.

Here is the format of the SELECT statement:


SELECT [ALL | DISTINCT] column1[,column2] FROM table1[,table2] [WHERE "conditions"]
[GROUP BY "column-list"] [HAVING "conditions] [ORDER BY "column-list" [ASC | DESC] ]

39
FROM & WHERE clause quick review
SELECT first_column_name, second_column_name FROM table_name WHERE
first_column_name > 1000;

• The column names that follow the SELECT keyword determine which columns will be
returned in the results. You can select as many column names that you'd like, or you
can use a * to select all columns. The order they are specified will be the order that
they are returned in your query results.

• The table name that follows the keyword FROM specifies the table that will be queried
to retrieve the desired results.

• The WHERE clause (optional) specifies which data values or rows will be returned or
displayed, based on the criteria described after the keyword where.

Example:
SELECT name, age, salary FROM employee WHERE age > 40;

The above statement will select all of the values in the name, age, and salary columns from the
employee table whose age is greater than 50.

Note: Remember to put a semicolon at the end of your SQL statements. The ; indicates that your
SQL statement is complete and is ready to be interpreted.

Comparison Operators

= Equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> or != Not equal to
LIKE String comparison test

Note about LIKE


SELECT first_column_name, second_column_name FROM table_name WHERE
first_column_name LIKE 'Mc%';

40
The LIKE pattern matching operator can also be used in the conditional selection of the where
clause. Like is a very powerful character string comparison operator that allows you to select
only rows that are "like" what you specify. The percent sign "%" can be used as a wild card to
match any possible character that might appear before or after the characters specified. For
example:

select first, last, city from empinfo where first LIKE 'Mc%';

This SQL statement will match any first names that start with 'Mc'. Strings must be in single
quotes.

Example:
SELECT name, title, dept FROM employee WHERE title LIKE 'Pro%';

The above statement will select all of the rows/values in the name, title, and dept columns from the
employee table whose title starts with 'Pro'. This may return job titles including Programmer or Pro-
wrestler.

ALL and DISTINCT are keywords used to select either ALL (default) or the "distinct" or unique records
in your query results. If you would like to retrieve just the unique records in specified columns, you
can use the "DISTINCT" keyword. DISTINCT will discard the duplicate records for the columns you
specified after the "SELECT" statement: For example:

SELECT DISTINCT age FROM employee_info;

This statement will return all of the unique ages in the employee_info table.

ALL will display "all" of the specified columns including all of the duplicates. The ALL keyword is the
default if nothing is specified.

Aggregate Functions

MIN returns the smallest value in a given


column MAX returns the largest value in a given
column
SUM returns the sum of the numeric values in a given
column AVG returns the average value of a given column
COUNT returns the total number of values in a given
column COUNT(*) returns the number of rows in a table
41
Aggregate functions are used to compute against a "returned column of numeric data" from your
SELECT statement. They basically summarize the results of a particular column of selected data. We
are covering these here since they are required by the next topic, "GROUP BY". Although they are
required for the "GROUP BY" clause, these functions can be used without the "GROUP BY" clause. For
example:

SELECT AVG(salary) FROM employee;

This statement will return a single result which contains the average value of everything returned in
the salary column from the employee table.

Another example:
SELECT AVG(salary) FROM employee WHERE title = 'Programmer';

This statement will return the average salary for all employee whose title is equal to 'Programmer'

Example:
SELECT Count(*) FROM employee;

GROUP BY clause
The GROUP BY clause will gather all of the rows together that contain data in the specified column(s)
and will allow aggregate functions to be performed on the one or more columns. This can best be
explained by an example:

GROUP BY clause syntax:


SELECT column1, SUM(column2) FROM "list-of-tables" GROUP BY "column-list";

Let's say you would like to retrieve a list of the highest paid salaries in each dept:

SELECT max(salary), dept FROM employee GROUP BY dept;

This statement will select the maximum salary for the people in each unique department. Basically,
the salary for the person who makes the most in each department will be displayed. Their, salary and
their department will be returned.

GROUP BY - Multiple Grouping Columns - What if?


What if you ALSO want to display their lastname for the query below:

SELECT max(salary), dept FROM employee GROUP BY dept;

42
What you'll need to do is:

SELECT lastname, max(salary), dept FROM employee GROUP BY dept, lastname;

This is a called "multiple grouping columns".

For example, take a look at the items_ordered table. Let's say you want to group everything of
quantity 1 together, everything of quantity 2 together, everything of quantity 3 together, etc. If you
would like to determine what the largest cost item is for each grouped quantity (all quantity 1's, all
quantity 2's, all quantity 3's, etc.), you would enter:

SELECT quantity, max(price) FROM items_ordered GROUP BY quantity;

HAVING clause
The HAVING clause allows you to specify conditions on the rows for each group - in other words, which
rows should be selected will be based on the conditions you specify. The HAVING clause should follow
the GROUP BY clause if you are going to use it.

HAVING clause syntax:


SELECT column1, SUM(column2) FROM "list-of-tables" GROUP BY "column-list" HAVING
"condition";
HAVING can best be described by example. Let's say you have an employee table containing the
employee's name, department, salary, and age. If you would like to select the average salary for each
employee in each department, you could enter:

SELECT dept, avg(salary) FROM employee GROUP BY dept;

But, let's say that you want to ONLY calculate & display the average if their salary is over 20000:

SELECT dept, avg(salary) FROM employee GROUP BY dept HAVING avg(salary) > 20000;

ORDER BY clause
ORDER BY is an optional clause which will allow you to display the results of your query in a sorted
order (either ascending order or descending order) based on the columns that you specify to order
by.

ORDER BY clause syntax:

43
SELECT column1, SUM(column2) FROM "list-of-tables" ORDER BY "column-list" [ASC |
DESC];

[ ] = optional

This statement will select the employee_id, dept, name, age, and salary from the employee_info table
where the dept equals 'Sales' and will list the results in Ascending (default) order based on their Salary.

ASC = Ascending Order - default


DESC = Descending Order

For example:
SELECT employee_id, dept, name, age, salary FROM employee_info WHERE dept = 'Sales'
ORDER BY salary;

If you would like to order based on multiple columns, you must seperate the columns with commas. For
example:

SELECT employee_id, dept, name, age, salary FROM employee_info WHERE dept = 'Sales'
ORDER BY salary, age DESC;

Combining Conditions & Boolean Operators


The AND operator can be used to join two or more conditions in the WHERE clause. Both sides of the
AND condition must be true in order for the condition to be met and for those rows to be displayed.

SELECT column1, SUM(column2) FROM "list-of-tables" WHERE "condition1" AND


"condition2";

The OR operator can be used to join two or more conditions in the WHERE clause also. However,
either side of the OR operator can be true and the condition will be met - hence, the rows will be
displayed. With the OR operator, either side can be true or both sides can be true.

For example:
SELECT employeeid, firstname, lastname, title, salary FROM employee_info WHERE salary
>= 45000.00 AND title = 'Programmer';

This statement will select the employeeid, firstname, lastname, title, and salary from the
employee_info table where the salary is greater than or equal to 50000.00 AND the title is equal to
'Programmer'. Both of

44
these conditions must be true in order for the rows to be returned in the query. If either is false, then it
will not be displayed.

Although they are not required, you can use paranthesis around your conditional expressions to make
it easier to read:

SELECT employeeid, firstname, lastname, title, salary FROM employee_info WHERE (salary
>= 45000.00) AND (title = 'Programmer');

Another Example:

SELECT firstname, lastname, title, salary FROM employee_info WHERE (title = 'Sales')
OR (title = 'Programmer');

This statement will select the firstname, lastname, title, and salary from the employee_info table
where the title is either equal to 'Sales' OR the title is equal to 'Programmer'.

IN & BETWEEN

SELECT col1, SUM(col2) FROM "list-of-tables" WHERE col3 IN (list-of-values);

SELECT col1, SUM(col2) FROM "list-of-tables" WHERE col3 BETWEEN value1 AND value2;

The IN conditional operator is really a set membership test operator. That is, it is used to test whether
or not a value (stated before the keyword IN) is "in" the list of values provided after the keyword IN.

For example:
SELECT employeeid, lastname, salary FROM employee_info WHERE lastname IN ('Hernandez',
'Jones', 'Roberts', 'Ruiz');

This statement will select the employeeid, lastname, salary from the employee_info table where the
lastname is equal to either: Hernandez, Jones, Roberts, or Ruiz. It will return the rows if it is ANY of
these values.

The IN conditional operator can be rewritten by using compound conditions using the equals operator
and combining it with OR - with exact same output results:

45
SELECT employeeid, lastname, salary FROM employee_info WHERE lastname = 'Hernandez'
OR lastname = 'Jones' OR lastname = 'Roberts' OR lastname = 'Ruiz';

As you can see, the IN operator is much shorter and easier to read when you are testing for more
than two or three values.

You can also use NOT IN to exclude the rows in your list.

The BETWEEN conditional operator is used to test to see whether or not a value (stated before the
keyword BETWEEN) is "between" the two values stated after the keyword BETWEEN.

For example:

SELECT employeeid, age, lastname, salary FROM employee_info WHERE age BETWEEN 30 AND
40;

This statement will select the employeeid, age, lastname, and salary from the employee_info table
where the age is between 30 and 40 (including 30 and 40).

This statement can also be rewritten without the BETWEEN operator:

SELECT employeeid, age, lastname, salary FROM employee_info WHERE age >= 30 AND age
<= 40;

You can also use NOT BETWEEN to exclude the values between your range.

Mathematical Functions
Standard ANSI SQL-92 supports the following first four basic arithmetic operators:

+ addition
- subtraction
* multiplication
/ division
% modulo

The modulo operator determines the integer remainder of the division. This operator is not ANSI
SQL supported, however, most databases support it. The following are some more useful
mathematical

46
functions to be aware of since you might need them. These functions are not standard in the ANSI
SQL- 92 specs, therefore they may or may not be available on the specific RDBMS that you are using.
However, they were available on several major database systems that I tested. They WILL work on
this tutorial.

ABS(x) returns the absolute value of x


SIGN(x) returns the sign of input x as -1, 0, or 1 (negative, zero, or positive
respectively) MOD(x,y) modulo - returns the integer remainder of x divided by y
(same as x%y) FLOOR(x) returns the largest integer value that is less than or equal to x
CEILING(x) or CEIL(x) returns the smallest integer value that is greater than or equal
to x POWER(x,y) returns the value of x raised to the power of y
ROUND(x) returns the value of x rounded to the nearest whole integer
ROUND(x,d) returns the value of x rounded to the number of decimal places specified by the value
d SQRT(x) returns the square-root value of x
For example:
SELECT round(salary), firstname FROM employee_info

Table Joins, a must


All of the queries up until this point have been useful with the exception of one major limitation - that
is, you've been selecting from only one table at a time with your SELECT statement. It is time to
introduce you to one of the most beneficial features of SQL & relational database systems - the "Join".
To put it simply, the "Join" makes relational database systems "relational".

Joins allow you to link data from two or more tables together into a single query result--from one
single SELECT statement.

A "Join" can be recognized in a SQL SELECT statement if it has more than one table after the FROM
keyword.

For example:

SELECT "list-of-columns" FROM table1,table2 WHERE "search-condition(s)"

Joins can be explained easier by demonstrating what would happen if you worked with one table only,
and didn't have the ability to use "joins". This single table database is also sometimes referred to as a
"flat table". Let's say you have a one-table database that is used to keep track of all of your customers
and what they purchase from your store:

47
Every time a new row is inserted into the table, all columns will be be updated, thus resulting in
unnecessary "redundant data". For example, every time Wolfgang Schultz purchases something, the
following rows will be inserted into the table:

An ideal database would have two tables:


1. One for keeping track of your customers
2. And the other to keep track of what they
purchase: "Customer_info" table:

"Purchases" table:"Purchases" table:

Now, whenever a purchase is made from a repeating customer, the 2nd table, "Purchases" only needs
to be updated! We've just eliminated useless redundant data, that is, we've just normalized this
database!

Notice how each of the tables have a common "cusomer_number" column. This column, which
contains the unique customer number will be used to JOIN the two tables. Using the two new tables,
let's say you would like to select the customer's name, and items they've purchased. Here is an
example of a join statement to accomplish this:

SELECT customer_info.firstname, customer_info.lastname, purchases.item FROM


customer_info, purchases WHERE customer_info.customer_number =
purchases.customer_number;

48
This particular "Join" is known as an "Inner Join" or "Equijoin". This is the most common type of "Join"
that you will see or use.

Notice that each of the colums are always preceeded with the table name and a period. This isn't
always required, however, it IS good practice so that you wont confuse which colums go with what
tables. It is required if the name column names are the same between the two tables. I recommend
preceeding all of your columns with the table names when using joins.

Note: The syntax described above will work with most Database Systems -including the one with this
tutorial. However, in the event that this doesn't work with yours, please check your specific database
documentation.

Although the above will probably work, here is the ANSI SQL-92 syntax specification for an Inner Join
using the preceding statement above that you might want to try:

SELECT customer_info.firstname, customer_info.lastname, purchases.item FROM


customer_info INNER JOIN purchases ON customer_info.customer_number =
purchases.customer_number;

Another example:

SELECT employee_info.employeeid, employee_info.lastname, employee_sales.comission


FROM employee_info, employee_sales WHERE employee_info.employeeid =
employee_sales.employeeid;

This statement will select the employeeid, lastname (from the employee_info table), and the
comission value (from the employee_sales table) for all of the rows where the employeeid in the
employee_info table matches the employeeid in the employee_sales table.

Activities:

Activity 6: (HANDS ON) During the Face to Face

Schedule Q2/WEEK10 : FINAL PRESENTATION OF OUTPUTS AND

EXAMINATIONS

FINAL REQUIREMENT

Project Proposal Documentation

This will include the following parts:

49
I. Tile (Adopted from (Sacred Heart University Library, 2020))
= The title summarizes the main idea or ideas of your study. A good title contains the fewest
possible words that adequately describe the contents and/or purpose of your research paper.
The title is without doubt the part of a paper that is read the most, and it is usually read first.

Example:
Point of Sale System
Event Attendance Management System
SSC Election System

II. Introduction (Adopted from (Zepernick, 2006))


= The introduction serves multiple purposes. It presents the background to your study,
introduces your topic and aims, and gives an overview of the paper. A good introduction will
provide a solid foundation and encourage readers to continue on to the main parts of your
paper—the methods, results, and discussion.

10 tips for writing an effective introduction.


These tips apply primarily to full papers and letters reporting original research results.
Although some tips will be more suited to papers in certain fields, the points are broadly
applicable.

1. Start broadly and then narrow down


In the first paragraph, briefly describe the broad research area and then narrow down to your
particular focus. This will help position your research topic within the broader field, making the
work accessible to a broader audience, not just to specialists in your field.

2. State the aims and importance


Papers rejected for "not showing the importance of the topic" or "lacking clear motivation"
usually neglect this point. Say what you want to achieve and why your reader should be
interested in finding out whether you achieve it. The basic structure can be as simple as "We
aim to do X, which is important because it will lead to Y."

3. Cite thoroughly but not excessively


Once you've narrowed your focus to the specific topic of your study, you should thoroughly
cover the most recent and most relevant literature pertaining to your study. Your review of the
literature should be complete, but not overly long—remember, you're not writing a review
article. If you find

50
that your introduction is too long or overflowing with citations, one possible solution is to cite
review articles, rather than all the individual articles that have already been summarized in
the review.

4. Avoid giving too many citations for one point


Consider the following sentence: "Many studies have found a significant association between
X and Y [4-15]." This sentence cites too many studies at once. Although references [4-15]
might provide a good overview of the topic, this sentence doesn't provide enough context or
explanation for these past studies. If all of these references are worth citing, they should be
discussed in greater specificity. For example, "A significant association has been found
between X and Y in men [4-7], women [8-11], and children [12-15]."

5. Clearly state either your hypothesis or research question


For research in empirical sciences, stating a hypothesis can be an effective way of framing the
research. For example, instead of stating "In this study, we show that X is related to Y by
method A," you could say, "In this study, we hypothesize that X is related to Y, and we use
method A to test this hypothesis." For research in formal sciences or exploratory research, you
could consider stating a research question instead: "In this study, we examine the following
research question: Is X related to Y?" Note that the research question doesn't always have to
be stated in the interrogative form (with a question mark); instead, you can put the question
into a declarative sentence: "In this study, we investigate whether X is related to Y."
Hypotheses and research questions are effective because they help give shape to the paper
and serve as "signpost phrases" that guide readers through your paper smoothly.

6. Consider giving an overview of the paper


An organizational overview is more common in some fields than others. It is particularly
common in technology, but less so in medicine. In the last paragraph of your introduction,
consider giving a section-by-section overview of your paper if it is appropriate for your field.
For example, "In Section II, we describe our analysis methods and the datasets we used. In
Section III we present the results. In Section IV, we discuss the results and compare our
findings with those in the literature. In Section V, we state our conclusions and suggest
possible topics for future research."

7. Keep it short
Try to avoid an overly long introduction. A good target is 500 to 1000 words, although
checking the journal's guidelines and past issues will provide the clearest guidance.

51
8. Show, don't tell
One goal of the introduction is explaining why your research topic is worthy of study. One of
the most common pitfalls is to simply say, "Subject X is important." Instead of simply saying
that the topic is important, show why the topic is important. For example, instead of writing
"The development of new materials is important for the automotive industry," you could write,
"The development of new materials is necessary for the automotive industry to produce
stronger, lighter vehicles, which will improve safety and fuel economy."

9. Don't bury your readers in detail


In the introduction, if your paper is in a field that commonly summarizes the study's main
results before starting the methods, you should avoid stating too many detailed results
because these results need the development in the other sections of your paper to be properly
understood. Instead of saying "We find that our algorithm requires 55% of the memory and
45% of the computation time of the conventional algorithm," it is usually better to give a
general overview of the findings in the introduction: "Here we compare the proposed
algorithm with a conventional algorithm in terms of memory use and computational speed,
showing that the proposed algorithm is both smaller and faster." Some older style guides
suggest holding back the main result to build suspense, but now journals in many fields—
medicine being a notable exception—encourage giving a preview of your main results in the
introduction.

10. Check the journal requirements


Many journals have specific requirements for the introduction in their guidelines for authors.
For example, there might be a maximum word count stated or the guidelines might require
specific content, such as a hypothesis statement or a summary of your main results.

Concluding remarks
When you begin drafting a paper, the introduction should be one of the first things you plan.
The introduction serves as the roadmap for your paper; by clearly stating the study's
background, aims, and hypothesis/research question, the introduction can guide you as you
write the rest of

52
the paper. It's such an important section—setting the scene for everything that follows—that
many authors write the methods, results, and discussion sections in full before completing the
introduction.

III. Significance of the Study (Adopted from (Thesis Notes : Admin, 2016))
= Significance of the study is written as part of the introduction section of a thesis. It provides
details to the reader on how the study will contribute such as what the study will contribute
and who will benefit from it. It also includes an explanation of the work’s importance as well
as its potential benefits. It is sometimes called rationale.

Tips in Writing the Significance of the Study


Statement of the problem will guide you to write a significance of the study. Based on your
statement of the problem you will see the potential benefits of your study. Just answer this
question, “What are the benefits or advantages of the study based on statement of the
problem?” Determine the specific contribution of your thesis study to the society as well as to
the individual

Below is an example of significance of the study of thesis entitled, “Development of a


Source Material in Food Dehydration Craft Technology for the Secondary Schools” by Mary
Rose Florence
S. Cobar.

Significance of the Study

The study of dehydration technology and fabrication can be a learning paradigm in the

secondary level and vocational schools to enhance the students’ knowledge and

entrepreneurial skills as well. The project’s goal is designed to help students improve

academic competence, develop employability skills, implement a career plan and participate

in a career pathway in preparation for post-secondary education or careers in the food

manufacturing or services sector after graduating from high school.

IV. Scope and Limitation (Adopted from (Viper, 2017)

SCOPE
= refers to how far the research area has explored and parameters in with the study will be
operating in. The type of information to be included in the scope of a research project would
include facts and theories about the subject of the project. The coverage of the study is in
terms of:
1. General purpose
53
2. Population or sample
3. Time or duration
4. Subject matters and topics discussed
5. Area or locality

Example: This investigation as conducted to determine the status of the teaching of


science in the high schools of Province A as perceived by the teachers and students in
science classes during the school year 1989-1990. The aspects looked into were the
qualifications of teachers, their methods and strategies, facilities forms of supervisory
assistance, problems and proposed solutions to the problems.

What Has Been Included?


• General purpose: To determine the status of the teaching of science.
• Subject matter: The teaching of science
• Topics (aspects) studied: Qualifications of teachers, their methods and strategies,
facilities, form of supervisory assistance, problems and proposed solutions to problems
• Population or sample: teachers and students
• Area or locality: High schools of Province
• A Time or duration: School year 1989-1990

LIMITATION
= limitations, also known as the bounds, are influences that the researcher cannot control.
They are the shortcomings, conditions or influences that cannot be controlled by the
researcher that place restrictions on your methodology and conclusions. Any limitations that
might influence the results should be mentioned.

DELIMITATION
= delimitations are choices made by the researcher which should be mentioned. They
describe the boundaries that you have set for the study.

• This is the place to explain:


• The things that you are not doing (and why you have chosen not to do them).
• The literature you will not review (and why not).
• The population you are not studying (and why not).
• The methodological procedures you will not use (and why you will not use them).

54
EXAMPLE:

Although the research has reached its aims, there were some unavoidable limitations. First,
because of the time limit, this research was conducted only on a small size of population who
were attending the Writing 3 course in their third semester at CTU. Therefore, to generalize
the results for larger groups, the study should have involved more participants at different
levels. Second, the students' overloaded work, to some extent, might affect the result of the
correlation between the students' motivation in learning.

When considering what limitations there might be in your investigation, be thorough. Consider
all of the following:
1. Your analysis
2. The nature of self-reporting
3. The instruments you utilized
4. The sample
5. Time constraints to write in English and their writing performance because they were
required to take part in many studies at the same time. Finally, the slow network might
discourage participants' interests and motivation in joining peer feedback activities.

IMPORTANCE of limitations Always acknowledge a study's limitations. It is far better for you to
identify and acknowledge your study's limitations than to have them pointed out by your
professor and be graded down because you appear to have ignored them. Keep in mind that
acknowledgement of a study's limitations is an opportunity to make suggestions for further
research. Claiming limitations is a subjective process because you must evaluate the impact
of those limitations. Don't just list key weaknesses and the magnitude of a study's limitations.
Limitations require a critical, overall appraisal and interpretation of their impact. You should
answer the question: do these problem with errors, methods, validity, etc. eventually matter
and, if so, to what extent? Descriptions of possible limitations all studies have limitations.

V. Entity Relational Diagram (ERD)


= Your Database Design

Document Format

Font Style : Century

Gothic Font Size 10

Spacing : 1.5

Paper Size : A4

55
Margin : 1inch both Top, Bottom, Left and

Right Required Pages

1. Cover Page
a. School Logo
b. Department Logo
c. Use “Presented by:” instead of “Submitted by:” and do not put “Submitted To:”
or “Presented To:”

Example Cover Page (See Next Page)

56
=THIS IS MY PROJECT
TITLE
Information and Communications Technology Department

Presented By

Roronoa Zorro

September 8, 2020

2. Table of Contents
3. References

57
RUBRIC

CRITERA DESCRIPTION REMARKS


Document Required output format/style is applied hundred points Out of
Format percent.
Comment/s:
properly
followed

Document All parts from are available:


points Out of
Contents/Parts
are properly Cover Page Comment/s:
presented Table of
Contents
Introduction
Significance
Scope and Limitation
Entity Relational Diagram(ERD)
References
Thoughts and Idea is explained in a chronological order from
points Out of
Idea are Introduction to ERD
properly laid Comment/s:
out.

Document is Ideas and thoughts copied from different sources to points Out of
properly help the readers understand clearly the thought of
Comment/s:
cited or the project proposal is properly cited/referenced on
referenced the last page of the documents.

TOTAL
General Comment/s:

References

58
CL500. (2020, September 04). Database - Advantages & Disadvantages. Retrieved from http://www.cl500.net/:
http://www.cl500.net/pros_cons.html

eTutorials.org. (2008, September 05). Types of Relationships. Retrieved from http://etutorials.org/:


http://etutorials.org/SQL/Database+design+for+mere+mortals/Part+II+The+Design+Process/Chapter+10.+Table
+Relationships/Types+of+Relationships/

eWEEK. (2020, September 05). Interactive Online SQL Training . Retrieved from SQLCourse.com:
http://www.sqlcourse.com/table.html

Gregory, H. (2018, July 27). Advantages & Disadvantages of Traditional File Organization. Retrieved from
smallbusiness.chron.com: https://smallbusiness.chron.com/advantages-disadvantages-traditional-file-
organization-41400.html

IPTCREWKB. (2020, September 09). Introduction to Storing and Retrieving. Retrieved from
http://iptcrewkb.weebly.com/: http://iptcrewkb.weebly.com/storing-and- retrieving.html#:~:text=Storing
%20and%20retrieving%20is%20a,process%20at%20a%20later%20time.

Rouse, M., Ferguson, K., Biscobing, J., & Aberle, L. (2019, Septermber 04). Entity Relationship Diagram (ERD).
Retrieved from searchdatamanagement.techtarget.com:
https://searchdatamanagement.techtarget.com/definition/entity-relationship-diagram-ERD

Rouse, M., Mullins, C. S., & Christiansen, S. (2020, September 04). Database Management System (DBMS). Retrieved
from SearchSQLServer: https://searchsqlserver.techtarget.com/definition/database-management-system

Sacred Heart University Library. (2020, September 8). Organizing Academic Research Papers: Choosing a Title. Retrieved
from Sacred Heart University: https://library.sacredheart.edu/c.php?g=29803&p=185911#:~:text=The%20title
%20summarizes%20the%20mai n,it%20is%20usually%20read%20first.

Singh, C. (2020, September 09). Primary key in DBMS. Retrieved from


beginnersbook.com: https://beginnersbook.com/2015/04/primary-key-in-dbms/

TEACH COMPUTER SCIENCE. (2020, September 05). Database Data Types. Retrieved from
teachcomputerscience.com: https://teachcomputerscience.com/database-data-types/

Thesis Notes : Admin. (2016, September 19). Writing Thesis Significance of the Study. Retrieved from Thesis
Notes: https://thesisnotes.com/thesis-writing/writing-thesis-significance-of-the- study/#:~:text=Significance
%20of%20the%20study%20is,well%20as%20its%20potential%20benefits.

Viper, L. (2017, May 22). RESEARCH PAPER - SCOPE & LIMITATIONS (Reporting). Retrieved from SCRIBD:
https://www.scribd.com/presentation/349056812/RESEARCH-PAPER-SCOPE-LIMITATIONS-Reporting

Wenzel, K. (2020, September 04). Foreign and Primary Key Differences (Visually Explained). Retrieved from
www.essentialsql.com: https://www.essentialsql.com/what-is-the-difference-between-a-primary-key-and-a-
foreign-key/

Zepernick, J. M. (2006, September 8). 10 tips for writing an effective introduction to original research papers. Retrieved
from Think Science: https://thinkscience.co.jp/en/articles/effective-introductions-to-original-
research#:~:text=The%20introduction%20is%20your%20opportunity,your%20paper%20warrants%20their%20at
tention.&text=It%20presents%20the%20background%20to,an%20overview%20of%20the%20pap

59

You might also like