Sunteți pe pagina 1din 311

MODULE OF INSTRUCTION

Oracle Database
Welcome to the 1st module of this course Database
Management System 1! For this lesson, we will introduce to
you the type of database system and its components.

Database Management A database-management system (DBMS) is a collection of


interrelated data and a set of different application programs
System
use to access those data. This is a collection of related data
with an implicit meaning and hence is a database.

After completing this lesson, the student should be able to:


 Understand what is the difference between data,
information, database and database management
system.
 Discuss the advantage and disadvantage of database
management system.
 Familiarize with the term ER-Model, Entities,
Relationship and Attribute.

The collection of data, also known as the database, contains


information relevant to an enterprise and or in organization.
The main goal of a Database Management System or also
known as DBMS is to provide a way to store, manage and
retrieve database information that is both convenient and
efficient. By data, we mean known facts that can be recorded
and that have implicit meaning. For example, consider the
Database Management System 1 1
Week 1 Data Manipulation Language

student record which have the complete names, course, year


level, and subjects enrolled. With You may have recorded this
data belongs to the student.
A datum – a unit of data – is a symbol or a set of symbols
which is used to represent something. The relationship
between symbols and what they represent is the true value of
what it mean by information. Hence, information is
interpreted data – data supplied with semantics. Knowledge
refers to the practical use of information. While information
can be transported, stored or shared without many difficulties
the same cannot be said about knowledge. Knowledge
necessarily involves a personal experience.

Database systems are designed to manage bulk of


information. The process of managing the data involves both
defining structures for storage of information and providing
mechanisms for the manipulation of information. In addition,
the database system must ensure the security of the
information stored, in the event of system crashes or attempts
at unauthorized access. If the data are shared to different
users, the system must avoid possible anomalous results.
Because information is so important in most organizations,
the reason why computer scientists have developed a large
body of concepts and techniques for managing data in
Database system which is known as Database Management
System.

Types of Handling Data


Handling of data is divided into three types:
1. Data Processing this is the term generally used to

_____________________________________________________________________________________
2
MODULE OF INSTRUCTION
describe what was done by the large computers in the
late 1940's until 1980's. The process of data
processing before is still being done by most large
organization. Example large volumes of raw
transaction data fed into programs that update a master
file, with fixed format reports written to paper.
2. The term Data Management Systems refers to an
expansion of data processing where the raw data that
fed into programs that update a master file, with fixed
format reports written to paper. is now fed into the
system from a variety of sources, including but not
limited to ATMs, EFT, and direct customer entry
through the Internet. The master file concept has been
largely displaced by database management systems,
and static reporting replaced or augmented by ad-hoc
reporting and direct inquiry, including downloading of
data by customers.

3. File Oriented Approach – The computer system in


the earliest business were used to process and manage
business records and produced information. This is
faster and more accurate compared to manual system.
these systems stored groups of records in separate file,
and now called as file processing. In a common file
processing systems, each department has its own files,
designed and stored specifically for those applications.

Characteristics of Database
1. Concurrent Access – is one of the characteristic of a
database system that allows several users to access the

Database Management System 1 3


Week 1 Data Manipulation Language

database concurrently and simultaneously. And


example of this is answering different questions from
different users with the same database is a central
aspect of an information system. The concurrent use
and access of data increases the economy of a system.
2. Structured and Described Data – once of the
fundamental feature of the database approach is that
the database system does not only contain the data but
also the complete definition, structure and description
of these data. These descriptions are the complete
details about the extent, the structure, the type and the
format of all data and, additionally, the relationship
between the data. This kind of stored data is called
metadata.
3. Separation of Data and Applications – As the
structure and describe data is described through
metadata which is also stored in the database.
Application software does not need any knowledge
about the physical data storage like encoding, format,
storage place, structure and the like. The primary task
of application software is to communicate with the
management system via a standardized interface with
the help of a standardized language like SQL or also
know Structure Query Language. The access to the
data and the metadata is done by the DBMS. In this
way, all the applications can be totally separated from
the data.
4. Data Integrity - Data integrity is a mean of quality
and the reliability of the data of a database system. In
a broader sense data, integrity includes also the

_____________________________________________________________________________________
4
MODULE OF INSTRUCTION
protection of the database from unauthorized access
and changes.
5. Transactions - A transaction is a group of actions
which are done within a database to bring it from one
consistent state to a new consistent state. A transaction
is atomic which means that it cannot be divided up
any further. Within a transaction, all or none of the
actions need to be carried out.
6. Data Persistence - Data persistence means that in a
database management system all data is maintained as
long as it is not deleted explicitly in the database. The
life span of data needs to be determined directly or
indirectly be the user and must not be dependent on
system features which means a database administrator
may identify data that must be deleted or retained.

Advantages and Disadvantages of a DBMS


ADBMS has many advantages
1. Data independence: an application programs should
be as independent as possible from details and
structure of data representation and storage. The
Database Management System can provide an abstract
view of the data to insulate application code from such
details.
2. Efficient data access: A Database Management
System utilizes a variety of sophisticated techniques to
store and retrieve data efficiently. This feature is
especially important if the data is stored on external
storage devices.
3. Data integrity and security: If data is always
accessed through the Database Management System,

Database Management System 1 5


Week 1 Data Manipulation Language

the DBMS can enforce integrity constraints on the


data. DBMS can enforce access controls that govern
what data is visible to different classes of users.
4. Data administration: When several users share the
data simultaneously, centralizing the administration of
data can offer significant improvements and security.
5. Concurrent access and crash recovery: A Database
Management System schedule concurrent accesses to
the data in such a manner that users can think of the
data as being accessed by only one user at a time.
Furthermore, the DBMS protects users from the
effects of system failures.
6. Reduced application development time: The
Database Management System supports many
important functions that are common to many
applications which accesses data stored in the DBMS.
This is connected to the high-level interface of data
that facilitates quick development of applications. This
applications are likely to be more robust than
applications developed from scratch or manualy
because many important tasks are handled by the
DBMS instead of being implemented by the
application.

Disadvantages of a DBMS
1. Danger of a Overkill: For small and simple
applications or for single users a database system is
often not advisable.
2. Complexity: Having database system creates
additional complexity and requirements into the

_____________________________________________________________________________________
6
MODULE OF INSTRUCTION
company and or organization. Managing the operation
of a database management system with several users
and databases is quite costly and demanding.
3. Qualified Personnel: The professional operation of a
database system requires fully trained staff. Without a
qualified database administrator nothing will work for
long as no one will able to maintain and manage the
data store in the database.
4. Costs: having a database management system means
new costs are generated for the system itself but also
for additional hardware and the more complex
handling of the system.
5. Lower Efficiency: A database system is a multi-use
software or also known as generic software which is
often less efficient than specialized software which is
produced and optimized exactly for one problem.

Instances, Physical and Logical Schemas


As values are inserted and deleted information in the database
also changes. The group of information stored in the database
at a particular moment is called an instance of the database.
While the overall design of the database is called the
database schema. Schemas are changed infrequently, if at
all.

The physical schema of database describes the design of the


database at the physical level, while the logical schema
describes the design of the database at the logical level.
Database also have several schemas at the view level, also
known as subschemas that describe different views of the
database. The Application programs are used to exhibit

Database Management System 1 7


Week 1 Data Manipulation Language

physical data independence given that it to do not depend on


the physical schema, and thus need not be rewritten if the
physical schema changes.

Data Models
The underlying the structure of a database is the data model: it
is a collection of conceptual tools for describing data,
relationships, semantics, and integrity constraints.

The Entity-Relationship Model


The entity-relationship (E-R) data model is a collection of
different objects, called entities, and of relationships among
these objects. While an entity is a something that describes an
object from other objects.

The connection or association among several entities is called


a relationship. The logical structure or schema of a database
can be represented graphically by an E-R diagram.

Relational Model
The relational model uses a collection of tables to represent
both data and the relationships among those data a table in
relational model is also know an Entity. Each table or entity
has multiple columns or also known as an attribute which is
used to uniquely identify once table or entity to the other, and
each column has a unique name. The data is arranged in a
relation which is visually represented in a two dimensional
table meaning it is a relationship or connections of two or
more table. In the database, the data is inserted into the table
in the form of tuples or also known as values per row. The

_____________________________________________________________________________________
8
MODULE OF INSTRUCTION
relational model is implemented in database where a relation
is represented by a table, a tuple is represented by a row, an
attribute is represented by a column of the table, attribute
name is the name of the column such as ‘identifier’, ‘name’,
‘city’ etc., and attribute value contains the value for column in
the row.

Constraints during or after the creation of table a user may


apply the constraint to the table and form the logical schema.
A constraint is used to uniquely identify a data and restrict
access to the database. In order to identify properly the
selection of which particular row/tuple from the table, the
attributes i.e. column names are used (ID, LASTNAME,
COURSE), and to expedite the selection of the rows some
fields are defined uniquely to use them as indexes, this helps
in searching the required data as fast as possible.

Lesson Summary:
In this lesson, you should have learned the following.
 Database
 Database Management System
 ER Model
 Advantage and Disadvantage if database

Terms to Remember!
 Application programs - are said to exhibit physical
data independence if they do not depend on the
physical schema.
 Data-known facts that can be recorded and that have
implicit meaning.
 Data integrity- is a byword for the quality and the

Database Management System 1 9


Week 1 Data Manipulation Language

reliability of the data of a database system.


 Database-management system (DBMS) - is a
collection of interrelated data and a set of programs
that is used to access and manipulate data stored in the
database.
 Database schema - the overall design of the database
is called the
 Database systems - are designed to manage large
bodies of information.
 Datum – a unit of data – is a symbol or a set of
symbols which is used to represent relevant
information in the database.
 Information - is also known as interpreted data – data
supplied with semantics.
 Instance of the database – is the collection of
information stored in the database at a particular
moment which means the current state of the data.
 Logical schema - describes the design of the database
at the logical level.
 Physical schema - describes the design of the
database at the physical level,
 Relationship - is an association or connection of one
entity to other entities.
 Transaction - is a group of actions or changes made
to the database to bring it from one consistent state to
a new consistent state.

Textbook:

_____________________________________________________________________________________
10
MODULE OF INSTRUCTION
• Oracle Press (2010). Applied Oracle Security

References:
References • Pratt, Philip J. (2010). Database management systems
• Rob, Peter & Coronel, Carlo (2009). Database
Management Systems
• Schwalbe, Kathy (2011). Management of Information
Technology Projects
• Wheeler, Evan (2011). Security Risk Management :
Building an Information Security Risk Management
Program from the Ground Up

Supplementary Links for Reading and Videos


Supplementary Reading
http://www.eazynotes.com/pages/database-management-
system/introduction-to-dbms.html
https://www.w3schools.in/dbms/intro/
http://www.cs.ubc.ca/nest/dbsl/intro.html

Supplementary Video
https://www.youtube.com/watch?v=1057YmExS-I
https://www.youtube.com/watch?v=kTVLO9F1QoY
https://www.youtube.com/watch?v=0uWA4zps-3k

Suggested Reading
• SQL Tutorial. In ws3schools, Retrieved from
http://www.w3schools.com/sql/default.asp
• Database management system. In Encyclopedia
Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/152201/d
atabase-management-system-DBMS.
• SQL. In Encyclopedia Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/569684/
SQL

Database Management System 1 11


Week 1 Data Manipulation Language

• Database Administration. In Encyclopedia.com,


Retrieved from
http://www.encyclopedia.com/topic/Database_adminis
tration.aspx
• SQL. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/SQL.aspx
• Tutorialspoint.com
• oracle.com
• apex.oracle.com

_____________________________________________________________________________________
12
MODULE OF INSTRUCTION

Oracle Database
Welcome to the second module of this course Database
Management System 1! For this lesson, we will features and
usage of Oracle 11 express edition.

Oracle Database An Oracle database is a collection of data that is treated as a


unit. The main purpose of a database is to store, manage and
retrieve related information. In the database, a key in solving
the problems of information management is known as a
database server.

After completing this lesson, the student should be able to:


 Identify the main focus area of Oracle 11g software.
 Discuss each feature of Oracle.
 Familiarize with the 4 types of Oracle statement to be
used for database management system 1 subject.

Oracle Database 11g offers extensive features across the


following focus areas:
• Infrastructure Grids: The Infrastructure Grid
technology of Oracle enables pooling of low-cost
servers and storage to form systems that deliver the
highest quality of service in terms of manageability,
high availability, and performance. Oracle Database
11g consolidates and extends the benefits of grid
computing. Aside from taking full advantage of grid
Database Management System 1 1
Week 3 Data Manipulation Language

computing, Oracle Database 11g has unique change


assurance features that allows the database
administrator to manage changes in a controlled and
cost effective manner.
• Information Management: Oracle Database 11g has
the capability to extends the existing information
management capabilities in content management,
information integration, and information life-cycle
management areas. Oracle provides content
management of advanced data types such as
Extensible Markup Language (XML), text, spatial,
multimedia, medical imaging, and semantic
technologies.
• Application Development: Oracle Database 11g has
capabilities to use and manage all the major
application development environments which include
the following Applications: PL/SQL, Java/JDBC,
.NET and Windows, PHP, SQL Developer, and
Application Express.

Features of Oracle Database 11g


• Manageability: By using some of the change
assurance, management automation, and fault
diagnostics features, the database administrators or
also known as DBA can increase their productivity,
reduce costs, minimize errors, and maximize quality
of service. Some of the useful features that promote
better management are Database Replay facility, the
SQL Performance Analyzer, and the Automatic SQL

_____________________________________________________________________________________
2
MODULE OF INSTRUCTION
Tuning facility.

• High availability: By using the high availability


features, a database administrator may reduce the risk
of down time and data loss. These features improve
online operations which enable faster database
upgrades.

• Performance: In Oracle capabilities such as


SecureFiles, compression for online transaction
processing (OLTP), Real Application Clusters (RAC)
optimizations, Result Caches, and so on, a database
administrator may improve the performance of
database. Oracle Database 11g help the organizations
to manage large, scalable, transactional, and data
warehousing systems that deliver fast data access
using low-cost modular storage.

• Security: For the security, the Oracle Database 11g


helps organizations manage and protect their
information with the help of unique and secure
configurations, data encryption and masking, and
sophisticated auditing capabilities. This delivers a
secure and scalable platform for reliable and fast
access to all types of information by using the
industry-standard interfaces.

• Information integration: The integration part of


Oracle Database 11g has many features to better
integrate data throughout the enterprise. It also
supports advanced information life-cycle
management capabilities. This helps you manage the
changing data in your database

Database Management System 1 3


Week 3 Data Manipulation Language

Object Relational Database Management System

• Is also known Relational model and object relational


model

• A user-defined data types and objects

• An Object Relational is fully compatible with


relational database

• It supports multimedia and large objects

• Include a high-quality database server features

Relational Database Concept

• In 1970 the relational model was proposed by Dr. E.F


Codd and has been the basis for Relational Database
Management System.

• The relational model is consists of the following:

• A collection of objects (entities) or relations

• A set of operators to act on the relations


which is used to identify the relationship that
may exist per object.

• A data integrity for accuracy and consistency


of data

_____________________________________________________________________________________
4
MODULE OF INSTRUCTION
• A relational database is a collection of relations or a
connection of two-dimensional tables controlled by
the Oracle server.

Relating Multiple Tables

• Each row of data in a table can be uniquely identified


by adding a primary key during or after the table has
been created.

• A user can logically relate data from multiple tables


using foreign keys or also known as the connection
between two or more table.

Using SQL to Query Your Database

Structured query language (SQL) is:

• Is also know as the ANSI standard language for


operating relational databases

• Efficient, easy to learn, and use

• Complete with SQL, where a user can define,


retrieve, and manipulate data in the tables.

SQL Statements Used in the Course

1. Data manipulation language (DML

Database Management System 1 5


Week 3 Data Manipulation Language

 SELECT

 INSERT

 UPDATE

 DELETE

 MERGE

2. Data definition language (DDL)

 CREATE

 ALTER

 DROP

 RENAME

 TRUNCATE

 COMMENT

3. Data control language (DCL

 GRANT

 REVOKE

4. Transaction control

 COMMIT

 ROLLBACK

 SAVEPOINT

Lesson Summary:
In this lesson, you should have learned the following.

_____________________________________________________________________________________
6
MODULE OF INSTRUCTION
• Focus area of Oracle;

• Features; and

• Different type of oracle statements

Terms to Remember!
• In 1970 the relational model was proposed by Dr.
E.F Codd and has been the basis for Relational
Database Management System.
• A relational database is a collection of relations or a
connection of two-dimensional tables controlled by
the Oracle server.

Textbook:
• Oracle Press (2010). Applied Oracle Security

References:
• Pratt, Philip J. (2010). Database management systems
• Rob, Peter & Coronel, Carlo (2009). Database
Management Systems
• Schwalbe, Kathy (2011). Management of Information
Technology Projects
• Wheeler, Evan (2011). Security Risk Management :
Building an Information Security Risk Management
Program from the Ground Up

References
Suggested Reading
• SQL Tutorial. In ws3schools, Retrieved from
http://www.w3schools.com/sql/default.asp

Database Management System 1 7


Week 3 Data Manipulation Language

• Database management system. In Encyclopedia


Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/152201/
database-management-system-DBMS.
• SQL. In Encyclopedia Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/569684/
SQL
• Database Administration. In Encyclopedia.com,
Retrieved from
http://www.encyclopedia.com/topic/Database_admini
stration.aspx
• SQL. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/SQL.aspx
• Tutorialspoint.com
• oracle.com
• apex.oracle.com

_____________________________________________________________________________________
8
MODULE OF INSTRUCTION

Oracle Database Installation Guide

Welcome to the second module of this course. For this lesson, we will
discuss the task of Database Administrator, System requirement and
Installation procedure.

Before a student may proceed on the next chapter installing this


software Oracle Database 11g is a prerequisite. Student need to create
an account to www.oracle.com in order to download the 11g database
software, moreover without installing the software may hinder the
student to complete the course due to activity file for manual grading
are included in this course.

Oracle Database 11g


This course used the Oracle Database 11g Express Edition (Oracle
Database XE) is an entry-level, small-footprint database based on the
Oracle Database 11g Release 2 code base. It's free to develop, deploy,
and distribute; fast to download; and simple to administer.

At the end of the lesson the student should be able to:

• Describe his/her role as a database administrator (DBA) and


explain typical tasks and tools.

• Plan an Oracle software installation.

• Install the Oracle database software.

The task of a database administor

A database administrator task involved the approach for designing,


implementing, and maintaining an Oracle database which involves the
following tasks:

1. Evaluating the database server hardware needed for


installation
2. Installing the Oracle software
3. Planning the database design and different security
strategy
4. Creating, migrating, and opening the database in
different scenario
5. Backing up the database.

Database Management System 2 1


Week 2 Oracle Database 11g Installation Guide

6. Enrolling system users and or creating new user and


roles as well as planning for their Oracle Network
access.
7. Implementing the database design develop
8. Recovering from database failure or system failure
9. Monitoring database performance at all times

Tools for Administering

1. Oracle Universal Installer


2. Database Configuration Assistant
3. Database Upgrade Assistant
4. Oracle Net Manager
5. Oracle Net Configuration Assistant
6. Oracle Enterprise Manager
7. Server Control Utility
8. Recovery Manager
9. SQL*Loader

Consideration guideline when planning to install Oracle Database 11g

• What Oracle software the database is planning to install?

• Does the current hardware/computer system used by the user


meet the minimum required specifications?

• Is there a recommended order of installation that a user must


follow when multiple products are involved?

• Are there other steps that must be performed by other user


other than the DBA?

System Requirements

1. Memory requirements:

 1 GB for the database instance with Oracle Enterprise


 Manager Database Control
 1.5 GB for the ASM instance and Oracle Restart
2. Disk space requirements

 3 GB of swap space (based on 2 GB RAM)

2
MODULE OF INSTRUCTION

 1 GB of disk space in the /tmp directory


 3.8 GB for the Oracle Database software
 4.5 GB for the Grid Infrastructure software
 1.7 GB for the preconfigured database (optional)
 3.4 GB for the fast recovery area (optional)

3. Operating system

Preparing the Operating System

Create the required operating system users and groups:

– Groups:
– oinstall
– dba
Optional groups (if doing separation of duty across multiple users):

– oper
– asmdba
– asmoper
– asmadmin
• Software owner, usually oracle

• Can create multiple users for multiple product installations

Setting environment Variables:

Oracle environment variables:

1. ORACLE_BASE: Base of the Oracle directory structure.

 Recommended to set this before installation.

2. ORACLE_HOME: The environment in which Oracle


products run. Not required before installation if
ORACLE_BASE is set.

3. ORACLE_SID: Not required before installation, but useful


afterwards for ease of interaction with a particular instance

4. NLS_LANG: Optional environment variable that controls


language, territory, and client character set settings

Database Management System 2 3


Week 2 Oracle Database 11g Installation Guide

Requirements:

• Adequate temporary space


• 64-bit versus 32-bit issues
• Correct operating system (OS)
• OS patch level
• System packages
• System and kernel parameters
• X Server permissions
• Sufficient swapping
• ORACLE_HOME status

Installation Guide:

Step 1:

• Download Oracle Database thru www.oracle.com


• Click on License Agreement
• Choose the type of Operating system used.

Step 2:

• If with existing oracle account provide information on the left


side then click sign in
• If a new user click the CREATE ACCOUNT

4
MODULE OF INSTRUCTION

Step 3:

• Fill up the form with necessary information mark in * are


required field.
• Click Submit

Step 3:

• Once the account is created open your email to confirm the


verification code sent by Oracle.

Step 4:

• Verify the link sent by oracle

Database Management System 2 5


Week 2 Oracle Database 11g Installation Guide

Step 5:
 Once verified the downloading the Oracle will start

Step 6:

 When download is completed double click the rar file >


Click on DISK1>followed by setup.exe
 Clicking the setup.exe will automatically extract the file
downloaded file.

6
MODULE OF INSTRUCTION

Step 7:

 Wait the installation wizard to finish extracting the Oracle


Database 11Express Edition

Database Management System 2 7


Week 2 Oracle Database 11g Installation Guide

 Once done click Next

 Accept the license agreement

8
MODULE OF INSTRUCTION

 Choose location where to install the software, or you may use


the default drive.

 Set you global password: suggested is oracle


Note: for uniformity student are required to follow the
suggested username and password in order to follow on the
succeeding examples.

Database Management System 2 9


Week 2 Oracle Database 11g Installation Guide

 Wait the setting to check all the required setting environment

 Click Finish

10
MODULE OF INSTRUCTION

Note:
1. After clicking the finish button, locate the Oracle 11g
Express edition Folder found on the start menu of your
Operating system.
2. Then click the folder, click the PL/SQL Command Line.
3. When the CMD is open try to log-in using the username
and password set during installation.
4. Type in Connect then click enter
5. Then type the password: oracle (note typing the password
is hidden on the screen)
You must have the CONNECTED message. This means you
successfully log-in in Oracle using the PL/SQL command line.

Lesson Summary:
Before preceding with the next Chapters the student should
finished the following:
 Create Oracle Account – www.oracle.com
 Successfully Install Oracle Database 11g Express
Edition
 Able to establish as user Connection at isqlplus using:
CONNECT
USERNAME: SYSTEM (Global Connection to Oracle)
PASSWORD: oracle (password inputted by the student during
installation)

Database Management System 2 11


Week 2 Oracle Database 11g Installation Guide

Glossary
 NLS_LANG: Optional environment variable that controls
language, territory, and client character set settings

 ORACLE_BASE: Base of the Oracle directory structure.


Recommended to set this before installation.

 ORACLE_HOME: The environment in which Oracle


products run. Not required before installation if
ORACLE_BASE is set.

 ORACLE_SID: Not required before installation, but useful


afterwards for ease of interaction with a particular instance

References
Textbook:
 Oracle Database 11g 2nd Edition K Gopalakrishnan (
2012)

References:
 Carlos, Peter (2009). Database Systems
 Connoly, Thomas & Begg, Carolyn (2010). Database
Systems : A practical approach to design,
implementation and management
 Sciore, Edward (2009). Database Design and
Implementation
 Bulusu, Lakshman (2008). Oracle PL/SQL : Expert
Techniques for Developers and Database
Administrators
 Loshin, David (2008). Master Data Management

Supplementary Reading and Video Link


Supplementary Reading

https://docs.oracle.com/cd/B19306_01/server.102/b14220/intro.htm
http://ugweb.cs.ualberta.ca/~c391/manual/chapt1.html
http://www.oracle-dba-online.com/introduction_to_oracle.htm

12
MODULE OF INSTRUCTION

Supplementary Video
https://www.youtube.com/watch?v=2deZysmz9rE&index=1&list=PLg
Xga1uh_X7dkEmttwzU7ulLa_abCq0N4
https://www.youtube.com/watch?v=B1EO24v2ico
https://www.youtube.com/watch?v=2deZysmz9rE

Other Suggested Readings (e.g. periodicals, articles, websites, IT


applications/software, etc.):
 www.oracle.com
 www.apex.oracle.com
 SQL Tutorial. In ws3schools, Retrieved from
http://www.w3schools.com/sql/default.asp
 SQL. In Encyclopedia Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/569684/S
QL
 Database Administration. In Encyclopedia.com,
Retrieved from
http://www.encyclopedia.com/topic/Database_administ
ration.aspx
 SQL. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/SQL.aspxLearning
Icons

Database Management System 2 13


MODULE OF INSTRUCTION

Oracle Database Installation Guide

Welcome to the second module of this course. For this lesson, we will
discuss the task of Database Administrator, System requirement and
Installation procedure.

Before a student may proceed on the next chapter installing this


software Oracle Database 11g is a prerequisite. Student need to create
an account to www.oracle.com in order to download the 11g database
software, moreover without installing the software may hinder the
student to complete the course due to activity file for manual grading
are included in this course.

Oracle Database 11g


This course used the Oracle Database 11g Express Edition (Oracle
Database XE) is an entry-level, small-footprint database based on the
Oracle Database 11g Release 2 code base. It's free to develop, deploy,
and distribute; fast to download; and simple to administer.

At the end of the lesson the student should be able to:

• Describe his/her role as a database administrator (DBA) and


explain typical tasks and tools.

• Plan an Oracle software installation.

• Install the Oracle database software.

The task of a database administor

A database administrator task involved the approach for designing,


implementing, and maintaining an Oracle database which involves the
following tasks:

1. Evaluating the database server hardware needed for


installation
2. Installing the Oracle software
3. Planning the database design and different security
strategy
4. Creating, migrating, and opening the database in
different scenario
5. Backing up the database.

Database Management System 2 1


Week 2 Oracle Database 11g Installation Guide

6. Enrolling system users and or creating new user and


roles as well as planning for their Oracle Network
access.
7. Implementing the database design develop
8. Recovering from database failure or system failure
9. Monitoring database performance at all times

Tools for Administering

1. Oracle Universal Installer


2. Database Configuration Assistant
3. Database Upgrade Assistant
4. Oracle Net Manager
5. Oracle Net Configuration Assistant
6. Oracle Enterprise Manager
7. Server Control Utility
8. Recovery Manager
9. SQL*Loader

Consideration guideline when planning to install Oracle Database 11g

• What Oracle software the database is planning to install?

• Does the current hardware/computer system used by the user


meet the minimum required specifications?

• Is there a recommended order of installation that a user must


follow when multiple products are involved?

• Are there other steps that must be performed by other user


other than the DBA?

System Requirements

1. Memory requirements:

 1 GB for the database instance with Oracle Enterprise


 Manager Database Control
 1.5 GB for the ASM instance and Oracle Restart
2. Disk space requirements

 3 GB of swap space (based on 2 GB RAM)

2
MODULE OF INSTRUCTION

 1 GB of disk space in the /tmp directory


 3.8 GB for the Oracle Database software
 4.5 GB for the Grid Infrastructure software
 1.7 GB for the preconfigured database (optional)
 3.4 GB for the fast recovery area (optional)

3. Operating system

Preparing the Operating System

Create the required operating system users and groups:

– Groups:
– oinstall
– dba
Optional groups (if doing separation of duty across multiple users):

– oper
– asmdba
– asmoper
– asmadmin
• Software owner, usually oracle

• Can create multiple users for multiple product installations

Setting environment Variables:

Oracle environment variables:

1. ORACLE_BASE: Base of the Oracle directory structure.

 Recommended to set this before installation.

2. ORACLE_HOME: The environment in which Oracle


products run. Not required before installation if
ORACLE_BASE is set.

3. ORACLE_SID: Not required before installation, but useful


afterwards for ease of interaction with a particular instance

4. NLS_LANG: Optional environment variable that controls


language, territory, and client character set settings

Database Management System 2 3


Week 2 Oracle Database 11g Installation Guide

Requirements:

• Adequate temporary space


• 64-bit versus 32-bit issues
• Correct operating system (OS)
• OS patch level
• System packages
• System and kernel parameters
• X Server permissions
• Sufficient swapping
• ORACLE_HOME status

Installation Guide:

Step 1:

• Download Oracle Database thru www.oracle.com


• Click on License Agreement
• Choose the type of Operating system used.

Step 2:

• If with existing oracle account provide information on the left


side then click sign in
• If a new user click the CREATE ACCOUNT

4
MODULE OF INSTRUCTION

Step 3:

• Fill up the form with necessary information mark in * are


required field.
• Click Submit

Step 3:

• Once the account is created open your email to confirm the


verification code sent by Oracle.

Step 4:

• Verify the link sent by oracle

Database Management System 2 5


Week 2 Oracle Database 11g Installation Guide

Step 5:
 Once verified the downloading the Oracle will start

Step 6:

 When download is completed double click the rar file >


Click on DISK1>followed by setup.exe
 Clicking the setup.exe will automatically extract the file
downloaded file.

6
MODULE OF INSTRUCTION

Step 7:

 Wait the installation wizard to finish extracting the Oracle


Database 11Express Edition

Database Management System 2 7


Week 2 Oracle Database 11g Installation Guide

 Once done click Next

 Accept the license agreement

8
MODULE OF INSTRUCTION

 Choose location where to install the software, or you may use


the default drive.

 Set you global password: suggested is oracle


Note: for uniformity student are required to follow the
suggested username and password in order to follow on the
succeeding examples.

Database Management System 2 9


Week 2 Oracle Database 11g Installation Guide

 Wait the setting to check all the required setting environment

 Click Finish

10
MODULE OF INSTRUCTION

Note:
1. After clicking the finish button, locate the Oracle 11g
Express edition Folder found on the start menu of your
Operating system.
2. Then click the folder, click the PL/SQL Command Line.
3. When the CMD is open try to log-in using the username
and password set during installation.
4. Type in Connect then click enter
5. Then type the password: oracle (note typing the password
is hidden on the screen)
You must have the CONNECTED message. This means you
successfully log-in in Oracle using the PL/SQL command line.

Lesson Summary:
Before preceding with the next Chapters the student should
finished the following:
 Create Oracle Account – www.oracle.com
 Successfully Install Oracle Database 11g Express
Edition
 Able to establish as user Connection at isqlplus using:
CONNECT
USERNAME: SYSTEM (Global Connection to Oracle)
PASSWORD: oracle (password inputted by the student during
installation)

Database Management System 2 11


Week 2 Oracle Database 11g Installation Guide

Glossary
 NLS_LANG: Optional environment variable that controls
language, territory, and client character set settings

 ORACLE_BASE: Base of the Oracle directory structure.


Recommended to set this before installation.

 ORACLE_HOME: The environment in which Oracle


products run. Not required before installation if
ORACLE_BASE is set.

 ORACLE_SID: Not required before installation, but useful


afterwards for ease of interaction with a particular instance

References
Textbook:
 Oracle Database 11g 2nd Edition K Gopalakrishnan (
2012)

References:
 Carlos, Peter (2009). Database Systems
 Connoly, Thomas & Begg, Carolyn (2010). Database
Systems : A practical approach to design,
implementation and management
 Sciore, Edward (2009). Database Design and
Implementation
 Bulusu, Lakshman (2008). Oracle PL/SQL : Expert
Techniques for Developers and Database
Administrators
 Loshin, David (2008). Master Data Management

Supplementary Reading and Video Link


Supplementary Reading

https://docs.oracle.com/cd/B19306_01/server.102/b14220/intro.htm
http://ugweb.cs.ualberta.ca/~c391/manual/chapt1.html
http://www.oracle-dba-online.com/introduction_to_oracle.htm

12
MODULE OF INSTRUCTION

Supplementary Video
https://www.youtube.com/watch?v=2deZysmz9rE&index=1&list=PLg
Xga1uh_X7dkEmttwzU7ulLa_abCq0N4
https://www.youtube.com/watch?v=B1EO24v2ico
https://www.youtube.com/watch?v=2deZysmz9rE

Other Suggested Readings (e.g. periodicals, articles, websites, IT


applications/software, etc.):
 www.oracle.com
 www.apex.oracle.com
 SQL Tutorial. In ws3schools, Retrieved from
http://www.w3schools.com/sql/default.asp
 SQL. In Encyclopedia Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/569684/S
QL
 Database Administration. In Encyclopedia.com,
Retrieved from
http://www.encyclopedia.com/topic/Database_administ
ration.aspx
 SQL. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/SQL.aspxLearning
Icons

Database Management System 2 13


MODULE OF INSTRUCTION

Data Manipulation Language


Welcome to the fourth module of this course Database
Management System 1! For this lesson, we will discuss the
Data Manipulation Language or also known as DML.

Data Manipulation Language is used to insert update and


delete value in the table.

DML Data manipulation language (DML) is a core part of SQL.


When you want to add, update, or delete data in the database,
you execute a DML statement. A collection of DML
statements that form a logical unit of work is called a
transaction.

After completing this lesson, the student should be able


to:
 Insert new values in the table using the INSERT
statement.
 Modify existing values in the table using the
UPDATE statement
 Delete existing row using DELETE statement.

Data Manipulation Language


A DML statement is executed when you:
 Add new rows to a table using INSERT statement

Database Management System 1 1


Week 3 Data Manipulation Language

 Modify existing rows in a table suing UPDATE


statement
 Remove existing rows from a table using DELETE
statement

A transaction consists of a collection of DML statements


that form a logical unit of work.
 Consider an enrollment database. When a student
already took the subject, the status of this subject
should be updated from enrolled to pass, as well a the
year level of the student must also change.

INSERT statement
 Insert a new row containing values for each column.
 List values in the default order of the columns in the
table.
 Optionally, list the columns in the INSERT clause.
 Enclose character and date values within single
quotation marks.
 Add new rows to a table by using the INSERT
statement:
 Syntax:
INSERT INTO tbl_name values (column_list);
 In the syntax:
o TBL_NAME - Is the name of the table
o COLUMN_LIST - Is the name of the column
in the table to populate
o VALUES - Is the corresponding value for the
column

_____________________________________________________________________________________
2
MODULE OF INSTRUCTION

 Old Table: with three values

 Suppose that the STUDENTS table is composed of 3


rows and a user wanted to add a new student record:
 Example:
INSERT INTO STUDENTS VALUES
(500,'REYES','ANNA','BSIS','1');
 To confirm that ANNA was successfully added used
the SELECT statement:

 As shown in the image above notice that Anna is now


one of the students recorded in STUDENTS table.

Inserting Rows with Null Values


 Implicit method: Omit the column from the
column list.
 Example:
INSERT INTO STUDENTS
(USN_ID,LASTNAME)
VALUES (502,'CUBAO');

Database Management System 1 3


Week 3 Data Manipulation Language

 Output:

 As you notice, in the implicit method specific


columns are specified during the insertion before the
values are added in the VALUES clause using this
method will automatically set the column to NULL to
those columns which are not called in the INSERT
INTO statement.

 Explicit method: Specify the NULL keyword in the


VALUES clause.
 EXAMPLE:
INSERT INTO STUDENTS VALUES
(505,'ABIOG','SHIELA',NULL,NULL);
 Output:

 As shown in the example, using the implicit method


this method is used to insert all values according to its
order in the column lists, however, notice that to

_____________________________________________________________________________________
4
MODULE OF INSTRUCTION
those values with no inputs this is set to NULL in the
INSERT INTO statement. By using this method
automatically column with values set to NULL will
automatically have NULL values.

Changing Data in a Table


 Modify existing values in a table with the UPDATE
statement:
 Syntax:
UPDATE TBL_NAME
SET COLUMN = NEW VALUES
[WHERE CONDITION];
 In the syntax:
Tbl_name - Is the name of the table
set column - Is the name of the column in the table to
populate
new_value - Is the corresponding value or subquery
for the column
condition - Identifies the rows to be updated by using
comparison operator, logical condition
and or adding subqueries.

 As shown in the table supposed that we wanted to


update the firstname to ‘MARVIN’ of students with
USN_ID equal to 502. To do that we may need to use

Database Management System 1 5


Week 3 Data Manipulation Language

the UPDATE statement.


 Example:
UPDATE STUDENTS
SET FIRSTNAME = 'MARVIN'
WHERE USN_ID=502;
 Output:

 As you notice in the output the firstname of student


with USN_ID equal to 502 is not updated to
MARVIN.
 Where condition identifies into which specific
column the user wanted to make the changes given in
the SET clause.

Updating two columns in one UPDATE statement.


 To update to or more columns in one UPDATE
statement put a comma (,) after each column called in
the SET clause.
 Example:
UPDATE STUDENTS
SET YR_LVL='IRREG', LASTNAME = 'ABIOG'
WHERE USN_ID = 505;

_____________________________________________________________________________________
6
MODULE OF INSTRUCTION
 Output: Old table

 Output: New table

 Compare the Old and new table after the Update


statement is issued as you notice the LASTNAME
and YR_LVL of the student of USN_ID equal to 505
were updated by using 1 UPDATE statement.

DELETE Statement
 You can remove existing rows from a table by using
the DELETE statement:
 Syntax:
DELETE FROM TBL_NAME
WHERE CONDITION;
 In the syntax:
Tbl_name - Is the name of the table
Where condition - Identifies the rows to be deleted,
and is composed of column names, expressions,
constants, subqueries, and comparison operators.

Database Management System 1 7


Week 3 Data Manipulation Language

 If WHERE condition is added on the statement,


specific rows will be deleted
 Example:
DELETE FROM STUDENTS
WHERE YR_LVL='1';
 Output: Old table

 Output: New table

 As by comparing old and new output notice that 2


rows with YR_LCL equal to 1 are deleted as shown
in the new output.
 All rows in the table are deleted if you omit the
WHERE clause:
 Example:
DELETE FROM STUDENTS;
 Output:

_____________________________________________________________________________________
8
MODULE OF INSTRUCTION
 As in the output all rows are deleted if WHERE
clause is omitted.

Lesson Summary:
In this lesson, you should have learned how to use the
following statements:

 Insert into to add new rows in a table

 Update to modify existing values is a table

 Delete to remove specific rows in a table

Terms to Remember!
 DELETE – a statement use to remove existing rows
in a table.
 DML – stand for Data Manipulation Language.
 Explicit method - an Insert statement that Specifies
the NULL keyword in the VALUES clause.
 Implicit method - an Insert statement that Omits the
column from the column list.
 INSERT - a statement used to add new rows in a
table.
 Transaction - consists of a collection of DML
statements that form a logical unit of work.
 UPDATE - a statement used to update existing rows
in a table.

References Textbook:
 Oracle Press (2010). Applied Oracle Security

References:
 Pratt, Philip J. (2010). Database management systems

Database Management System 1 9


Week 3 Data Manipulation Language

 Rob, Peter & Coronel, Carlo (2009). Database


Management Systems
 Schwalbe, Kathy (2011). Management of Information
Technology Projects
 Wheeler, Evan (2011). Security Risk Management :
Building an Information Security Risk Management
Program from the Ground Up

Supplementary Reading and Video Link


Supplementary Reading
https://docs.microsoft.com/en-us/sql/t-sql/queries/queries
https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-data-
manipulation.html
https://docs.oracle.com/database/121/TDDDG/tdddg_dml.htm#T
DDDG99941

Supplementary Video
https://www.youtube.com/watch?v=S54W4oSqp7s
https://www.youtube.com/watch?v=vnFu6sBfcSs
https://www.youtube.com/watch?v=0EmMIUvjPbA

Suggested Reading
 SQL Tutorial. In ws3schools, Retrieved from
http://www.w3schools.com/sql/default.asp
 Database management system. In Encyclopedia
Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/152201/
database-management-system-DBMS.
 SQL. In Encyclopedia Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/569684/
SQL
 Database Administration. In Encyclopedia.com,
Retrieved from
http://www.encyclopedia.com/topic/Database_admini

_____________________________________________________________________________________
10
MODULE OF INSTRUCTION
stration.aspx
 SQL. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/SQL.aspx
 Tutorialspoint.com
 oracle.com
 apex.oracle.com

Database Management System 1 11


MODULE OF INSTRUCTION

Data Retrieval using Basic


SELECT Statement
Welcome to the fifth module of this course Database
Management System 1! For this lesson, it covers the
different statement that can be applied using the SELECT
statement. Sample and demonstration in this lesson uses the
AUTHORS table as shown below:
Table 1.0 Authors

The select statement is used to create different types of


reports where the user can apply the basic select, restrict the
rows returned by the query, use single row or multiple row
functions and sort the data either ascending or descending.

Database Management System 1 1


Week 3 Basic SELECT Statement

SELECT A SELECT statement is a used to retrieves information from


the database. With a SELECT statement, you can do the
following:
• Projection: Selects the columns in a table that are
returned by a query. Selects a few or as many of the
columns as required.
• Selection: Selects the rows in a table that are returned by
a query. Various criteria can be used to restrict the rows
that are retrieved.
• Joins: Brings together data that is stored in different
tables by specifying the link between them.

After completing this lesson, the student should be able


to:
• List the capabilities of SQL SELECT statements
• Execute a basic SELECT statement

Basic SELECT Statement


• Is used to create a different type of report.
• Syntax:
SELECT (COLUMN_LIST [EXPRESSION])
FROM TBLE_NAME
• Where:
o A SELECT clause, which is use to specify which
column to be displayed
o A FROM clause, which is use to specify the table
containing the columns that are listed in the
SELECT clause

_____________________________________________________________________________________
2
MODULE OF INSTRUCTION
Select (ALL) column
• You can display all rows and column in a table by using
the SELECT followed by (*) asterisk.
• (*) is used to call/display all row in column.
• Example:
SELECT * FROM AUTHORS
• Output:


• As shown in the output all rows and columns in the
AUTHORS table are displayed.

Select SPECIFIC row


• You can use the SELECT statement to display specific
columns of the table by specifying the column names,
separated by commas.
• In the SELECT clause, specify the columns that you
want to be displayed in the order in which you want them
to appear in the output.
• For example, to display the last name before the first
name of author in AUTHORS table use the following
example

Database Management System 1 3


Week 3 Basic SELECT Statement

• Example:
SELECT LNAME, FNAME
FROM AUTHORS;
• Output:

• As shown the output the specific columns displayed in


the output are LNAME and FNAME notice that in the
original values in AUTHORS table the first column
should be FNAME followed by LNAME but since in the
select statement we call first the LNAME then it is also
displayed first as shown in the output above.

Writing SQL Statements guidelines


• SQL statements are not case-sensitive a combination of
upper and lower case will do.
• SQL statements can be entered on one or many lines this
is used to make the codes more readable.
• Keywords cannot be split across lines or abbreviated
example a SELECT should be written as SELECT not
SE LECT.
• Clauses are usually placed on separate lines for
readability and ease of editing but no effect on codes.
• Indents should be used to makes the code more readable
only and no effect on the codes.

_____________________________________________________________________________________
4
MODULE OF INSTRUCTION
• Keywords typically are entered in uppercase; all other
words, such as table names and columns names are
entered in lowercase this is to make the codes readable.

Arithmetic Expressions
• Use arithmetic expression in order to create expression
with number and date values.
• An arithmetic expression can contain column names,
constant numeric values, and the arithmetic operators.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
• Just in case you wanted to create a report that computes
for the possible additional year of 5 to all books
published by the author.
• Example:
SELECT LNAME, FNAME, BOOK, YR_PUB + 5
FROM AUTHORS;
• Output:


• As shown in the output originally the year publish of Mr.

Database Management System 1 5


Week 3 Basic SELECT Statement

Hernandez book is 2010, since in the select statement we


use the arithmetic expression which adds 5 more years to
YR_PUB column.

Operator Precedence
If the select statement containing an arithmetic expression
with more than one operator, multiplication, and division are
evaluated first. However, if operators in an expression are of
the same priority, evaluation is done from left to right.
You can use parentheses to force the expression that is
enclosed by the parentheses to be evaluated first.

Rules of Precedence
• Multiplication and division are evaluated first before
addition and subtraction.
• Operators of the same priority are evaluated from left to
right.
• Parentheses ( ) are used to override the default
precedence or to clarify the statement.
• Example: without the parentheses operator
SELECT LNAME, FNAME, BOOK, 10 * YR_PUB +
5
FROM AUTHORS;

_____________________________________________________________________________________
6
MODULE OF INSTRUCTION

• Output:

• Example: with parentheses operator


SELECT LNAME, FNAME, BOOK, 10 * (YR_PUB + 5)
FROM AUTHORS;
• Output:

• As shown in the output for example of with and without


parentheses, in without parentheses the oracle server
follows the order of precedence in which the
multiplication is evaluated first before addition. This
means oracle compute first for 10 multiplied to the
YR_PUB then add 5 to the output for multiplication.
• While when parentheses is added the oracle evaluate first
or force to prioritize the computation inside the open and
close parenthesis, this means it compute first for
YR_PUB + 5 then the output for the addition is

Database Management System 1 7


Week 3 Basic SELECT Statement

multiplied to 10.

Defining NULL values


 In database, Null is a value that is unavailable,
unassigned, unknown, or inapplicable.
 Null are not the same as zero or a blank space.
 If a row lacks a data value for a column, that value is
said to be null or to contain a null.
 By default, all select statement may contain a null
value.
 Example:
SELECT ID, FNAME, TYPE, YR_PUB
FROM AUTHORS;

• Output:

• In the output, the columns with NULL values are those


with blank values and these are FNAME, YR_PUB.
Value for ID 17 and 20 FNAME are NULL while the
value of ID 20 for YR_PUB is NULL.

Null values are Arithmetic Expression


• If any or all column value in an arithmetic expression is
null, the result is also null.

_____________________________________________________________________________________
8
MODULE OF INSTRUCTION
• For example, if you attempt to perform division by zero,
you get an error. However, if you divide a number by
null, the result is a null or unknown.
• Example:
SELECT LNAME, FNAME, BOOK, 10 * YR_PUB * 5
FROM AUTHORS;
• Output:

• Explanation:
Notice that value for the ID 20 for the YR_PUB
column is still NULL.

Column Aliases
When displaying the result of a query, the name of the
column after the table has been created will be once to be
displayed in the output. This column heading may not be
descriptive and, therefore, may be difficult to understand
most especially if it contains additional SELECT like
arithmetic expression. To change a column heading use a
column alias.

A column alias:
• Renames a column heading
• Is useful for calculations
• Immediately follows the column name (There can also be
the optional AS keyword between the column name and
the alias.)
• Requires double quotation marks if it contains spaces or
special characters, or if it is case-sensitive

Database Management System 1 9


Week 3 Basic SELECT Statement

• Example: AS Keyword
SELECT FNAME AS NAME, LNAME AS
SURNAME, YR_PUB + 5 AS YEAR
FROM AUTHORS;

• Example: with Double Quotation Mark “”


SELECT FNAME "GIVEN NAME", LNAME
"SURNAME", YR_PUB + 5 "YEAR PUBLISHED"
FROM AUTHORS;

• Example: combination of AS and “” mark


SELECT FNAME AS "GIVEN NAME", LNAME AS
"SURNAME", YR_PUB + 5 AS "YEAR PUBLISHED"
FROM AUTHORS;

_____________________________________________________________________________________
10
MODULE OF INSTRUCTION

• As shown on the three ways of renaming a table alias


will do and generate the same output as long as you
follow the guideline in using the column alias.

Concatenation operator:
• Links columns or character strings to other columns
• Is represented by two vertical bars (||)
• Creates a resultant column that is a character expression
• Example:
SELECT LNAME||FNAME AS "COMPLETE NAME", BOOK

FROM AUTHORS;

• Output:

• Explanation: As shown in the example the lname and


fname are merge or concatenated into one column and
this column is renamed Complete Name.

Database Management System 1 11


Week 3 Basic SELECT Statement

• Notice also that two columns are combined without the


space to out a space in between two columns you may
add literal character string in between.

Literal Character Strings


• A literal is a character, is either a number, or a date that
may be included in the SELECT statement.
• A select statement with date and character literal values
must be enclosed within single quotation marks.
• Literal strings added in the query is included in the query
result and are treated the same as a column in the
SELECT list.
• Each character string is output once for each row
returned
• Example:
SELECT LNAME||' , '||FNAME AS
"COMPLETE NAME", BOOK
FROM AUTHORS;

• Output:

• Explanation: as shown in the output lname and fname


now have spaces and additional character in between.
• Additional Example: Concatenation two or more

_____________________________________________________________________________________
12
MODULE OF INSTRUCTION
columns:
SELECT LNAME||' , '||FNAME|| ' is the author of
' ||BOOK as "AUTHORS RECORD"
from AUTHORS;
• Output:

Lesson Summary:
In this lesson, you should have learned how to use the
following statements:
• Use the * to call all rows and columns in the table.
• Display specific column by specifying the column lists in
the select list.
• Make use of arithmetic expression
• Rename a column heading
• Make use of concatenation operator as well as character
literal string.

Terms to Remember!
• Arithmetic Expressions - Create expression with
number and date values.
• Column Alias - renames a column heading
• Concatenation Operator - Links columns or character

Database Management System 1 13


Week 3 Basic SELECT Statement

strings to other columns


• Joins: Brings together data that is stored in different
tables by specifying the link between them.
• Literal - is either a a character, a number, or a date that
is included in the SELECT statement.
• Null - is a value that is unavailable, unassigned,
unknown, or inapplicable.
• Parentheses ( ) - are used to override the default
precedence or to clarify the statement.
• Projection: Selects the columns in a table that are
returned by a query.
• Selection: Selects the rows in a table that are returned by
a query.

Textbook:
References • Oracle Press (2010). Applied Oracle Security

References:
• Pratt, Philip J. (2010). Database management systems
• Rob, Peter & Coronel, Carlo (2009). Database
Management Systems
• Schwalbe, Kathy (2011). Management of Information
Technology Projects
• Wheeler, Evan (2011). Security Risk Management :
Building an Information Security Risk Management
Program from the Ground Up

Supplementary Reading and Video Link


Supplementary Reading
https://dev.mysql.com/doc/refman/5.6/en/select.html
https://docs.oracle.com/cd/B28359_01/server.111/b28286/state
ments_10002.htm#SQLRF01702

_____________________________________________________________________________________
14
MODULE OF INSTRUCTION
https://www.techonthenet.com/oracle/select.php

Supplementary Video
https://www.youtube.com/watch?v=otI5dbmEU7c
https://www.youtube.com/watch?v=SoxHivg9Ldw
https://www.youtube.com/watch?v=WB0zBS1wre4

Suggested Reading
• SQL Tutorial. In ws3schools, Retrieved from
http://www.w3schools.com/sql/default.asp
• Database management system. In Encyclopedia
Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/152201/dat
abase-management-system-DBMS.
• SQL. In Encyclopedia Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/569684/SQ
L
• Database Administration. In Encyclopedia.com,
Retrieved from
http://www.encyclopedia.com/topic/Database_administra
tion.aspx
• SQL. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/SQL.aspx
• Tutorialspoint.com
• oracle.com
• apex.oracle.com

Database Management System 1 15


MODULE OF INSTRUCTION

Restrict the rows returned


using the WHERE Condition
Welcome to the 6th module of this course Database
Management System 1! For this lesson, it covers the
different conditions that you can apply in order to limit the
rows returned by the query. Sample and demonstration in this
lesson uses the AUTHORS table as shown below:
Table 1.0 Authors

SELECT statement is use to create different types of reports


where user can apply the basic select, restrict the rows
returned by the query, use single row or multiple row
function and sort the data either ascending or descending.

Database Management System 1 1


Week 3 WHERE Condition

WHERE Clause You can restrict the rows that are returned from the query by
using the WHERE clause. A WHERE clause contains a
condition that must be met and it directly follows the FROM
clause. If the condition is true, the row meeting the condition
is returned.

After completing this lesson, the student should be able


to:
• Use Where clause to limit the rows that are retrieved by a
query
• Sort the rows that are retrieved by a query using
ascending or descending order.

Where Clause
• Restrict the rows that are returned by using the WHERE
clause:
• Syntax:
SELECT (COLUMN_LIST [EXPRESSION])
FROM TBLE_NAME
WHERE CONDITION;
• Where:
o A SELECT clause, which specifies the columns
to be displayed
o A FROM clause, which identifies the table
containing the columns that are listed in the
SELECT clause
o A WHERE is used to identify what specific
condition you would like to add in the select
statement to restrict the rows returned by a query.
• You can use WHERE clause to compare values in
columns, add literal character string in between two or

_____________________________________________________________________________________
2
MODULE OF INSTRUCTION
more column, apply arithmetic expressions, or functions.
It consists of three elements:
• Column name
• Comparison condition
• Column name, constant, or list of values
• Example:
SELECT ID, LNAME, FNAME, BOOK, TYPE
FROM AUTHORS
WHERE TYPE = 'CSIT';
• Output:

• Explanation:
As shown in the example from the original 8 rows the
report now only shows all authors in which the type of
the book is equal to CSIT.

Character Strings and Dates


• When and where clause contain Character strings and
date values always enclosed the values in single
quotation marks.
• Note that Character values are case-sensitive and date
values are format-sensitive.
• Example/Output:

Database Management System 1 3


Week 3 WHERE Condition

• Explanation:
No rows are select because of the condition
TYPE=’GenEd’, since this type is in capital letter during
the time that the user inserted the values. This only
means that we have to follow the character type of the
values whether in capital, small or initcap.

Comparison Condition:
 Comparison operators are used in conditions that
compare one expression with another value or
expression.
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> or != Not equal to
IN (SET) Match any of the values
inside the (SET)
BETWEEN..AND Between two inclusive
values
LIKE Match a character pattern
IS NULL Is a NULL value

Using Comparison Operator

_____________________________________________________________________________________
4
MODULE OF INSTRUCTION
 Example:
SELECT LNAME, FNAME, BOOK, YR_PUB
FROM AUTHORS
WHERE YR_PUB < 1995;
 Output:

 Explanation:
Record shown that there is only one author who meets
the condition of YR_PUB less than to 1995.
 Example:
SELECT LNAME, FNAME, BOOK, YR_PUB
FROM AUTHORS
WHERE YR_PUB <= 1995;
 Output:

 Explanation:
Record shown that there is two authors who meets the
condition of YR_PUB either less than or equal to 1995.

Range Conditions Using the BETWEEN Operator


 To display rows based on a range of values use the
BETWEEN operator. The range should have a lower
limit and an upper limit.
 Use the BETWEEN operator to display rows based on a
range of values
 Example:
SELECT ID, FNAME, LNAME, BOOK, TYPE, AC_NO, YR_PUB

Database Management System 1 5


Week 3 WHERE Condition

FROM AUTHORS
WHERE ID BETWEEN 10 AND 15;
 Output:

 Explanation:
Record shows the lists of authors whose ID is in between
the lowest range and highest range of 10 to 15. So
basically this is from 10, 11,12,13,14 and 15 any number
equal to these ranges will be included in the output.

Membership Condition Using the IN Operator


 Use the IN operator to test for values in a list:
 To test for values in a specified set of values, use the IN
operator. The condition defined using the IN operator is
also known as the membership condition.
 Example:
SELECT ID, FNAME, LNAME, BOOK, TYPE, AC_NO, YR_PUB

FROM AUTHORS
WHERE TYPE IN ('BA','GENED');
 Output:

 Explanation:

_____________________________________________________________________________________
6
MODULE OF INSTRUCTION
Record shows the lists of authors whose type is equal to
the values called in the set either the type is (BA or
GENED).

Pattern Matching Using the LIKE Operator


• To perform wildcard searches of valid search string
values use the LIKE operator.
• Search conditions can contain either literal characters or
numbers:
• % denotes zero or many characters.
• _ denotes one character.
• You may not always know the exact value to search for.
You can select rows that match a character pattern by
using the LIKE operator. The character pattern–matching
operation is referred to as a wildcard search. Two
symbols can be used to construct the search string.
• Example: Getting the first letter
SELECT ID, FNAME, LNAME, BOOK, TYPE, AC_NO, YR_PUB

FROM AUTHORS
WHERE FNAME LIKE 'M%';
• Output:

• Explanation:
Record shows the lists of authors whose first name starts
with capital letter M.
• Example: Getting the second letter
SELECT ID, FNAME, LNAME, BOOK, TYPE, AC_NO, YR_PUB

FROM AUTHORS
WHERE LNAME LIKE '%O';

Database Management System 1 7


Week 3 WHERE Condition

• Output:

• Explanation:
Record shows the lists of authors whose last name ends
with capital letter O.

Escape Identifier
The percentage % and underscore _ symbols can be used in
any combination with literal characters. When you need to
have an exact match for the actual percentage % and
underscore _ characters, use the ESCAPE identifier. This
option specifies what the escape character is.
• Example: Skipping the first letter
SELECT ID, FNAME, LNAME, BOOK, TYPE, AC_NO, YR_PUB

FROM AUTHORS
WHERE FNAME LIKE '_E%';
• Output:

• Explanation:
Record shows the lists of authors whose first name
second letter is equal to capital letter E regardless of its
starting character because of _ (underscore) it skips the
first letter.
• Example: Getting string/number or character in

_____________________________________________________________________________________
8
MODULE OF INSTRUCTION
between %%.
SELECT ID, FNAME, LNAME, BOOK, TYPE, AC_NO, YR_PUB

FROM AUTHORS
WHERE LNAME LIKE '%CA%';
• Output:

• Explanation:
Record shows the lists of authors whose last name have
the string equal to CA whether on the first, in between
and or last.

Using the NULL Conditions


• Test for nulls with the IS NULL operator.
• The NULL conditions include the IS NULL condition
and the IS NOT NULL condition.
• The IS NULL condition tests for nulls. A null value
means that the value is unavailable, unassigned,
unknown, or inapplicable. Therefore, you cannot test
with =, because a null cannot be equal or unequal to any
value.
• Example:
SELECT ID, FNAME, LNAME, BOOK, TYPE, AC_NO, YR_PUB

FROM AUTHORS
WHERE FNAME IS NULL;
• Output:

• Explanation:

Database Management System 1 9


Week 3 WHERE Condition

Record shows the lists of authors whose first name is


null.

Using the ORDER BY Clause


• Sort the retrieved rows with the ORDER BY clause:
• ASC: Ascending order, default
• DESC: Descending order
• The ORDER BY clause comes last in the SELECT
statement:
• In the syntax:
• ORDER BY - specifies the order in which the
retrieved rows are displayed
• ASC - orders the rows in ascending order (This is
the default order.)
• DESC - orders the rows in descending order.
• Example:
SELECT LNAME, BOOK, TYPE
FROM AUTHORS
WHERE TYPE = 'CSIT'
ORDER BY LNAME DESC;
 Output:

 Explanation:
 The lastname are sorted in Descending order starting
from z-a.
 Example:
SELECT LNAME, BOOK, TYPE

_____________________________________________________________________________________
10
MODULE OF INSTRUCTION
FROM AUTHORS
WHERE TYPE = 'CSIT'
ORDER BY LNAME ASC;
 Example: default
SELECT LNAME, BOOK, TYPE
FROM AUTHORS
WHERE TYPE = 'CSIT'
ORDER BY LNAME;
 OUTPUT:

 In the given example both of them will be having the


same output as shown above.

Lesson Summary:
In this lesson, you should have learned how to use the
following statements:
• Where condition that applies comparison condition
• Where condition that applies other comparison operator.

Terms to Remember!
• BETWEEN operators – is used to display rows based on
a range of values.
• Comparison operators - are used in conditions that
compare one expression with another value or
expression.
• IN operator - is used to test for values in a list.
• LIKE operator – use to perform wildcard searches of
valid search string values.
• Null value - means that the value is unavailable,
unassigned, unknown, or inapplicable.

Database Management System 1 11


Week 3 WHERE Condition

• Where Clause - restrict the rows that are returned from


References the query

Textbook:
• Oracle Press (2010). Applied Oracle Security

References:
• Pratt, Philip J. (2010). Database management systems
• Rob, Peter & Coronel, Carlo (2009). Database
Management Systems
• Schwalbe, Kathy (2011). Management of Information
Technology Projects
• Wheeler, Evan (2011). Security Risk Management :
Building an Information Security Risk Management
Program from the Ground Up

Supplementary Reading and Video


Supplementary Reading
https://www.techonthenet.com/oracle/where.php
https://www.w3schools.com/sql/sql_where.asp
https://www.tutorialspoint.com/sql/sql-where-clause.htm

Supplementary Video
https://www.youtube.com/watch?v=BYl7bz234Ew
https://www.youtube.com/watch?v=rkFnksNgQTk
https://www.youtube.com/watch?v=vxlD94G0Geo

Suggested Reading
• SQL Tutorial. In ws3schools, Retrieved from
http://www.w3schools.com/sql/default.asp
• Database management system. In Encyclopedia
Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/152201/data
base-management-system-DBMS.

_____________________________________________________________________________________
12
MODULE OF INSTRUCTION
• SQL. In Encyclopedia Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/569684/SQ
L
• Database Administration. In Encyclopedia.com,
Retrieved from
http://www.encyclopedia.com/topic/Database_administra
tion.aspx
• SQL. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/SQL.aspx
• Tutorialspoint.com
• oracle.com
• apex.oracle.com

Database Management System 1 13


MODULE OF INSTRUCTION

Defining Condition using Logical


Operators
Welcome to the 7th module of this course Database Management System
1! For this lesson, it covers the where condition with the additional
restriction which applies the logical condition AND, OR and NOT.
Sample and demonstration in this lesson uses the AUTHORS table as
shown below:
Table 1.0 Authors

The select statement is used to create different types of reports where the
Logical
user can apply the basic select, restrict the rows returned by the query,
Condition
use single row or multiple row functions and sort the data either
ascending or descending.

To combine the result of two statements or also known as the component


you may use logical conditions to produce a single result based on those
conditions or it inverts the result of a single condition. A row is returned

Database Management System 1 1


Week 3 Logical Condition

only if the overall result if the condition is true.

After completing this lesson, the student should be able to:


 Define the rows returned using the three logical condition AND, OR
and NOT.
 Identify the result when the order of precedence is applied in
WHERE clause.

Three types of Logical Condition


Operator Description
AND Returns TRUE if both component conditions are
true

OR Returns TRUE if either component condition is true

NOT Returns TRUE if the condition is false

Using the AND Operator


 Both the component conditions must be true for any record to be
selected.
 Example:
SELECT ID, FNAME, LNAME, BOOK, TYPE
FROM AUTHORS
WHERE TYPE='CSIT'
AND BOOK LIKE '%A';
 Output:

 Explanation:

_____________________________________________________________________________________
2
MODULE OF INSTRUCTION
As shown in the output only those authors who have a type of CSIT
and book that contains the last letter equal to A are selected.

Using the OR Operator


 Either component condition can be true for any record to be selected.
 Example:
SELECT ID, FNAME, LNAME, BOOK, TYPE
FROM AUTHORS
WHERE BOOK='CSIT'
OR BOOK LIKE '%A';
 Output:

 Explanation:
As shown in the output only those authors who have a type of CSIT
or either a book that contains the last letter equal to A are selected.

Using the NOT Operator


 Reverse the value from TRUE to FALSE or FALSE to TRUE.
 The NOT operator can also be used with other SQL operators, such as
BETWEEN, LIKE, and NULL.
 Example:
SELECT ID, FNAME, LNAME, TYPE,YR_PUB
FROM AUTHORS
WHERE YR_PUB NOT IN(2010, 1995);
 Output:

Database Management System 1 3


Week 3 Logical Condition

 Explanation:
As shown in the output only those authors who have a YR_PUB not
equal to the value inside the IN (SET) are selected.

Rules of Precedence
 The rules of precedence determine the order in which expressions are
evaluated and calculated.
 The table in the slide lists the default order of precedence.
To override the default order of expression to be calculated first put
parentheses around the expression.
Operator Meaning
1 Arithmetic operators
2 Concatenation operator
3 Comparison conditions
4 IS [NOT] NULL, LIKE, [NOT] IN
5 [NOT] BETWEEN
6 Not equal to
7 NOT logical condition
8 AND logical condition
9 OR logical condition

 Example:
SELECT (FNAME||','||LNAME)AS NAME, BOOK,

_____________________________________________________________________________________
4
MODULE OF INSTRUCTION
TYPE,AC_NO
FROM AUTHORS
WHERE TYPE='CSIT'
OR AC_NO LIKE'%S'
AND LNAME LIKE 'S%';
 Output:

 Explanation:
In this example, there are two conditions:
 The first condition is that the AC_NO end with capital letter S and
the LNAM start with capital letter S.
 The second condition is that the TYPE is CSIT.
 Therefore, the SELECT statement reads as follows:
“Select the row if an author AC_NO ends with letter S and the
LNAME starts with letter S or the TYPE is equal to CSIT.
 Example: with parentheses
SELECT (FNAME||','||LNAME)AS NAME, BOOK,
TYPE,AC_NO
FROM AUTHORS
WHERE (TYPE='CSIT'
OR AC_NO LIKE'%S')
AND LNAME LIKE 'S%';

 Output:

Database Management System 1 5


Week 3 Logical Condition

 Explanation:
 In this example, there are two conditions:
 The first condition is that the AC_NO ends with letter S or the TYPE
are equal to CSIT
 The second condition is that the LNAME ends with letter S.
 “Select the row if an author AC_NO ends with letter S and the
LNAME starts with letter S and the TYPE is equal to CSIT.

Lesson Summary:
In this lesson, you should have learned how to use the following
statements:
 Apply the logical condition.
 Identify the order of precedence.

Terms to Remember!
 AND - Both component condition can be true for any record to be
selected.
 Logical condition - combines the result of two component conditions
to produce a single result based on those conditions or it inverts the
result of a single condition
 NOT - Reverse the value from TRUE to FALSE or FALSE to TRUE.
 OR - Either component condition can be true for any record to be
selected.
 Rules of precedence - determine the order in which expressions are
evaluated and calculated.

Textbook:
 Oracle Press (2010). Applied Oracle Security

_____________________________________________________________________________________
6
MODULE OF INSTRUCTION
References:

References  Pratt, Philip J. (2010). Database management systems


 Rob, Peter & Coronel, Carlo (2009). Database Management Systems
 Schwalbe, Kathy (2011). Management of Information Technology
Projects
 Wheeler, Evan (2011). Security Risk Management : Building an
Information Security Risk Management Program from the Ground Up

Supplementary Reading and Video Link


Supplementary Reading
https://www.tutorialspoint.com/sql/sql-and-or-clauses.htm
https://docs.oracle.com/cd/B19306_01/server.102/b14200/conditions004.htm
https://docs.microsoft.com/en-us/sql/t-sql/language-elements/logical-
operators-transact-sql

Supplementary Video
https://www.youtube.com/watch?v=JRmpM9UNY-w
https://www.youtube.com/watch?v=OjJUPYS6o1E
https://www.youtube.com/watch?v=eXGOYouMkJA

Suggested Reading
 SQL Tutorial. In ws3schools, Retrieved from
http://www.w3schools.com/sql/default.asp
 Database management system. In Encyclopedia Britannica, Retrieved
from http://www.britannica.com/EBchecked/topic/152201/database-
management-system-DBMS.
 SQL. In Encyclopedia Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/569684/SQL
 Database Administration. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/Database_administration.aspx
 SQL. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/SQL.aspx
 Tutorialspoint.com
 oracle.com

Database Management System 1 7


Week 3 Logical Condition

 apex.oracle.com

_____________________________________________________________________________________
8
MODULE OF INSTRUCTION

Formatting Case, Character and


Number using Single-row Function
Welcome to the 8th module of this course Database Management
System 1! For this lesson, it covers the different conditions that you
can apply in order to change and get the character or case value in the
table. Sample and demonstration in this lesson uses the AUTHORS
table as shown below:
Table 1.0 Authors

Functions make the basic query block more powerful, and they are
Single-Row
used to manipulate data values.
Function
After completing this lesson, the student should be able to:
• Describe the various types of functions available in SQL
• Use the character, number, and date functions in SELECT
statements

Database Management System 1 1


Week 3 Single Row Function

Functions are a very powerful feature of SQL. They can be used to do


the following:
• Perform calculations on data
• Modify individual data items
• Manipulate output for groups of rows
• Format dates and numbers for display
• Convert column data types

There are two types of functions:


1. Single-row functions - returns one result per row.
These functions operate on single rows only and return one result
per row. There are different types of single-row functions. This
lesson covers the following functions:
• Character
• Number
2. Multiple-row functions – returns one result per group of row.
Functions can manipulate groups of rows to give one result per
group of rows. These functions are also known as group functions.
This will be discuss in Week 11 lesson.

Single-row functions:
• Use to manipulate data items
• Can accept arguments that may return one value
• Act on each row that is returned
• Can return one result per row
• Can be used to modify the data type
• Arguments can be nested
• Can accept arguments that can be a column or an expression
• Syntax:
SELECT Function_name (arguments1,2 [expression])
FROM tbl_name;

_____________________________________________________________________________________
2
MODULE OF INSTRUCTION

 Where:
function_name - Is the name of the function
arg1, arg2 - Is any argument to be used by the function. This
can be represented by a column name or expression.
From tbl_name – is the name of the table

Two types of Single row function


1. Character functions: is a type of single row function that may
accept character input and can return both character and number
values
Character functions can be divided into the following:
1. Case-conversion functions
2. Character-manipulation functions
2. Number functions: a type of single row function that may accept
numeric input and return numeric values
Number functions can be divided into the following:
1. ROUND
2. TRUNC
3. MOD

Case Conversion function:


Function Result
LOWER(‘Database database management system
Management System’)
UPPER(‘Database Management DATABASE
System’) MANAGEMENT SYSTEM
INITCAP(‘Database Database Management System
Management System’)

Database Management System 1 3


Week 3 Single Row Function

Where:
• LOWER: Converts mixed-case or uppercase character strings to
lowercase
• UPPER: Converts mixed-case or lowercase character strings to
uppercase
• INITCAP: Converts the first letter of each word to uppercase and
the remaining letters to lowercase

Using Case-Conversion function: UPPER


 Example: UPPER
SELECT UPPER(LNAME||','||FNAME) AS "NAME"
FROM AUTHORS
WHERE LNAME LIKE'S%';
 Output:

 Explanation:
It retrieves the record of all authors whose LNAME starts with
capital S then converts the concatenated LNAME and FNAME to
upper case.
 Note that since during the insertion of values into authors table all
value is inserted in capital form the reason why no changes in the
conversion as shown in the output.

_____________________________________________________________________________________
4
MODULE OF INSTRUCTION
Using Case-Conversion function: lower
 Example: lower
SELECT LOWER(LNAME||','||FNAME) AS "NAME"
FROM AUTHORS
WHERE LNAME LIKE'S%';
 Output:

 Explanation:
It retrieves the record of all authors whose LNAME starts with
capital S then converts the concatenated LNAME and FNAME to
lowercase.

Using Case-Conversion function: InitCap


 Example: lower
SELECT INITCAP(LNAME||','||FNAME) AS "NAME"
FROM AUTHORS
WHERE LNAME LIKE'S%';
 Output:

 Explanation:
It retrieves the record of all authors whose LNAME starts with
capital S then converts the concatenated LNAME and FNAME to
sentence case like. Where the first letter is capitalized and every
time an SQL encounter special character and or space is
automatically capitalized the first letter of the following string and

Database Management System 1 5


Week 3 Single Row Function

or character.

Character Manipulation Function


Function Result
CONCAT(‘Data’,’Base’) DataBase
SUBSTR(Database System, 1, 8) Database
LENGTH(‘Database’) 8
INSTR(Database,’b’) 5
LPAD(price,6,’$’) $$$360
RPAD(proce,6,’$’) 360$$$
REPLACE(Database, ‘a’,’c’) Dctcbce
TRIM(‘D’ from ‘Database’) atabase
Where:
• CONCAT: Joins values together (You are limited to using two
parameters with CONCAT.) instead used || (double bars) if it
contains two or more columns and character literal string
• SUBSTR: Extracts a string of determined length
• LENGTH: Shows the length of a string as a numeric value
• INSTR: Finds the numeric position of a named character
• LPAD: Returns an expression left-padded to the length of n
characters with a character expression
• RPAD: Returns an expression right-padded to the length of n
characters with a character expression
• TRIM: is sued to trim the leading or trailing characters (or both)
from a character string (If trim_character or trim_source is a
character literal, you must enclose it in single quotation marks.)

_____________________________________________________________________________________
6
MODULE OF INSTRUCTION
Using Character Manipulation Function: Concat
 Example: CONCAT
SELECT CONCAT(LNAME,FNAME), YR_PUB
FROM AUTHORS
WHERE YR_PUB = 2010;
 Output:

 Explanation:
It retrieves the record of all authors whose YR_PUB is equal to
2010, then concatenates the LNAME to FNAME.

Character Manipulation Function: SUBSTR


 Example: SUBSTR
SELECT LNAME, FNAME, BOOK
FROM AUTHORS
WHERE SUBSTR(BOOK,6)='ING';
 Output:

 Explanation:
It retrieves the record of all authors whose BOOK counting from
1-6 is equal to ING.

Database Management System 1 7


Week 3 Single Row Function

Character Manipulation Function: INSTR and LENGTH


 Example: LENGTH, INSTR
SELECT BOOK,LENGTH(BOOK), INSTR(BOOK,'A')
FROM AUTHORS
WHERE BOOK LIKE 'A%';
 Output:

 Explanation:
It retrieves the record of all authors whose BOOK name starts with
the capital letter A then gets the length of the book as well as the
character position of A in the book column. Notice that the Oracle
only returns the character position of the first A it encounters
starting from the first letter up to the last. Like for example the
work DATABASE is composed of 3 A’s but since it only reads the
first letter A its INSTR value is 2 (second letter equal to A)

Character Manipulation Function: LPAD and RPAD


 Example: RPAD, LPAD
SELECT BOOK, LPAD(YR_PUB,7,'$'),
RPAD(YR_PUB,7,'@')
FROM AUTHORS
WHERE BOOK LIKE '%ING%';
 Output:

 Explanation:

_____________________________________________________________________________________
8
MODULE OF INSTRUCTION
It retrieves the record of all authors whose BOOK has an ING
string then pads the YR_PUB to the left and replace the other
numbers with $ dollar sign symbol to make the digits size 6, as
well as pads the YR_PUB to the right and replace the other
numbers with $ dollar sign symbol to make the digits size 6.

Character Manipulation Function: Replace


 Example: REPLACE
SELECT REPLACE(FNAME,'A','T')
FROM AUTHORS;
 Output:

 Explanation:
It retrieves the record of all authors FNAME then replaced the
letter A with T in the column FNAME.

Character Manipulation Function: Trim


 Example: TRIM
SELECT BOOK, TRIM('A' FROM BOOK)
FROM AUTHORS;
 Output:

Database Management System 1 9


Week 3 Single Row Function

 Explanation:
It retrieves the record of all authors BOOK then trim the letter A
from BOOK Column.

Number Function
Function Result
ROUND(75. 46,1) 75.5
TRUNC(75.46,1) 75
MOD(100/3) 10
Where:
• ROUND: a type of number function that is used to rounds value to
a specified decimal
• TRUNC: a type of number function that is used to truncates value
to a specified decimal
• MOD: a type of number function that is used to returns remainder
of division

DUAL Table
The DUAL table is owned by the user SYS and can be accessed by all
users. It contains one column, DUMMY, and one row with the value
X. The DUAL table is useful when you want to return a value only
once (for example, the value of a constant, pseudo column, or

_____________________________________________________________________________________
10
MODULE OF INSTRUCTION
expression that is not derived from a table with user data). The DUAL
table is generally used for completeness of the SELECT clause syntax
because both SELECT and FROM clauses are mandatory, and several
calculations do not need to select from the actual tables.

Using Number Function: ROUND


 Example: ROUND
SELECT ROUND(75.475,2),ROUND(75.475,1),
ROUND(75.475,-1)
FROM DUAL;

 Output:

 Explanation:
ROUND(75.475,2) – Round the number starting from decimal
point count to 2 = 75.47 and since the following number of 7 is 5 it
round off to 8 the which results to 75.48
ROUND(75.475,1) – Round the number starting form decimal
point count to 1 = 75.4 and since the following number of 4 is 7 it
round off to 5 the which results to 75.5
ROUND(75.475,-1) – Round the number starting form decimal
point count to 1 to the left(because of – negative sign) = 75 and
since the following number of 7 is 5 it rounds off to 8 and makes
the value of 5 to 0 which results to 80.

Database Management System 1 11


Week 3 Single Row Function

Using Number Function: TRUNC


 Example: TRUNC
SELECT
TRUNC(75.475,2),TRUNC(75.475,1),TRUNC(75.475,-1)
FROM DUAL;
 Output:

Explanation:
TRUNC(75.475,2) – Truncate/cut the number starting from
decimal point 2 which result to 75.47
TRUNC(75.475,1) – Truncate/cut the number starting from
decimal point 1 which result to 75.4
TRUNC(75.475,-1) – Truncate/cut the number starting from the
decimal point -1(starting to the left) which result to 75 and since
we have to cut the digit at position -1 make this digit 0 which
result to 70.

Using Number Function: MOD


 Example: MOD
SELECT MOD(1000,300)
FROM DUAL;
 Output:

 Explanation:
It gets the remainder of 1000 over 300 which is equal to 100.

_____________________________________________________________________________________
12
MODULE OF INSTRUCTION
Lesson Summary:
In this lesson, you should have learned how to:
• Perform calculations on data using functions
• Modify case and character values.

Terms to Remember!
• Character functions: Accept character input and can return both
character and number values
• CONCAT: Joins values together (You are limited to using two
parameters with CONCAT.) instead used || (double bars) if it
contains two or more columns and character literal string
• DUAL - the table that is owned by the user SYS and can be
accessed by all users.
• INITCAP: Converts the first letter of each word to uppercase and
the remaining letters to lowercase
• INSTR: Finds the numeric position of a named character
• LENGTH: Shows the length of a string as a numeric value
• LOWER: Converts mixed-case or uppercase character strings to
lowercase
• LPAD: Returns an expression left-padded to the length of n
characters with a character expression
• Multiple-row functions – returns one result per group of row.
• MOD: Returns remainder of division
• Number functions: Accept numeric input and return numeric
values
• ROUND: Rounds value to a specified decimal
• RPAD: Returns an expression right-padded to the length of n
characters with a character expression
• Single-row functions - returns one result per row.
• SUBSTR: Extracts a string of determined length
• TRIM: Trims leading or trailing characters (or both) from a

Database Management System 1 13


Week 3 Single Row Function

character string (If trim_character or trim_source is a character


literal, you must enclose it within single quotation marks.)
• TRUNC: Truncates value to a specified decimal
• UPPER: Converts mixed-case or lowercase character strings to
uppercase

References Textbook:
• Oracle Press (2010). Applied Oracle Security

References:
• Pratt, Philip J. (2010). Database management systems
• Rob, Peter & Coronel, Carlo (2009). Database Management
Systems
• Schwalbe, Kathy (2011). Management of Information Technology
Projects
• Wheeler, Evan (2011). Security Risk Management : Building an
Information Security Risk Management Program from the Ground
Up

Supplementary Reading and Video


Supplementary Reading
https://docs.oracle.com/database/121/SQLRF/functions002.htm#SQLRF511
78
https://www.tutorialspoint.com/sql_certificate/using_single_row_functions
.htm
http://database-query.blogspot.com/2007/10/basic-select-
statement_18.html

Supplementary Video
https://www.youtube.com/watch?v=5rx8Q4x4-qI
https://www.youtube.com/watch?v=WQe-p2F3Kcg
https://www.youtube.com/watch?v=yjXXntX0sh8

Suggested Reading
• SQL Tutorial. In ws3schools, Retrieved from

_____________________________________________________________________________________
14
MODULE OF INSTRUCTION
http://www.w3schools.com/sql/default.asp
• Database management system. In Encyclopedia Britannica,
Retrieved from
http://www.britannica.com/EBchecked/topic/152201/database-
management-system-DBMS.
• SQL. In Encyclopedia Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/569684/SQL
• Database Administration. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/Database_administration.aspx
• SQL. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/SQL.aspx
• Tutorialspoint.com
• oracle.com
• apex.oracle.com

Database Management System 1 15


MODULE OF INSTRUCTION

Grouping Aggregated data using


Group Function
Welcome to the 9th module of this course Database Management System 1!
For this lesson, it covers the different type of group function, group the data
using GROUP BY clause and exclude output using HAVING clause.
Sample and demonstration in this lesson uses the AUTHORS table as shown
below:
Table 1.0 Authors

Group Function helps how to group rows in a table into smaller sets and how
Multiple-
to specify search criteria for groups of rows.
Row
Function After completing this lesson, the student should be able to:
1. Identify the available group functions
2. Describe the use of group functions
3. Group data by using the GROUP BY clause
4. Use the HAVING clause to include or exclude group function.

Database Management System 1 1


Week 3 Multiple Row Function

Group Function
 Group functions are used to operate on sets of rows in order to give one
result per group. These sets may comprise either the entire table or a
table may be split into groups.

Types of Group Function


Function Description
AVG Average value of N ignoring null values

COUNT Count the number of rows where expr evaluates to


something other than null
Count all selected rows using *, including duplicates and
rows with null
MAX Maximum value of expression ignoring null values
MIN Minimum value of expression ignoring null values
STDEV Standard deviation of N ignoring null values
SUM Sum values of N ignoring null values
VARIANCE Variance of N ignoring null values

Group Function Syntax:


SELECT group_function(Column_lists),…
FROM table_name
[WHERE condition];
Where
 SELECT Group_function – is the name of the group function ex. MIN
 FROM table_name – is the name of the table
 WHERE condition – is optional

_____________________________________________________________________________________
2
MODULE OF INSTRUCTION

Using the AVG and SUM function


 Can be used only with numeric data types
 Example:
SELECT AVG(YR_PUB), SUM(YR_PUB)
FROM AUTHORS;
 Output:

 Explanation:
The sample output displays the average and sum YR_PUB of all authors.

Using the MIN and MAX function


 You can use the MAX and MIN functions for numeric, character, and
date data types.
 Example:
SELECT MIN(LNAME), MAX(LNAME)
FROM AUTHORS;
 Output:

 Explanation:
The sample output displays the authors LNAME and FNAME that is
first in the alphabet lists for MIN function and last in the alphabet lists
for MAX function.

Database Management System 1 3


Week 3 Multiple Row Function

Using the STDDEV and VARIANCE function


 Can be used only with numeric data types
 Example:
SELECT STDDEV(ID), VARIANCE(ID)
FROM AUTHORS;
 Output:

 Explanation:
 The sample output displays the author’s standard deviation for STDDEV
function and variance for VARIANCE function applied in ID column.

Using the COUNT function


 The COUNT function has three formats:

1. COUNT(*) - COUNT(*) is use to return the number of rows in a


table that satisfy the criteria of the SELECT statement, including
duplicate rows and rows containing null values in any of the
columns. If a WHERE clause is included in the SELECT statement,
COUNT(*) returns the number of rows that satisfy the condition in
the WHERE clause.

2. COUNT(expr) - In contrast, COUNT(expr) returns the number of


non-null values that are in the column identified by expr.

3. COUNT(DISTINCT expr) – While COUNT(DISTINCT expr)


returns the number of unique, non-null values that are in the column
identified by expr.

_____________________________________________________________________________________
4
MODULE OF INSTRUCTION

 Example: Using Count(*)


SELECT COUNT(*)
FROM AUTHORS;
 Output:

 Explanation:
The sample output displays the total number of authors in the table.
 Example: Using Count(expr)
SELECT COUNT(TYPE)
FROM AUTHORS
WHERE TYPE='CSIT';
 Output:

 Explanation:
The sample output displays the total number of authors whose book
TYPE is CSIT.

 Example: Using Count(DISTINCT expr)


SELECT COUNT(distinct YR_PUB)
FROM AUTHORS;
 Output:

Database Management System 1 5


Week 3 Multiple Row Function

 Explanation:
The sample output displays the number of distinct value that are in
authors table using the YR_PUB column.

Using NVL Function to include NULL values.


 By default group function always ignores NULL values to include the
NULL values in counting of output you may use the NVL function.
 Example: default output
SELECT AVG(YR_PUB)
FROM AUTHORS;
 Output:

 Example: with NVL function


SELECT AVG(NVL(YR_PUB,0))
FROM AUTHORS;
 Output:

 Explanation:
 The output for default function displays the calculated average based
only on those rows with values in the table in which a valid value is
stored in the YR-PUB column. The average is calculated as the total
YR_PUB to all authors divided by the number of authors with valid
values in YR_PUB column which is equal to 7.

 The output for function with NVL displays the calculated average
regardless of whether null values are stored in the YR-PUB column. The
average is calculated as the total YR_PUB to all authors divided by the

_____________________________________________________________________________________
6
MODULE OF INSTRUCTION
number of authors with or without valid values in YR_PUB column
which is equal to 8 (including author with NULL YR_PUB).

Creating groups of data using GROUP BY clause.


 A group functions output came from the table with large group of
information. In order to divide the table of information into smaller
group a GROUP BY clause is being use.
 Syntax:
SELECT function_name(column), group_function(column)
FROM table_name
[WHERE condition]
[GROUP BY group_by_expr]
[ORDER BY column];
 Where:
group_by_expr - Specifies the columns whose values determine the
basis for grouping rows.

Guidelines in using a GROUP BY clause

• When a group function is included in a SELECT clause, you cannot


select individual column as well, unless the individual column appears in
the GROUP BY clause. You receive an error message if you fail to
include the column list in the GROUP BY clause.
• Using a WHERE clause, you can exclude rows before dividing them into
groups.
• You can substitute column by an Expression in the SELECT statement.
• You must include the columns in the GROUP BY clause.
• You cannot use a column alias in the GROUP BY clause

Database Management System 1 7


Week 3 Multiple Row Function

Using GROUP BY Clause


 If the Select statement contain a GROUP BY clause, make sure that all
columns in the SELECT list that are not group functions are called in the
GROUP BY clause.
 Example:
SELECT TYPE, COUNT(*)
FROM AUTHORS
GROUP BY TYPE;
 Output:

 Explanation:
The sample select the authors book TYPE and count the number of book
TYPE, the group by clause specifies that the values retrieved should be
group per book TYPE and count the type per group. This only means
that there are 4 types of CSIT, 2 for GENED and 2 for BA.
 Example: Violation

 Output:
In the example sing TYPE column has no function enforce while
COUNT(*) is a function this will cause an error, the reason why column
with no function should be called in GROUP BY Clause.

_____________________________________________________________________________________
8
MODULE OF INSTRUCTION
Grouping two (2) columns
 To see the results for groups within group use this example.
 Example:
SELECT TYPE, YR_PUB, SUM(YR_PUB), AVG(YR_PUB)
FROM AUTHORS
GROUP BY TYPE, YR_PUB;
 Output:

 Explanation:
The sample displays the authors book TYPE, YR_PUB and get the SUM
and AVG for YR_PUB column then group the data by TYPE and
YR_PUB, since the YR_PUB have more distinct values the select
statement then prioritize the columns with the most number of distinct
values.
 You can always use the WHERE condition to restrict the rows returned
by the query.
 Example: Group by with WHERE condition
SELECTTYPE, YR_PUB,
COUNT(DISTINCT(YR_PUB)),SUM(YR_PUB), AVG(YR_PUB)
FROM AUTHORS
WHERE YR_PUB > 1995
GROUP BY TYPE, YR_PUB;

Database Management System 1 9


Week 3 Multiple Row Function

 Output:

 Explanation:
The sample displays the authors book TYPE, YR_PUB and gets the
number of distinct values, SUM and AVG for YR_PUB column where
YR_PUB is greater than 1995, then group the data by TYPE and
YR_PUB.

Having Clause
• You cannot use the WHERE clause to restrict groups.
• You use the HAVING clause to restrict groups.
• You cannot use group functions in the WHERE clause.
• Syntax
SELECT function_name(column), group_function(column)
FROM table_name
[WHERE condition]
[GROUP BY group_by_expr]
[HAVING group Condition]
[ORDER BY column];
• Example: Illegal Queries

_____________________________________________________________________________________
10
MODULE OF INSTRUCTION
 Explanation:
Sample shows that a WHERE condition cannot have a group function in
it ex: WHERE MAX(ID)>15 to restrict the rows return pure column can
only be applied to WHERE condition. By the time that you wanted to
restricts the rows with group function.
 Example: with HAVING CLAUSE
SELECT YR_PUB,
COUNT(DISTINCT(YR_PUB)),SUM(YR_PUB), AVG(YR_PUB)
FROM AUTHORS
GROUP BY YR_PUB
HAVING MAX(ID)>15;
 Output:

 Explanation:
The sample displays the YR_PUB, the distinct values for YR_PUB,
SUM and AVG then group the data per YR_PUB and restricts the rows
retuned having maximum ID greater than 5;

Complete SELECT
 Example:
SELECT TYPE, MIN(FNAME),MAX(ID)
FROM AUTHORS
WHERE ID BETWEEN 10 AND 15
GROUP BY TYPE
HAVING MAX(ID)>= 5
ORDER BY MAX(ID) DESC;

Database Management System 1 11


Week 3 Multiple Row Function

 Output:

 Explanation:
The sample displays the authors book TYPE, number of distinct values
for YR_PUB, SUM and AVG for YR_PUB column whose ID is in
between the lowest and highest range of 10-15 then group the data per
YR_PUB having maximum ID which is greater than or equal to 15 and
sort the data by maximum ID in descending order.

Nesting Group Function


 Group functions can be nested to a depth of two functions.
 Example:
SELECT MAX(AVG(YR_PUB))
FROM AUTHORS
GROUP BY TYPE;
 Output:

 Explanation:
The sample output displays the maximum average YR_PUB of authors
per book TYPE.

_____________________________________________________________________________________
12
MODULE OF INSTRUCTION
Lesson Summary:
In this lesson, you should have learned how to:
• Use the group functions COUNT, MAX, MIN, SUM, and
AVG
• Include the NULL values using the NVL function
• Write queries that use the GROUP BY clause
• Write queries that use the HAVING clause
• Group date using 2 columns
• And apply Nested Groups

Terms to Remember!
 AVG - Average value of N ignoring null values
 COUNT - Count the number of rows where expr evaluates to something
other than null
 COUNT(DISTINCT expr) – While COUNT(DISTINCT expr) returns
the number of unique, non-null values that are in the column identified
by expr.
 COUNT(expr) - In contrast, COUNT(expr) returns the number of non-
null values that are in the column identified by expr.
 COUNT(*) - COUNT(*) returns the number of rows in a table that
satisfy the criteria of the SELECT statement, including duplicate rows
and rows containing null values in any of the columns.
 Group functions - operate on sets of rows to give one result per group.
 MAX - Maximum value of expression ignoring null values
 MIN - Minimum value of expression ignoring null values
 STDDEV - Standard deviation of N ignoring null values
 SUM - Sum values of N ignoring null values
 VARIANCE - Variance - of N ignoring null values

Database Management System 1 13


Week 3 Multiple Row Function

Textbook:
References  Oracle Press (2010). Applied Oracle Security

References:
 Pratt, Philip J. (2010). Database management systems
 Rob, Peter & Coronel, Carlo (2009). Database Management Systems
 Schwalbe, Kathy (2011). Management of Information Technology
Projects
 Wheeler, Evan (2011). Security Risk Management : Building an
Information Security Risk Management Program from the Ground Up

Supplementary Reading and Video Link


Supplementary Reading
https://www.tutorialspoint.com/sql_certificate/using_the_group_functions.htm
http://www.dba-oracle.com/t_garmany_7_stor_dba_sum.htm
https://docs.oracle.com/cd/B12037_01/server.101/b10759/functions001.htm

Supplementary Video
https://www.youtube.com/watch?v=5rx8Q4x4-qI&t=6s
https://www.youtube.com/watch?v=WQe-p2F3Kcg
https://www.youtube.com/watch?v=mFxejM58wyM

Suggested Reading
 SQL Tutorial. In ws3schools, Retrieved from
http://www.w3schools.com/sql/default.asp
 Database management system. In Encyclopedia Britannica, Retrieved
from http://www.britannica.com/EBchecked/topic/152201/database-
management-system-DBMS.
 SQL. In Encyclopedia Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/569684/SQL
 Database Administration. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/Database_administration.aspx
 SQL. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/SQL.aspx

_____________________________________________________________________________________
14
MODULE OF INSTRUCTION
 Tutorialspoint.com
 oracle.com
 apex.oracle.com

Database Management System 1 15


MODULE OF INSTRUCTION

Sets Operators
Welcome to the 10th and last module of this course Database
Management System 1! For this lesson, it covers the different type
of sets operators that is used to retrieve sets of data from 2 or more
table. Sample and demonstration in this lesson uses the AUTHORS
and BORROWER table as shown below:
Table 1.0 Authors

Database Management System 1 1


Week 3 Sets Operator

Sets All set operators either IN ANY or ALL have equal precedence.
When a SELECT statement have multiple set operators, the Oracle
server evaluates the operator from left / top to right / bottom – that is
if there is no parentheses. In order to change the order of evaluation
you may use a parentheses, this is added in the query in order to
specify the order of evaluation in the queries that use the
INTERSECT operator with other set operators.

After completing this lesson, the student should be able to:


1. Describe and define what sets operators are.
2. Make used of sets operator.
3. Apply different SELECT statement into sets.

Set Operators
 Set operators combine the results of two or more component
queries into one result. Queries containing set operators are
called compound queries.

Types of Set Operators


Function Description
Union Rows from both queries after eliminating
duplications
Union Rows from both queries including all duplications
ALL
Intersect Rows that are common to both queries
Minus Rows in the first query that are not present in the
second query

_____________________________________________________________________________________
2
MODULE OF INSTRUCTION
Set Operator Guidelines
• The expressions in the SELECT lists must match in number.
• The data type of each column in the second query must match
the data type of its corresponding column in the first query.
• Parentheses can be used to alter the sequence of execution.
• ORDER BY clause can appear only at the very end of the
statement.

Oracle Server and Set Operators


• The duplicated rows are automatically eliminated in the final
report except in UNION ALL.
• The column names selected from the first query appear in the
result.
• By default, the output is sorted in ascending order except in
UNION ALL.

Union Operator
The UNION operator returns all rows that are selected by either
query. Use the UNION operator to return all rows from multiple
tables and eliminate any duplicate rows.
Guidelines
• The number of columns being selected must be the same.
• The data types of the columns being selected must be in the
same data type group (such as numeric or character).
• The names of the columns need not be identical.
• UNION operates over all of the columns being selected.
• The NULL values or blank data in the report are not ignored
during duplicate checking.
By default, the output is sorted in ascending order of the columns of
the SELECT clause.

Database Management System 1 3


Week 3 Sets Operator

Authors Borrower

Example: Retrieve the record on both tables with the same values
after eliminating duplicated data.
SELECT BOOK, AC_NO
FROM AUTHORS
UNION
SELECT BOOK, AC_NO
FROM BORROWER;
Output:

Explanation:
 The UNION operator eliminates any duplicate records. If
records that occur in both the AUTHORS and the BORROWER
tables are identical, the records are displayed only once.
 The example retrieves only the record form AUTHORS and
BORROWER table with match values.

_____________________________________________________________________________________
4
MODULE OF INSTRUCTION
Union ALL

UNION ALL operator is use to return all rows from multiple queries
or multiple tables.

Guidelines
The guidelines for UNION and UNION ALL are the same, except
for the following: unlike UNION, in UNION ALL duplicated rows
are not eliminated in the report and the output is not sorted by
default.

Authors Borrower

Example:
SELECT BOOK, AC_NO
FROM AUTHORS
UNION ALL
SELECT BOOK, AC_NO
FROM BORROWER;

Database Management System 1 5


Week 3 Sets Operator

Output:

Explanation:
 The combination of the two tables totals to 30 rows. The
UNION ALL operator does not eliminate duplicate rows.
UNION returns all distinct rows selected by either query.
UNION ALL returns all rows selected by either query, including
all duplicates.
 The examples retrieves the record form AUTHORS table (equal
to 8 values), and retrieves all record from BORROWER table
(equal to 5 rows) which make the output 13 rows.

Intersect Operator:
Use the INTERSECT operator to return all rows that are common to
multiple queries.

_____________________________________________________________________________________
6
MODULE OF INSTRUCTION
Guidelines
• The number of columns and the data types of the columns
being selected by the SELECT statements in the queries
must be identical in all the SELECT statements used in the
query. The names of the columns, however, need not be
identical.
• Reversing the order of the intersected tables does not alter
the result.
• INTERSECT does not ignore NULL values.

Authors Borrower

Example:
SELECT BOOK, AC_NO
FROM AUTHORS
INTERSECT
SELECT BOOK, AC_NO
FROM BORROWER;
Output:

Explanation:
 In the example in this slide, the query returns only those records

Database Management System 1 7


Week 3 Sets Operator

that have the same values in the selected columns in both tables.

Minus Operator
Use the MINUS operator to return all distinct rows selected by the
first query, but not present in the second query result set (the first
SELECT statement MINUS the second SELECT statement).
Note: The number of columns must be the same and the data types
of the columns being selected by the SELECT statements in the
queries must belong to the same data type group in all the SELECT
statements used in the query. The names of the columns, however,
need not be identical.

Authors Borrower

Example:
SELECT BOOK, AC_NO
FROM AUTHORS
MINUS
SELECT BOOK, AC_NO
FROM BORROWER;

_____________________________________________________________________________________
8
MODULE OF INSTRUCTION
Output:

Explanation:
The output retrieves the record with identical values in AUTHORS
table but not present in the BORROWER table.

Lesson Summary:
In this lesson, you should have learned how to:
• Use the 4 types of SET operator
• Identify the difference between set operator
• Identify the guideline in using set operator.

Terms to Remember!
 Intersect - Rows that are common to both queries
 Minus - Rows in the first query that are not present in the
second query
 Union - Rows from both queries after eliminating duplications
 Union All - Rows from both queries including all duplications

Textbook:
References
 Oracle Press (2010). Applied Oracle Security

References:
 Pratt, Philip J. (2010). Database management systems
 Rob, Peter & Coronel, Carlo (2009). Database Management
Systems

Database Management System 1 9


Week 3 Sets Operator

 Schwalbe, Kathy (2011). Management of Information


Technology Projects
 Wheeler, Evan (2011). Security Risk Management : Building an
Information Security Risk Management Program from the
Ground Up

Supplementary Reading and Video Link


Supplementary Reading
https://oracle-base.com/articles/misc/all-any-some-comparison-
conditions-in-sql
https://www.w3schools.com/sql/sql_any_all.asp
https://docs.microsoft.com/en-us/sql/t-sql/language-elements/some-
any-transact-sql

Supplementary Video
https://www.youtube.com/watch?v=4bglO4qJZcc
https://www.youtube.com/watch?v=O1KVzYHCKDo
https://www.youtube.com/watch?v=HKZigj4c-DQ

Suggested Reading
 SQL Tutorial. In ws3schools, Retrieved from
http://www.w3schools.com/sql/default.asp
 Database management system. In Encyclopedia Britannica,
Retrieved from
http://www.britannica.com/EBchecked/topic/152201/database-
management-system-DBMS.
 SQL. In Encyclopedia Britannica, Retrieved from
http://www.britannica.com/EBchecked/topic/569684/SQL
 Database Administration. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/Database_administration.as
px
 SQL. In Encyclopedia.com, Retrieved from
http://www.encyclopedia.com/topic/SQL.aspx
 Tutorialspoint.com

_____________________________________________________________________________________
10
MODULE OF INSTRUCTION
 oracle.com
 apex.oracle.com

Database Management System 1 11


Database Management System 1

Introduction to Database System


Lesson Objective
After completing this lesson, the student should be able
to:
 Understand what is the difference between data,
information, database and database management system.
 Discuss the advantage and disadvantage of database
management system.
 Familiarize with the term ER-Model, Entities, Relationship
and Attribute.
Introduction to Database System: Terminologies

• Database-management system (DBMS) is a collection of


interrelated data and a set of different application programs use to
access those data. The primary role of a Database Management
System or also known as DBMS is to provide a way to store and
retrieve database information that is both convenient and efficient.

• Database – is the collection of data, contains information relevant


to an enterprise.

• Data – is also known facts that can be recorded and that have
implicit meaning.
Introduction to Database System: Terminologies

• Datum – a unit of data – is a symbol or a set of


symbols which is used to represent something.

• Information is interpreted data – data supplied


with semantics

• Database systems are designed to manage large


bodies of information.
Types of Handling Data

1. Data Processing

2. Data Management Systems

3. File Oriented Approach


Characteristics of Database
1. Concurrent Access
2. Structured and Described Data
3. Separation of Data and Applications
4. Data Integrity
5. Transactions
6. Data Persistence
Advantages of a DBMS

1. Data independence
2. Efficient data access
3. Data integrity and security
4. Data administration
5. Concurrent access and crash recovery
6. Reduced application development time
Disadvantages of a DBMS

1. Danger of a Overkill

2. Complexity

3. Qualified Personnel

4. Costs

5. Lower Efficiency
Instances, Physical and Logical Schemas

• Instance of the database – is the collection of information stored in the


database at a particular moment is called an.

• Database schema – is the overall design of the database is called the.

• Physical schema - describes the database design at the physical level

• Logical schema logically describes the database design at the logical level.

• Application programs are said to exhibit physical data independence if


they do not depend on the physical schema, and thus need not be
rewritten if the physical schema changes.
Data Models
• Entity-relationship (E-R) - is the data model that is
based on a perception of a real world.
• Entities - is consists of a collection of basic objects.
• Relationship - is an association among several entities.
The overall logical structure (schema) of a database can
be expressed graphically by an E-R diagram.
Lesson Summary:

In this lesson, you should have learned the


following.
 Database
 Database Management System
 ER Model
 Advantage and Disadvantage if database
Database Management System 1

Introduction to Oracle
Lesson Objective

After completing this lesson, the student should be


able to:
 Identify the focus area of Oracle 11g software.
 Discuss each feature of Oracle.
 Familiarize with the 4 types of Oracle statement to be
used for database management system 1 subject.
Focus areas of Oracle 11g

Infrastructure Grids
Information Management

Application Development
Features of Oracle Database 11g

Manageability

High availability
Performance
Security
Information integration
Object Relational Database Management System

• Relational model and object relational model

• User-defined data types and objects

• Fully compatible with relational database

• Supports multimedia and large objects

• High-quality database server features


Relational Database Concept
• Dr. E. F. Codd proposes the used and
implementation relational model for database
systems in 1970.

• In 1970 the relational model has been the


basis for the relational database management
system (RDBMS).
Relational Model
• The relational model consists of the following:

• Collection of objects or relations

• Set of operators to act on the relations

• Data integrity for accuracy and consistency

• A relational database is a collection of relations or


two-dimensional tables controlled by the Oracle server.
Relating Multiple Tables
• A primary key is used to uniquely identify each
row of data in a table.

• A user can logically relate or connect data


from multiple tables using foreign keys.
Using SQL to Query Your Database
• The Structured query language or SQL has been
standardized by the ANSI standard language for
operating relational databases

• Efficient, easy to learn, and use

• Functionally complete (With SQL, you can define,


retrieve, and manipulate data in the tables.)
SQL Statements Used in the Course
Data manipulation language (DML) Data definition language (DDL)

SELECT INSERT CREATE ALTER


UPDATE DELETE DROP RENAME

MERGE TRUNCATE COMMENT

Transaction control
Data control language (DCL
GRANT COMMIT
REVOKE SAVEPOINT
Lesson Summary:

In this lesson, you should have learned the


following.

• Focus area of Oracle;

• Features; and

• Different type of oracle statements


Database Management System 1

Installing Oracle Software


Lesson Objectives:
At the end of this lesson the student should be able
to:
• Describe the different role of database
administrator (DBA) and explain typical tasks and
tools needed before installing the oracle software.
• Know how to properly plan an Oracle software
installation.
• Install the Oracle database software.
Tasks of an Oracle Database
Administrator
The process for designing, implementing, and maintaining an Oracle
database involves and not limited to the following task as listed below:
1. Evaluating the database server hardware
2. Installing the Oracle software
3. Planning the database and security strategy
4. Creating, migrating, and opening the database
5. Backing up the database
6. Enrolling system users and planning for their Oracle Network access.
7. Implementing the database design
8. Recovering from database failure
9. Monitoring database performance
Tools for Administering
1. Oracle Universal Installer
2. Database Configuration Assistant
3. Database Upgrade Assistant
4. Oracle Net Manager
5. Oracle Net Configuration Assistant
6. Oracle Enterprise Manager
7. Server Control Utility
8. Recovery Manager
9. SQL*Loader
Planning Your Installation
Considerations:
• What Oracle software are you installing?
• Does the hardware involved meet the
minimum required specifications?
• Is there a recommended order of installation
when multiple products are involved?
• Are there prerequisite steps that must be
performed by someone other than the DBA?
Oracle Database Installation:
System Requirements
1. Memory requirements:
 1 GB for the database instance with Oracle Enterprise
 Manager Database Control
 1.5 GB for the ASM instance and Oracle Restart
2. Disk space requirements
 3 GB of swap space (based on 2 GB RAM)
 1 GB of disk space in the /tmp directory
 3.8 GB for the Oracle Database software
 4.5 GB for the Grid Infrastructure software
 1.7 GB for the preconfigured database (optional)
 3.4 GB for the fast recovery area (optional)
3. Operating system
Preparing the Operating System
Create the required operating system users and groups:
– Groups:
– oinstall
– dba
Optional groups (if doing separation of duty across multiple users):
– oper
– asmdba
– asmoper
– asmadmin
• Software owner, usually oracle
• Can create multiple users for multiple product installations
Setting Environment Variables
Oracle environment variables:
1. ORACLE_BASE: Base of the Oracle directory structure.
 Recommended to set this before installation.
2. ORACLE_HOME: The environment in which Oracle
products run. Not required before installation if
ORACLE_BASE is set.
3. ORACLE_SID: Not required before installation, but useful
afterwards for ease of interaction with a particular instance
4. NLS_LANG: Optional environment variable that controls
language, territory, and client character set settings
Checking the System

Requirements

• Adequate temporary space


• 64-bit versus 32-bit issues
• Correct operating system (OS)
• OS patch level
• System packages
• System and kernel parameters
• X Server permissions
• Sufficient swapping
• ORACLE_HOME status
Downloading Oracle Database: Step 1

All items boxed in color red are important to follow.


1. Type in the complete website address where you can find the free download for
Oracle Database.
2. Click on Accept Licensed Agreement.
3. Choose the type of Oracle Database depending on your Operating System
Specification.
Downloading Oracle Database: Step 2

After Choosing the correct version of Oracle Database depending on your Operating
System you will be redirected to this page.
1. Provide your valid Username/ Email and Password.
Downloading Oracle Database: Step 3

When email and Password is successfully validated you will be redirected to this
page.
1. Fill up necessary and required information in the registration form
Downloading Oracle Database: Step 4

1. Click on Continue.
2. Open your personal email for account validation
Downloading Oracle Database: Step 5

1. Click on the link: Verify E-mail Address


Downloading Oracle Database: Step 6

1. By clicking on Continue after the Email Verification: Oracle Software is


automatically downloaded as shown in the image zip file. Wait until the file is
downloaded
Installing Oracle Database: Step 1
Running the setup.exe
1. When Download is completed click on the zip file

2. Double click the Disk1

3. Double Click the setup.exe, when setup.exe


is clicked Extracting File OracleXE12 is open.
As shown in the next image.
Installing Oracle Database: Step 2
Loading the Oracle File
Installing Oracle Database: Step 3
Welcome Module
Installing Oracle Database: Step 4
License Agreement
Installing Oracle Database: Step 5
Choose a Location
Installing Oracle Database: Step 6
Setting Password: oracle
Password used:
Oracle
Installing Oracle Database: Step 7
Settings Summary
Installing Oracle Database: Step 8
Set up initiation
Installing Oracle Database: Step 8
Installation Completed
Installing Oracle Database: Step 9
Initiating a Session
1. Click on Start menu then double click the : Run SQL Command Line.

2. Or Click on Start > Choose all Programs>Oracle Database 11g Express


Edition> Run SQL Command Line
Installing Oracle Database: Step 9
Initiating a Session
3. Type in connect system and password during installation.
Lesson Summary:
Before proceeding with the next Chapters the student should
finished the following:
 Create Oracle Account – www.oracle.com
 Successfully Install Oracle Database 11g Express Edition
 Able to establish as user Connection at isqlplus using:
CONNECT
USERNAME: SYSTEM (Global Connection to Oracle)
PASSWORD: oracle (password inputted by the student during installation)
Database Management System 1

Data Definition Language


Lesson Objective
After completing this lesson, the student should be able
to:
• Categorize differences between database objects.
• Review and analyze the structure of the table.
• Lists and identify the usage of different data types.
• Create a simple table.
• Modify, drop or delete a column after the table is created.
Database Objects
A database objects is composed of the following:
1. Synonym – Gives alternative name to an object.
2. Index – improves the performance of some queries.
3. Sequence – generate numeric values.
4. View – logically represents subsets of data from one or
more table.

5. Table –is also known as basic storage composed of rows


and columns.
Table Naming Rule
Table names and column names must:
• Begin with a letter uppercase, lowercase or a
combination will do.
• At least 30 characters long.
• Must only have a letter from A–Z, or a–z, 0–9, and
special character _(underscore), $ (dollar sign),
and # (sharp symbol)
• Must not duplicate or use the name of another
object owned by the same user
• Not be an Oracle server–reserved word
CREATE TABLE statement
To create a table a user must have

 The CREATE TABLE privilege


 A storage area
 Syntax:
CREATE TABLE tbl_name
(Column_lists datatype (size) [default expression] ;

 Where:
o Tbl_name - is the name of the table
o Column_lists – the lists of columns
o Expression – constraint added on each column (if any).
CREATE TABLE statement cont.
• Example:
CREATE TABLE STUDENTS
(USN_ID NUMBER (6) PRIMARY KEY,
LASTNAME VARCHAR (15) NOT NULL,
FIRSTNAME VARCHAR (15),
COURSE CHAR (4),
YR_LVL CHAR (5));
Data type
1. VARCHAR- Variable-length character data
2. CHAR - Fixed-length character data
3. NUMBER - Variable-length numeric data
4. DATE - Date and time values
5. LONG - Variable-length character data (up to 2 GB
6. CLOB - Character data (up to 4 GB)
7. RAW and LONG RAW - Raw binary data
8. BLOB - Binary data (up to 4 GB)
9. BFILE - Binary data stored in an external file (up to 4 GB)
10. ROWID - A base-64 number system representing the unique address of a row in its
table
Use the ALTER TABLE statement to:
• Add a new column after the table has been
created
• Modify an existing column definition
• Define a default value for the new column
• Drop existing column
• Rename a column
• Change table to a read-only status
Three (3) types of ALTER statement

1.Alter to ADD – add new column after the


table has been created
2.Alter to DROP – delete specific column
3.Alter to MODIFY – modify an existing column
either change the data type size and data
type.
ALTER to ADD
 Syntax:
ALTER TABLE tbl_name
ADD column_name datatype(size);

• Example:
ALTER TABLE STUDENTS
ADD ADDRESS VARCHAR(15);
ALTER to MODIFY
 Syntax:
ALTER TABLE tbl_name
MODIFY column_name [new]datatype[new](size);

 Example:
ALTER TABLE STUDENTS

MODIFY LASTNAME VARCHAR(20);


ALTER to DROP
 Syntax:
ALTER TABLE tbl_name
DROP COLUMN column_name;

 Example:
ALTER TABLE STUDENTS
DROP COLUMN ADDRESS;
Rename the table
 To rename the table or change the existing
name of the table use the RENAME statement;
 Syntax:
RENAME old_tbl_name TO new_tbl_name;
 Example:
RENAME STUDENTS TO STUDYANTE;
Truncate Statement
 To delete the values in the STUDENTS but leaving
it structure you may use the TRUNCATE
statement.
 Syntax:
TRUNCATE TABLE tbl_name;
 Example:
TRUNCATE TABLE STUDYANTE;
Dropping a table
 Using DROP table statement will lose all the data in the
table and all the indexes associated in it.
 Even if a rollback statement is issued the record in the
table will not be restored.
 Syntax
DROP TABLE table ;
• Example:
DROP TABLE STUDYANTE;
Lesson Summary:

In this lesson, you should have learned the following.


 Create new table by using the CREATE table statement.
 Add, modify or drop exiting column using the ALTER statement.
 Change the name of the table using the RENAME statement.
 Delete the table using the DROP statement
 Remove all rows in the table using the TRUNCATE statement.
Database Management System 1

Data Manipulation Language


Lesson Objective
After completing this lesson, the student should be
able to:
 Insert new values in the table using the
INSERT statement.
 Modify existing values in the table using the
UPDATE statement
 Delete existing row using DELETE statement.
Data Manipulation Language
 A DML statement is executed when you:
 Add new rows to a table using INSERT statement
 Modify existing rows in a table using UPDATE
statement
 Remove existing rows from a table using DELETE
statement
What is a transaction
A transaction is consists of a collection of Data
Manipulation Language (DML) statements that
form a logical unit of work.
INSERT statement
 Insert a new row containing values for each column.
 List values in the default order of the columns in the
table.
 Optionally, list the columns in the INSERT clause.
 Enclose character and date values within single quotation
marks.
 Add new rows to a table by using the INSERT statement:
INSERT statement cont.
 Syntax:
INSERT INTO tbl_name values (column_list);
 In the syntax:
o TBL_NAME - Is the name of the table
o COLUMN_LIST - Is the name of the column in the table to populate
o VALUES - Is the corresponding value for the column
 Example:
INSERT INTO STUDENTS VALUES
(500,'REYES','ANNA','BSIS','1');
Inserting Rows with Null Values
1. Implicit method: Omit the column from the column list.
 Example:
INSERT INTO STUDENTS
(USN_ID,LASTNAME)
VALUES (502,'CUBAO');
2. Explicit method: Specify the NULL keyword in the VALUES clause.
 EXAMPLE:
INSERT INTO STUDENTS VALUES
(505,'ABIOG','SHIELA',NULL,NULL);
Changing Data in a Table
 Modify existing values in a table with the UPDATE statement:

 Syntax:

UPDATE TBL_NAME
SET COLUMN = NEW VALUES
[WHERE CONDITION];
 In the syntax:
 Tbl_name - Is the name of the table
 set column - Is the name of the column in the table to populate
– new_value - Is the corresponding value or subquery for the column
– condition - Identifies the rows to be updated, should apply either
Comparison Condition, Logical Condition or apply a subquery.
Changing Data in a Table cont.
 Example: 1 column
UPDATE STUDENTS
SET FIRSTNAME = 'MARVIN'
WHERE USN_ID=502;
• Updating two columns in one UPDATE statement.
– To update to or more columns in one UPDATE statement put a comma (,) after
each column called in the SET clause.

 Example:
UPDATE STUDENTS
SET YR_LVL='IRREG', LASTNAME = 'ABIOG'
WHERE USN_ID = 505;
DELETE Statement

 You can remove existing rows from a table by


using the DELETE statement:
 Syntax:
DELETE FROM TBL_NAME
WHERE CONDITION;
 Example:
DELETE FROM STUDENTS
WHERE YR_LVL='1';
Lesson Summary:

In this lesson, you should have learned the


following.

 Insert into to add new rows in a table

 Update to modify existing values is a table

 Delete to remove specific rows in a table


Database Management System 1

SELECT Statement
Lesson Objective

After completing this lesson, the student should


be able to:
• List and enumerate the capabilities of SQL SELECT
statements

• Write and execute a basic SELECT statement


Three application of SELECT
1. Projection
2. Selection
3. Joins
Basic SELECT Statement
• Is used to create a different type of report.
• Syntax:
SELECT (COLUMN_LIST [EXPRESSION])
FROM TBLE_NAME

• Where:
o A SELECT clause, which specifies the columns to be displayed
o A FROM clause, which identifies the table containing the
columns that are listed in the SELECT clause
Select (ALL) column
• You can display all rows and column in a table
by using the SELECT followed by (*) asterisk.
• (*) is used to call/display all row in the column.
• Example:
SELECT * FROM AUTHORS
Select SPECIFIC row
• Specifically display a column by using the SELECT statement then separate
with commas.
• In the SELECT clause, specify the columns that you want to be displayed in
the order in which you want them to appear in the output.
• For example, to display the last name before the first name of author in
AUTHORS table use the following example
• Example:
SELECT LNAME, FNAME
FROM AUTHORS;
Writing SQL Statements guidelines
• SQL statements are not case sensitive, a user may use all capital letter
combination of small or uppercase.
• SQL statements can be entered on one or many lines to make the code
readable.
• Keywords cannot be split across lines or abbreviated. Example: SELECT should
be call ad SELECT not SE LECT
• Clauses are usually placed on separate lines for readability and ease of editing
and to make code readable.
• Indents should be used to make code more readable.
• Keywords typically are entered in uppercase; all other words, such as table
names and columns names are entered in lowercase but is not required.
Arithmetic Expressions
• Create expression with number and date values.
• An arithmetic expression can contain column names,
constant numeric values, and the arithmetic
operators.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
Arithmetic Expressions cont.
• Example:
SELECT LNAME, FNAME, BOOK, YR_PUB + 5
FROM AUTHORS;
Rules of Precedence
• If all operators are present, multiplication and division
occur before addition and subtraction.
• Operators of the same priority example: multiplication and
division are evaluated from left to right.
• To override the default precedence or to clarify the
statement use parentheses. ()
• Example: without the parentheses operator
SELECT LNAME, FNAME, BOOK, 10 * YR_PUB + 5
FROM AUTHORS;
Rules of Precedence cont.
• Example: with parentheses operator
SELECT LNAME, FNAME, BOOK, 10 * (YR_PUB + 5)

FROM AUTHORS;
Defining NULL values
• Null is a value that is unavailable, unassigned,
unknown, or inapplicable.
• Null is not the same as zero or a blank space.
• If a row lacks a data value for a particular column, that
value is said to be null or to contain a null.
• Example:
SELECT ID, FNAME, TYPE, YR_PUB
FROM AUTHORS;
Null values is Arithmetic Expression
• If the arithmetic expression contains a null
value, the result would also be null.
• For example, if you attempt to perform
multiplication by zero, you get an error.
However, if you multiply a number by null, the
result is a null or unknown.
• Example:
SELECT LNAME, FNAME, BOOK, 10 * YR_PUB * 5
FROM AUTHORS;
A column alias:
• Renames a column heading
• Is useful with calculations
• Immediately follows the column name (There can also be the
optional AS keyword between the column name and the alias.)
• Requires double quotation marks if it contains spaces or special
characters, or if it is case-sensitive
• Example: AS Keyword
SELECT FNAME AS NAME, LNAME AS SURNAME, YR_PUB + 5 AS YEAR
FROM AUTHORS;
A column alias: cont.
• Example: with Double Quotation Mark “”
SELECT FNAME "GIVEN NAME", LNAME "SURNAME", YR_PUB + 5
"YEAR PUBLISHED"
FROM AUTHORS;

• Example: combination of AS and “” mark


SELECT FNAME AS "GIVEN NAME", LNAME AS "SURNAME", YR_PUB + 5
AS "YEAR PUBLISHED"

FROM AUTHORS;
Concatenation operator:
• Links columns or character strings to other columns
• Is represented by two vertical bars (||)
• Creates a resultant column that is a character
expression
• Example:
SELECT LNAME||FNAME AS "COMPLETE NAME", BOOK
FROM AUTHORS;
Literal Character Strings
• A literal is either a character, a number, or a date that is included
in the SELECT statement.
• Date and character literal values must be enclosed in single
quotation marks.
• Literal strings of free-format text can be included in the query
result and are treated the same as a column in the SELECT list.
• Each character string is output once for each row returned
• Example:
SELECT LNAME||' , '||FNAME AS "COMPLETE NAME", BOOK
FROM AUTHORS;
Literal Character Strings cont.
• Additional Example: Concatenation two
or more columns:
• Example:
SELECT LNAME||' , '||FNAME|| ' is the author of '
||BOOK as "AUTHORS RECORD"
from AUTHORS
Lesson Summary:

In this lesson, you should have learned the following.

• Use the * to call all rows and columns in the table.


• Display specific column by specifying the column lists in
the select list.
• Make use of arithmetic expression
• Rename a column heading
• Make use of concatenation operator as well as character
literal string.
Database Management System 1

WHERE Statement
Lesson Objective
After completing this lesson, the student should be
able to:
• Use WHERE condition to limit the rows that are
retrieved by a query

• Sort the rows that are retrieved by a query using


ascending or descending order
Where Clause
• Restrict the rows that are returned by using the WHERE clause:
• Syntax:
SELECT (COLUMN_LIST [EXPRESSION])
FROM TBLE_NAME
WHERE CONDITION;

• Where:
o A SELECT clause, which specifies the columns to be displayed
o A FROM clause, which identifies the table containing the columns that
are listed in the SELECT clause
o A WHERE is used to identify what specific condition you would like to
add in the select statement to restrict the rows returned by a query.
Where Clause cont.
• The WHERE clause can ne use to compare values in columns, add
literal character string in between the two column, arithmetic
expressions, or functions. It consists of three elements:
• Column name
• Comparison condition
• Column name, constant, or list of values
• Example:
SELECT ID, LNAME, FNAME, BOOK, TYPE
FROM AUTHORS
WHERE TYPE = 'CSIT';
Character Strings and Dates
• If the Select statements contains character strings and date
values always enclosed in single quotation marks.

• Character values are case-sensitive and date values are


format-sensitive.

• Example:
Comparison Condition:
 Comparison operators are used in conditions that compare
one expression with another value or expression.
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> or != Not equal to
IN (SET) Match any of the values inside the (SET)
BETWEEN..AND Between two inclusive values
LIKE Match a character pattern
IS NULL Is a NULL value
Using Comparison Operator
 Example:
SELECT LNAME, FNAME, BOOK, YR_PUB
FROM AUTHORS
WHERE YR_PUB < 1995;

 Example:
SELECT LNAME, FNAME, BOOK, YR_PUB
FROM AUTHORS
WHERE YR_PUB <= 1995;
Range Conditions Using the BETWEEN Operator

 To display rows based on a range of values use the


BETWEEN operator. The rang specify in the where clause
must contains a lower limit and an upper limit.
 Use the BETWEEN operator to display rows based on a
range of values
 Example:
SELECT ID, FNAME, LNAME, BOOK, TYPE, AC_NO, YR_PUB
FROM AUTHORS
WHERE ID BETWEEN 10 AND 15;
Membership Condition Using the IN Operator

 Use the IN operator to test for values in a list:


 To test for values in a specified set of values, use the
IN operator. The condition defined using the IN
operator is also known as the membership condition.
 Example:
SELECT ID, FNAME, LNAME, BOOK, TYPE, AC_NO, YR_PUB
FROM AUTHORS
WHERE TYPE IN ('BA','GENED');
Pattern Matching Using the LIKE Operator
• To perform wildcard searches of valid search string values in a query use the
LIKE operator.
• Search conditions can contain either literal characters or may also be applied
in numbers:
• % denotes zero or many characters.
• _ denotes one character.
• Example: Getting the first letter
SELECT ID, FNAME, LNAME, BOOK, TYPE, AC_NO, YR_PUB
FROM AUTHORS
WHERE FNAME LIKE 'M%';

• Example: Getting the second letter


SELECT ID, FNAME, LNAME, BOOK, TYPE, AC_NO, YR_PUB
FROM AUTHORS
WHERE LNAME LIKE '%O';
Escape Identifier
• The % percentage symbol and _ underscore symbols can be used
in any combination with literal characters. This means you can apply
this to search for a first, last or in between string with the same
values. When you need to have an exact match for the
actual percentage symbol and _ underscore characters, use the
ESCAPE identifier. This option specifies what the escape character is.
• Example: Skipping the first letter
SELECT ID, FNAME, LNAME, BOOK, TYPE, AC_NO, YR_PUB
FROM AUTHORS
WHERE FNAME LIKE '_E%';
Escape Identifier cont.
• Example: Getting string/number or character
in between %%.
SELECT ID, FNAME, LNAME, BOOK, TYPE, AC_NO, YR_PUB
FROM AUTHORS
WHERE LNAME LIKE '%CA%';
Using the NULL Conditions
• Test for nulls with the IS NULL operator.
• The NULL conditions include the IS NULL condition and the IS NOT
NULL condition.
• The IS NULL condition tests for nulls. A null value means that the value
is unavailable, unassigned, unknown, or inapplicable. Therefore, you
cannot test with =, because a null cannot be equal or unequal to any
value.
• Example:
SELECT ID, FNAME, LNAME, BOOK, TYPE, AC_NO, YR_PUB
FROM AUTHORS
WHERE FNAME IS NULL;
Using the ORDER BY Clause
• Sort the retrieved rows with the ORDER BY clause:
• ASC: Ascending order, default
• DESC: Descending order
• The ORDER BY clause comes last in the SELECT statement:
• In the syntax:
• ORDER BY - specifies the order in which the retrieved rows are displayed
• ASC - orders the rows in ascending order (This is the default order.)
• DESC - orders the rows in descending order.
• Example:
SELECT LNAME, BOOK, TYPE
FROM AUTHORS
WHERE TYPE = 'CSIT'
ORDER BY LNAME DESC;
Lesson Summary:

In this lesson, you should have learned the


following.

• Where condition that applies comparison condition


• Where condition that applies other comparison
operator.
• Sort the data using Order By ASC or DESC
Database Management System 1

Logical Operator
Lesson Objective
After completing this lesson the student should be
able to:
 Define the rows returned using the three logical
condition AND, OR and NOT.

 Identify the result when the order of precedence


is applied in WHERE clause.
Three types of Logical Condition
Operator Description
AND Returns TRUE if both component
conditions are true
OR Returns TRUE if either component
condition is true
NOT Returns TRUE if the condition is false
Using the AND Operator
 Both the component conditions must be true for any record
to be selected.
 Example:
SELECT ID, FNAME, LNAME, BOOK, TYPE
FROM AUTHORS
WHERE TYPE='CSIT'
AND BOOK LIKE '%A';
Using the OR Operator
 Either of the component conditions must be true for any
record to be selected.
 Example:
SELECT ID, FNAME, LNAME, BOOK, TYPE
FROM AUTHORS
WHERE TYPE='CSIT'
OR BOOK LIKE '%A';
Using the NOT Operator
 Reverse the value from TRUE to FALSE or FALSE to TRUE.
 The NOT operator can also be used with other SQL operators,
such as BETWEEN, LIKE, and NULL.

 Example:
SELECT ID, FNAME, LNAME, TYPE,YR_PUB
FROM AUTHORS
WHERE YR_PUB NOT IN(2010, 1995);
Rules of Precedence
 The rules of precedence determine the order in which
expressions are evaluated and calculated.
 The table in the slide lists the default order of precedence.
• To override the default order of expression to be calculated
first put parentheses around the expression.
Rules of Precedence cont.
Operator Meaning
1 Arithmetic operators
2 Concatenation operator
3 Comparison conditions
4 IS [NOT] NULL, LIKE, [NOT] IN
5 [NOT] BETWEEN
6 Not equal to
7 NOT logical condition
8 AND logical condition
9 OR logical condition
Rules of Precedence
 Example:
SELECT (FNAME||','||LNAME)AS NAME, BOOK, TYPE,AC_NO
FROM AUTHORS
WHERE TYPE='CSIT'
OR AC_NO LIKE'%S'
AND LNAME LIKE 'S%';
• In this example, there are two conditions:
 The first condition is that the AC_NO end with capital letter S and the LNAM start with
capital letter S.
 The second condition is that the TYPE is CSIT.
 Therefore, the SELECT statement reads as follows:
• “Select the row if an author AC_NO ends with letter S and the LNAME starts with letter
S or the TYPE is equal to CSIT.
Rules of Precedence cont.
 Example: with parentheses
SELECT (FNAME||','||LNAME)AS NAME, BOOK, TYPE,AC_NO
FROM AUTHORS
WHERE (TYPE='CSIT‘
OR AC_NO LIKE'%S')
AND LNAME LIKE 'S%';
 In this example, there are two conditions:
 The first condition is that the AC_NO ends with letter S or the TYPE are equal
to CSIT
 The second condition is that the LNAME ends with letter S.
 “Select the row if an author AC_NO ends with letter S and the LNAME starts
with letter S and the TYPE is equal to CSIT.
Lesson Summary:

In this lesson, you should have learned the


following.

 Apply the logical condition.


 Identify the order of precedence.
Database Management System 1

Single-Row Function
Lesson Objective

After completing this lesson, the student should


be able to:
• Describe the various types of functions available in SQL

• Use the character, number, and date functions in SELECT


statements
Functions are a very powerful feature of SQL. They can be used
to do the following:

• Perform calculations on data

• Modify individual data items

• Manipulate output for groups of rows

• Format dates and numbers for display

• Convert column data types


2 Types of Functions

Functions

Single – Row Multiple – Row


Function Function
Single-Row Functions
Single-Row
Function

Character Function Number Function

MOD
Case Character
TRUNC
Manipulation Manipulation
ROUND
Case Conversion function:
Function Result
LOWER(‘Database Management database management system
System’)
UPPER(‘Database Management DATABASE MANAGEMENT
System’) SYSTEM
INITCAP(‘Database Management Database Management System
System’)

• Where:
• LOWER: Converts mixed-case or uppercase character strings to lowercase

• UPPER: Converts mixed-case or lowercase character strings to uppercase

• INITCAP: Converts the first letter of each word to uppercase and the
remaining letters to lowercase
Using Case-Conversion function
 Example: UPPER
SELECT UPPER(LNAME||','||FNAME) AS "NAME"
FROM AUTHORS
WHERE LNAME LIKE'S%';
 Example: lower
SELECT LOWER(LNAME||','||FNAME) AS "NAME"
FROM AUTHORS
WHERE LNAME LIKE'S%';
 Example: lower
SELECT INITCAP(LNAME||','||FNAME) AS "NAME“
FROM AUTHORS
WHERE LNAME LIKE'S%';
Character Manipulation Function
Function Result
CONCAT(‘Data’,’Base’) DataBase
SUBSTR(Database System, 1, 8) Database
LENGTH(‘Database’) 8
INSTR(Database,’b’) 5
LPAD(price,6,’$’) $$$360
RPAD(proce,6,’$’) 360$$$
REPLACE(Database, ‘a’,’c’) Dctcbce
TRIM(‘D’ from ‘Database’) atabase
Character Manipulation Function cont.
• Where:
• CONCAT: Joins values together (You are limited to using two parameters with CONCAT.) instead used
|| (double bars) if it contains two or more columns and character literal string

• SUBSTR: Extracts a string of determined length

• LENGTH: Shows the length of a string as a numeric value

• INSTR: Finds the numeric position of a named character

• LPAD: Returns an expression left-padded to the length of n characters with a character expression

• RPAD: Returns an expression right-padded to the length of n characters with a character expression

• TRIM: Trims leading or trailing characters (or both) from a character string (If
trim_character or trim_source is a character literal, you must enclose it within
single quotation marks.)
Using Character Manipulation Function

 Example: CONCAT
SELECT CONCAT(LNAME,FNAME), YR_PUB

FROM AUTHORS

WHERE YR_PUB = 2010;

 Example: SUBSTR
SELECT LNAME, FNAME, BOOK

FROM AUTHORS

WHERE SUBSTR(BOOK,6)='ING';
Using Character Manipulation Function cont.

 Example: LENGTH, INSTR


SELECT BOOK,LENGTH(BOOK), INSTR(BOOK,'A')

FROM AUTHORS

WHERE BOOK LIKE 'A%';


 Example: RPAD, LPAD
SELECT BOOK, LPAD(YR_PUB,7,'$'), RPAD(YR_PUB,7,'@')

FROM AUTHORS

WHERE BOOK LIKE '%ING%';


Using Character Manipulation Function: cont.

 Example: REPLACE
SELECT REPLACE(FNAME,'A','T')

FROM AUTHORS;
 Example: TRIM
SELECT BOOK, TRIM('A' FROM BOOK)

FROM AUTHORS;
Number Function
Function Result
ROUND(75. 46,1) 75.5
TRUNC(75.46,1) 75
MOD(100/3) 10

• Where:
• ROUND: Rounds value to a specified decimal

• TRUNC: Truncates value to a specified decimal

• MOD: Returns remainder of division


Dual Table
• The DUAL table is owned by the user SYS and can be accessed by all
users. It contains one column, DUMMY, and one row with the value X.

• The DUAL table is useful when you want to return a value only once
(for example, the value of a constant, pseudocolumn, or expression
that is not derived from a table with user data).

• The DUAL table is generally used for completeness of the SELECT


clause syntax, because both SELECT and FROM clauses are mandatory,
and several calculations do not need to select from the actual tables.
Using Number Function
 Example: ROUND
SELECT ROUND(75.475,2),ROUND(75.475,1), ROUND(75.475,-1)

FROM DUAL;

 Example: TRUNC
SELECT TRUNC(75.475,2),TRUNC(75.475,1),TRUNC(75.475,-1)

FROM DUAL;
 Example: MOD
SELECT MOD(1000,300)

FROM DUAL;
Lesson Summary:

In this lesson, you should have learned how to:


• Perform calculations on data using functions
• Modify case and character values.
Database Management System 1

Multiple-Row Function
Lesson Objective

After completing this lesson, the student should


be able to:
 Enumerate the available group functions in Oracle

 Discuss and make use of the available group functions

 Group the data by using the GROUP BY clause

 Either Include or exclude grouped rows by using the HAVING clause


Group Function

• A group functions is use to operate on sets of rows in order to


give one result per group. These sets may include the entire
table or the table split into groups.
Types of Group Function
Function Description
AVG Average value of N ignoring null values
COUNT Count the number of rows where expr evaluates to something
other than null
Count all selected rows using *, including duplicates and rows
with null
MAX Maximum value of expression ignoring null values
MIN Minimum value of expression ignoring null values
STDEV Standard deviation of N ignoring null values
SUM Sum values of N ignoring null values
VARIANCE Variance of N ignoring null values
Group Function Syntax:

SELECT group_function(Column_lists),…

FROM table_name

[WHERE condition];

• Where

– SELECT Group_function – is the name of the group function ex. MIN

– FROM table_name – is the name of the table

– WHERE condition – is optional


Using the AVG and SUM function

 Can be used only with numeric data types


 Example:
SELECT AVG(YR_PUB), SUM(YR_PUB)
FROM AUTHORS;
Using the MIN and MAX function

 You can use the MAX and MIN functions for numeric,
character, and date data types.
 Example:
SELECT MIN(LNAME), MAX(LNAME)
FROM AUTHORS;
Using the STDDEV and VARIANCE function

 Can be used only with numeric data


types
 Example:
SELECT STDDEV(ID), VARIANCE(ID)
FROM AUTHORS;
Using the COUNT function
The COUNT function has three formats:

1. COUNT(*) - COUNT(*) returns the number of rows in a table that satisfy the
criteria of the SELECT statement, including duplicate rows and rows containing
null values in any of the columns. If a WHERE clause is included in the SELECT
statement, the function COUNT(*) returns the number of rows that satisfy the
condition in the WHERE clause.

2. COUNT(expr) - In contrast, COUNT(expr) returns the number of non-null values


that are in the column identified by expr.

3. COUNT(DISTINCT expr) – While COUNT(DISTINCT expr) returns the number of


unique, non-null values that are in the column identified by expr.
Using the COUNT function cont.
• Example: Using Count(*)
SELECT COUNT(*)

FROM AUTHORS;

• Example: Using Count(expr)


SELECT COUNT(TYPE)

FROM AUTHORS

WHERE TYPE='CSIT';

• Example: Using Count(DISTINCT expr)


SELECT COUNT(distinct YR_PUB)

FROM AUTHORS;
Using NVL Function to include NULL values

• By default group function in Oracle always ignores NULL values to include


the NULL values in counting of output you may use the NVL function.

• Example: default output


SELECT AVG(YR_PUB)

FROM AUTHORS;

• Example: with NVL function


SELECT AVG(NVL(YR_PUB,0))

FROM AUTHORS;
Creating groups of data using GROUP BY clause.

 All available group functions have treated the table as one group of large
information in order to divide the table of information into smaller group
use the GROUP BY clause.
 Syntax:
SELECT function_name(column), group_function(column)
FROM table_name
[WHERE condition]
[GROUP BY group_by_expr]
[ORDER BY column];

 Where:
group_by_expr - Specifies the columns whose values determine the basis for grouping rows.
Guidelines in using a GROUP BY clause

 If you include a group function in a SELECT clause, you cannot select


individual column as well which only means that the individual column
called in the SELECT clause should also appears in the GROUP BY clause.
An error message will appear after running the query if you fail to include
the column list in the GROUP BY clause.
 Using a WHERE clause, you can exclude rows before dividing them into
groups.
 You can substitute column by an Expression in the SELECT statement.
 You must include the columns in the GROUP BY clause.
 You cannot use a column alias in the GROUP BY clause
Using GROUP BY Clause

 When using the GROUP BY clause, make sure that all


columns in the SELECT list that are not group
functions are included in the GROUP BY clause.
 Example:
SELECT TYPE, COUNT(*)
FROM AUTHORS
GROUP BY TYPE;
Using GROUP BY Clause cont.

Grouping two (2) columns


 To see the results for groups within group use this
example.
 Example:
SELECT TYPE, YR_PUB, SUM(YR_PUB), AVG(YR_PUB)
FROM AUTHORS
GROUP BY TYPE, YR_PUB;
Using GROUP BY Clause cont.

• Example: Group by with WHERE condition


SELECTTYPE, YR_PUB,
COUNT(DISTINCT(YR_PUB)),SUM(YR_PUB), AVG(YR_PUB)
FROM AUTHORS
WHERE YR_PUB > 1995
GROUP BY TYPE, YR_PUB;
Having Clause

• You cannot use the WHERE clause to restrict groups.


• You use the HAVING clause to restrict groups.
• You cannot use group functions in the WHERE clause.
Syntax
SELECT function_name(column), group_function(column)
FROM table_name
[WHERE condition]
[GROUP BY group_by_expr]
[HAVING group Condition]
[ORDER BY column];
Having Clause cont.

• Example: with HAVING CLAUSE


SELECT YR_PUB, COUNT(DISTINCT(YR_PUB)),SUM(YR_PUB),
AVG(YR_PUB)
FROM AUTHORS
GROUP BY YR_PUB
HAVING MAX(ID)>15;
Having Clause cont.

• Complete SELECT
• Example:
SELECT TYPE, MIN(FNAME),MAX(ID)
FROM AUTHORS
WHERE ID BETWEEN 10 AND 15
GROUP BY TYPE
HAVING MAX(ID)>= 5
ORDER BY MAX(ID) DESC;
Nesting Group Function

• Group functions can be nested to a depth of two


functions.
• Example:
SELECT MAX(AVG(YR_PUB))
FROM AUTHORS
GROUP BY TYPE;
Lesson Summary:

In this lesson, you should have learned how to:


• Use the group functions COUNT, MAX, MIN, SUM, and
AVG
• Include the NULL values using the NVL function
• Write queries that use the GROUP BY clause
• Write queries that use the HAVING clause
• Group date using 2 columns
• And apply Nested Groups
Database Management System 1

Set Operators
Lesson Objective

After completing this lesson, the student should


be able to:
 Describe and define what sets operators are.

 Make used of sets operator.

 Apply different SELECT statement into sets.


Set Operators

• Set operators combine the results of two or more component


queries into one result. Queries containing set operators are
called compound queries.
Types of Set Operator
Function Description

Union Rows from both queries after eliminating duplications

Union ALL Rows from both queries including all duplications

Intersect Rows that are common to both queries

Minus Rows in the first query that are not present in the second
query
Set Operator Guidelines

 The expressions in the SELECT lists must match in


number.
 The data type of each column in the second query
must match the data type of its corresponding
column in the first query.
 Parentheses can be used to alter the sequence of
execution.
 ORDER BY clause can appear only at the very end
of the statement.
Oracle Server and Set Operators

• The duplicated rows are automatically eliminated


in the final report except in UNION ALL.
• The column names selected from the first query
appear in the result.
• By default, the output is sorted in ascending
order except in UNION ALL.
Union Operator

 The UNION operator returns all rows that are


selected by either query. Use the UNION operator to
return all
Union: Guidelines

 The number of columns being selected must be the same.


 The data types of the columns being selected must be in the
same data type group (such as numeric or character).
 The names of the columns need not be identical.
 UNION operates over all of the columns being selected.
• The NULL values or blank data in the report are not ignored
during duplicate checking.
 By default, the output is sorted in ascending order of the
columns of the SELECT clause.
Union Example

 Example: Retrieve the record on both


tables with the same values after
eliminating duplicated data.
SELECT BOOK, AC_NO
FROM AUTHORS
UNION
SELECT BOOK, AC_NO
FROM BORROWER;
Union ALL
• UNION ALL operator is use to return all rows
from multiple queries or multiple tables.
Authors Borrower
Union ALL Guideline
• The guidelines for UNION and UNION ALL are
the same, except for the following: unlike
UNION, in UNION ALL duplicated rows are not
eliminated in the report and the output is not
sorted by default.
Union ALL Example

SELECT BOOK, AC_NO

FROM AUTHORS

UNION ALL

SELECT BOOK, AC_NO

FROM BORROWER;
Intersect Operator

 Use the INTERSECT operator to return all rows that are common to
multiple queries.
Intersect Guidelines

 The number of columns and the data types of the columns


being selected by the SELECT statements in the queries must
be identical in all the SELECT statements used in the query.
The names of the columns, however, need not be identical.
 Reversing the order of the intersected tables does not alter
the result.
 INTERSECT does not ignore NULL values.
Intersect Example

SELECT BOOK, AC_NO


FROM AUTHORS
INTERSECT
SELECT BOOK, AC_NO
FROM BORROWER;
Minus Operator

• Use the MINUS operator to return all distinct rows selected by


the first query, but not present in the second query result set
(the first SELECT statement MINUS the second SELECT
statement).
Minus Guideline

• Note: The number of columns must be the same and


the data types of the columns being selected by the
SELECT statements in the queries must belong to the
same data type group in all the SELECT statements
used in the query. The names of the columns,
however, need not be identical.
Minus Example

SELECT BOOK, AC_NO


FROM AUTHORS
MINUS
SELECT BOOK, AC_NO
FROM BORROWER;
Lesson Summary:

In this lesson, you should have learned how to:


• Use the 4 types of SET operator
• Identify the difference between set operator
• Identify the guideline in using set operator.

S-ar putea să vă placă și