Upload
niranjan
View
218
Download
0
Embed Size (px)
Citation preview
8/8/2019 Instructor Guide for Introduction
1/174
.......................................................................................
October 1999
Instructor Guide forIntroduction to Oracle:SQL and PL/SQL
8/8/2019 Instructor Guide for Introduction
2/174
Author
Priya Nathan
Copyright Oracle Corporation, 1999. All rights reserved.
This documentation contains proprietary information of Oracle Corporation. It is
provided under a license agreement containing restrictions on use and disclosure
and is also protected by copyright law. Reverse engineering of the software is
prohibited. If this documentation is delivered to a U.S. Government Agency of the
Department of Defense, then it is delivered with Restricted Rights and the
following legend is applicable:
Restricted Rights Legend
Use, duplication or disclosure by the Government is subject to restrictions for
commercial computer software and shall be deemed to be Restricted Rights
software under Federal law, as set forth in subparagraph (c) (1) (ii) of DFARS
252.227-7013, Rights in Technical Data and Computer Software (October 1988).
This material or any portion of it may not be copied in any form or by any means
without the express prior written permission of Oracle Corporation. Any other
copying is a violation of copyright law and may result in civil and/or criminal
penalties.
If this documentation is delivered to a U.S. Government Agency not within the
Department of Defense, then it is delivered with Restricted Rights, as defined in
FAR 52.227-14, Rights in Data-General, including Alternate III (June 1987).
The information in this document is subject to change without notice. If you findany problems in the documentation, please report them in writing to Education
Products, Oracle Corporation, 500 Oracle Parkway, Box SB-6, Redwood Shores,
CA 94065. Oracle Corporation does not warrant that this document is error-free.
Oracle is a registered trademark of Oracle Corporation.
All other products or company names are used for identification purposes only
and may be trademarks of their respective owners.
8/8/2019 Instructor Guide for Introduction
3/174
.....................................................................................................................................................Oracle Education Products 3
.....................................................................................................................................................Introduction
IntroductionIntroduction to Oracle: SQL and PL/SQL is often the first course that many Oracle students
attend. You might be their first contact with any Oracle personnel.
At the same time, this may be one of the first courses that you teach as an Oracle instructor, so
you might appreciate some help in achieving the best performance possible at an early stage ofyour career.
The tools and tips in this section come from the highly recommended AIT (Advanced
Instructional Techniques) class, which many Oracle Educaton instructors have attended. If
you attend that class, you will learn all that is hereand much more.
Aim of This Document
To help you make this the best technical course that students have ever attended, to excite
them to learn, and to make them want to come back for more
To give you some tips and techniques to help you vary your lecture style, avoid monotony
in classes, and make the learning experience more entertaining and interesting for both the
students and yourselfThis document is not a substitute for your own personal training and delivery instructions that
you receive from your Education department.
Using This Document
None of these suggestions and techniques are mandatory. They are simply examples of how to
introduce variety and change of pace into your classes.
Not all techniques suit all instructors. Choose those with which you feel most comfortable. If
possible, test the techniques with a fellow instructor who is also eager to encourage interactive
learning in the classroom.
8/8/2019 Instructor Guide for Introduction
4/174
.....................................................................................................................................................4 Oracle Education Products
.....................................................................................................................................................
The Learning Environment
Introduction
Establish a pleasant and effective learning environment at the start of a class.
Tips to Improve the Class Climate
When students first arrive at a course, they have doubts, concerns, and fears. To change these
negative feelings to positive ones, try to make students feel welcome, safe, comfortable,
important, competent, understood, and responsible. Think carefully about what you can say
and do to foster these feelings of comfort and familiarity in your students, especially in the
first 30 minutes of the course.
Students learn more effectively in a physically and emotionally comfortable environment.
Early Arrivals
Some students arrive early for class. Do not ignore these studentswelcome them with a
smile. Make them feel comfortable by introducing yourself and providing details about the
class and the environment.
Housekeeping
Explaining the housekeeping ground rules at the start of a class is very important to make
students feel comfortable and confident in their surroundings. Remember to explain some of
the following points:
Layout of building: Point out the location of restrooms, refreshments, and so on.
Timing of class: State the start and end times and lunchtime.
Questions: Encourage students to ask questions during the class.
Personal Introductions
Allowing time for students to introduce themselves is important for you and for them. Whenyou know that course timings are tight, it is very tempting to reduce time allowed for
introductions or skip them altogether, but you do so at your peril. Introductions help foster a
good relationship between all the students.
Use introductions to find out more about your audience: those who might not have sufficient
prerequisite knowledge, those who might cause problems because they are eager to prove
themselves in front of others, and so on.
Thought for the Day
Never do for the learners what they can do for themselves.
Efficient Use of Icebreakers
You can use icebreakers successfully throughout the course. At the beginning of a class: Choose something that helps students get to know others in the
class.
8/8/2019 Instructor Guide for Introduction
5/174
.....................................................................................................................................................Oracle Education Products 5
.....................................................................................................................................................The Learning Environment
After break times: Occupy and entertain those who return early from breaks.
Afternoon: Avoid the graveyard-shift syndrome. Give students a short, light activity to
refresh them after lunch or in the late afternoon.
Icebreakers to Use in Class Introductions
You can vary your class introductions with either of these icebreakers:
Partner Introductions
Ask each person to select a partner who is a stranger to them.
Give ten minutes for partners to interview each other and find out as much as possible
about each other.
Suggest that they take notes during their interviews.
After the interviews, ask each person to stand in turn and introduce their partner to the
entire group (encourage them to refer to their notes).
Note: This icebreaker works best with smaller groups (fewer than 20). For larger groups,
it is too time-consuming.
Icebreakers for After-Lunch Activity
Try using one of these to wake up the group after lunch:
Common Ground
Use this icebreaker for small groups or for each small group sitting together as a team
(example: four to six people).
Give the groups a specific time (example: five minutes) to list everything they can find
that they all have in common. Tell them to avoid the obvious (example: we are all taking
this workshop). Ask them to make a list.
After the time is up, ask each group how many items they have in their list.
For fun, ask them to announce some of the most interesting items in their lists.
Dreams and Nightmares
Each person states a dream about something positive that they hope will happen in this
course.
Each person states a nightmare about something negative that they hope will not happen in
this course.
Put the dreams and nightmares on a flip chart so all groups can read them.
Notice that most of these icebreakers are brief exercises that focus on getting to know the
people they will work with. If groups are changed regularly, start each session with a different
icebreaker.
8/8/2019 Instructor Guide for Introduction
6/174
.....................................................................................................................................................6 Oracle Education Products
.....................................................................................................................................................
Lecture Styles
Keywords
As you speak, write keywords on a flip chart to create an emerging content outline.
When you fill a page, tape it to the wall and start a new one on the flipchart. Put no more than seven keywords on a page.
When finished, ask the students to review by recalling the content that is triggered by each
keyword. The review can be an individual exercise or it can be done through discussion in
small groups.
Cartoon Lecture
Find cartoons that relate to the content of your lecture. Transfer the cartoons onto
overhead transparencies.
For each key point in the lecture, show the cartoon after you have described the content
verbally.
When the lecture is finished, show each cartoon again and have the students review thecontent using the cartoon as a mental trigger. The review can be an individual exercise or
it can be done through discussion in groups.
The mind is like the stomach. Its not how much you put into it that counts, but how much it
digests.
Examples and Exceptions
Good lectures often contain examples, analogies, and metaphors.
As you deliver a lecture, ask students in small groups to create an example or analogy of
the point you are describing.
For a change of pace, ask them to create exceptions to the point.
Encourage learners to use situations from their own experience as the source for examples,
where possible.
Fill in the Blank
Design a printed outline of the key ideas to be covered in the lecture.
Leave out a word or short phrase in each item in the outline.
As you lecture, ask students to fill in the missing words.
Before I speak, I have something important to say. Groucho Marx
Search and Learn
Rather than deliver a lecture, put the content in printed form. Use headings and bullets
rather than paragraphs.
Give learners a series of questions to answer by searching through the printed material. If
you want a competitive element, have small groups search quickly for the answer. The
group that finds it first raises their hands and announces the location of the answer. If they
8/8/2019 Instructor Guide for Introduction
7/174
.....................................................................................................................................................Oracle Education Products 7
.....................................................................................................................................................Lecture Styles
are correct, they receive a point. At the end, you could have a prize for the winning group.
Forming Effective Questions
The following points will help you to make your questioning more effective:
Employ the characteristics of a good question: Concise and contains only one idea
Thought provoking and interesting
Focused on important material
Open-ended (requires more than a yes or no answer)
Requires reasoning rather than memory
Challenging but answerable
Four directions for questions:
Direct: Ask a specific student.
Overhead: Ask the students in general; anyone can answer.
Relay: Ask someone else to answer a students question.
Reverse: Mirror a students question back to the same student.
Do not repeat students answers. Otherwise, students may stop listening to each other.
Use crossfire questioning. Refer questions to others, such as:
How would you have answered that?
Why do you think that?
What do you think of that answer?
What evidence do you have for that?
When answering a question, use these techniques:
When someone asks you a question, smile, take a step toward them, and say yes as
if you are pleased to have a question.
Check to be sure everyone heard and understood the question.
Answer briefly and state reasons for your answer.
Tie your answer to key points in your lesson, if possible.
If you do not know an answer, admit itnever bluff. Ask if anyone else knows the
answer. If no one does, offer to find out.
If someone asks a contentious question, give a direct and friendly answer. Do not be
provoked into a defensive position.
If someone asks a question that you will be covering later, say Thats a good
question. We will be covering that in a few minutes.
8/8/2019 Instructor Guide for Introduction
8/174
.....................................................................................................................................................8 Oracle Education Products
.....................................................................................................................................................
BibliographyEitlington, Julius. The Winning Trainer. Gulf Publishing, 1984.
Forbess-Green, Sue.Encyclopedia of Icebreakers . University Associates, 1990.
Jones, Philip (ed.).Adult Learning in Your Classroom. Lakewood Publications,
1982.
Newstrom, John, and Edward Scannell. Games Trainers Play. McGraw-Hill, 1980.
OConnor, Joseph, and John Seymour.Introducing Neuro-Linguistic
Programming. Thorsons, 1995.
OConnor, Joseph, and John Seymour. Training with NLP. Thorsons, 1994.
Pike, Robert. Creative Training Techniques Handbook. Lakewood Publications,
1989.
Scannell, Edward, and John Newstrom.More Games Trainers Play. McGraw-Hill,
1991.
8/8/2019 Instructor Guide for Introduction
9/174
.....................................................................................................................................................Oracle Education Products 9
.....................................................................................................................................................About the Course
About the Course
Lesson Objectives and Aims
Each lesson starts with an objectives page that describes the reasons for the lesson; there is
also an objectives slide that should be used. The intention of each lesson should be clear to
everyonelecturer and studentsat the start of every lesson.
The topics covered in each lesson should give students enough information to complete the
required part of each practice.
Lesson Timings
If a lesson drags on, for whatever reason (yes there will be those exceptions) then break the
lesson for five minutes. Give everyone a rest.
Practices
Practices are as important as the lesson. Practice timings are usually the same as or more than
the lecture time allowance, to ensure that the students get as much exposure to the product as
possible.The "If you have time" questions are there for those who need a challenge; for example, for
students who already have SQL knowledge or are finding the subject easy. What questions
students are expected to complete is made clear in the table at the start of each practice.
Enforcing Learning Points
Consider the following ideas when teaching:
Always use the lesson objectives slide to stress the intention of the lesson, and use the
summary slide to reiterate learning points.
Invite student questions at all times.
At the start of a new day, spend 5 minutes of your time to remind students of the topics
covered the previous day. No detail is required, this is just a memory-jogging session. Do not discuss syntax slides word-for-word. Identify and discuss the main learning points.
In most cases, students have an opportunity to use the syntax during the practices.
Practice Sessions
Some practices, contain "if you want extra challenge" questions. Let the student do these only
if you they have completed all of the other questions within the allocated time and would like
a further challenge to their skills.
Demonstrations
Do not show slides and demonstrate for each slide; use demonstrations to stress learning
points:
There is not enough time.
Students get bored watching the lecturer doing all the work and having all the fun, it
8/8/2019 Instructor Guide for Introduction
10/174
.....................................................................................................................................................10 Oracle Education Products
.....................................................................................................................................................
seems, when they are itching to get their hands on the product.
You can use the Class Management Notes to assist you when teaching the courses. This
document has been constructed to try to help instructors identify what the main learning
points are for any lesson.
You can present the course without any demonstration at all.
Interaction
Ensure the students are aware that the course is interactive. As much as you are there to teach,
the students are there to understand, assimilate, and experiment. If they do not understand
anything that is presented, they should ask questions. Students should not be afraid to ask
questions, or be worried as to whether the questions are relevant. Of course some questions
may be beyond the scope of the course (if that is the case, say so) or beyond the scope of your
knowledge.
Appendixes and Answers
Clearly identify which appendixes are available and where to find them in the manual and
specifically where to find the practice demostrate tables and practice solutions.
Snippets
This course includes animation and activity snippets. A description of these snippets can be
found in Snipdesc.doc along with the other lessons for this course.
Structure of the Instructor Guide
Element Description
Additional information Additional information that the instructor can
share in class
Hint A hint to the instructor with specific reference tothe slide
Additional example An additional example to explain in class
Additional reference Where the instructor can look up additional
information related to the subject of the slide
8/8/2019 Instructor Guide for Introduction
11/174
.....................................................................................................................................................Oracle Education Products 11
.....................................................................................................................................................Introduction
Introduction
Additional Information
If time permits, share the following
information with the class. Structured
systems analysis and design helps in
understanding and designing a system,
which will be programmed later in any
programming language. It is the stepping
stone in creating simple or large, critical-
mission, complex systems. During this
stage, you will learn how to put down on
paper a large, complex system in a short
and understandable manner that can be
understood by any lay person.
Beginning with strategy and analysis, theproject teams objective is to identify the
high-level requirements and develop a
conceptual scope of work. This
information is used to develop the
preliminary cost and time requirements. It
also serves as the foundation for the
remaining phases.
The design phase facilitates the design of
all system components. This includes the
user interface, database model, report
layout, business rules, systems interfacing,
and documentation. In essence, the projectteam creates the blueprints for the
development of the system.
Prototyping may be performed to help
facilitate the design and transition phases
and ensure the validity of business rules,
determine the feasibility of technical
options, and help to expose the value of
the comprehensive information
management system.
System Development Life Cycle
Strategyand
AnalysisDesign
Buildand
Document
Transition
Production
8/8/2019 Instructor Guide for Introduction
12/174
.....................................................................................................................................................12 Oracle Education Products
.....................................................................................................................................................
(continued) Transition is the process of applying
technology, skill, and development
standards to the design specifications.
Testing involves the validation of all
system components to ensure that theproduct operates and performans in
accordance with the design specifications.
QA audits, client reviews, quality
certification, implementation planning,
installation, setup, and training are
included in the production and rollout
phase.
A flexible support and maintenance plan
may include phone support,
troubleshooting, planned upgrades, and
enhancements.
Additional Information
If time permits, share the following
information with the class. A relational set
is often modeled as a table. The items of a
set are the rows of the table. The fields in
the items are the columns. The columns in
a table can have names. The rows are
unordered and unnamed. A database
consists of one or more tables plus a
catalog (also represented by tables)
describing the database.
Relational Database Concept
Dr. E. F. Codd proposed the relational modelfor database systems in 1970.
It is the basis for the relational databasemanagement system (RDBMS).
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
8/8/2019 Instructor Guide for Introduction
13/174
.....................................................................................................................................................Oracle Education Products 13
.....................................................................................................................................................Introduction
Additional Information
If time permits, share the following
information with the class. The relational
model presents an orderly, predictable,
and intuitive approach to organizing,manipulating, and viewing data.
Relational tables have six properties,
which must be satisfied for any table to be
classified as relational. These are:
Entries of attributes are single-valued.
Entries in every row and column
position in a table must be single-
valued. This means columns do not
contain repeating groups.
Entries of attributes are of the same
kind.Entries in a column must be of the
same kind. For example, a column
that stores salary information should
not be used to store commission
information.
No two rows are identical.
Each row should be unique. This
uniqueness is ensured by the values in
a specific set of columns called the
primary key.
The order of attributes is unimportant.There is no significance attached to
the order in which columns are stored
in the table. A user can retrieve
columns in any order.
The order of rows is unimportant.
There is no significance attached to
the order in which rows are stored in
the table. A user can retrieve rows in
any order.
Every column can be uniquely
identified.
Each column is identified by its name
and not its position. A column name
should be unique in the table.
Definition of aRelational Database
A relational database is a collection ofrelations or two-dimensional tables.
Database
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Table Name: DEPT
EMPNO E NAME JOB DEP TNO
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
EMPNO E NAME JOB DEPTNO
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
Table Name: EMP
8/8/2019 Instructor Guide for Introduction
14/174
.....................................................................................................................................................14 Oracle Education Products
.....................................................................................................................................................
Additional Reference
http://cis.csustan.edu/courses/
lodewyck/4720/ERModel/index.htm
http://coba.usf.edu/trimmer/
Chap3/index.htmhttp://www.musc.edu/hap/
Phoenix3/index.htm
Create an entity relationship diagram frombusiness specifications or narratives
Scenario
. . . Assign one or more employees to adepartment . . .
. . . Some departments do not yet haveassigned employees . . .
Entity Relationship Model
EMPLOYEE#* number* nameo job title
EMPLOYEE#* number* nameo job title
DEPARTMENT#* number* name
o location
DEPARTMENT#* number* nameo location
assigned to
composed of
8/8/2019 Instructor Guide for Introduction
15/174
.....................................................................................................................................................Oracle Education Products 15
.....................................................................................................................................................Introduction
Additional Information
If time permits, share the following
information with the class. Object
orientation is the use of objects and classes
in analysis, design, and programming. Theuse of objects distinguishes object
orientation from other techniques such as
traditional structured methods (process-
based: data and function are separate) or
other techniques such as knowledge-based
systems (logic programming, rules:
Prolog) or mathematical methods.
Object orientation is:
View Of The World - A Better
Approach
ProcessIterative/Incremental - Easy to add to
systems
Methods
Analysis
Design
Implementation
Languages
Programming Technique
Object-oriented programming languages
provide full support for object design.
Additional Reference
http://www.cyberdyne-object-
sys.com/oofaq2/
Oracle8: Object RelationalDatabase Management System
User-defined data types and objects
Fully compatible with relationaldatabase
Support of multimedia and large objects
High-quality database server features
8/8/2019 Instructor Guide for Introduction
16/174
.....................................................................................................................................................16 Oracle Education Products
.....................................................................................................................................................
Additional Reference
http://www.cyberdyne-object-
sys.com/oofaq2/
Data Models
Model ofsystem
in clientsmind
Entity model ofclients model
Table modelof entity model
Tables on disk
Server
8/8/2019 Instructor Guide for Introduction
17/174
.....................................................................................................................................................Oracle Education Products 17
.....................................................................................................................................................Introduction
Additional Information
If time permits, share this information
with the class. PL/SQL is the procedural
extension to SQL, provided by Oracle.
Through PL/SQL, the data manipulationcapabilities of SQL are combined with the
processing capabilities of a procedural
language. PL/SQL provides features like
conditional execution, looping, and
branching. PL/SQL supports subroutines
too. The basic unit in any PL/SQL
program is a block, which can occur
sequentially (one after the other) or nested
(one inside the other). Using PL/SQL you
can write subprograms, procedures,
packages, and functions that are stored in
the database.
Hint
One of the ways of introducing PL/SQL to the class is by explaining the capabilities that
SQL lacks and how PL/SQL serves as an extension to SQL. The objective of this slide is to
highlight that PL/SQL combines the data manipulating power of SQL with the data
processing power of procedural languages.
The Problem: SQL is the most powerful and comprehensive database language, that enables
you to create, organize, retrieve and maintain data stored in a database. But it does not
provide the features which a typical programming language offers, such as control-of-flow
constructs (sequence, selection and iteration constructs), or the facility to define and use
variables. SQL has a more set based approach. It returns a set of rows after a query is
executed.
The Solution: The solution is PL/SQL, which is a language that has the programming
features that SQL lacks. It provides control-of-flow constructs and lets you declare and use
variables. PL/SQL gives the flexibility of row-wise access to the records in the underlying
table.
Additional Reference
http://st-doc.us.oracle.com/8.0/815/server.815/a67842/
01_oview.htm#651
About PL/SQL
PL/SQL is an extension to SQL with
design features of programminglanguages.
Data manipulation and query statementsof SQL are included within proceduralunits of code.
8/8/2019 Instructor Guide for Introduction
18/174
.....................................................................................................................................................18 Oracle Education Products
.....................................................................................................................................................
Hint
Draw attention to the fact that PL/SQL can
reside in two environments:
The Oracle Server Oracle Tools
Explain the diagram on the slide as
follows: The diagram shows the PL/SQL
engine processing an anonymous block.
The engine executes procedural
statements but sends SQL statements to
the SQL statement executor in the Oracle
server.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67842/
01_oview.htm#962
PL/SQL Environment
PL/SQLblock
PL/SQL engine
Oracle Server
ProceduralStatementExecutor
PL/SQL
SQL
SQL Statement Executor
PL/SQLblock
8/8/2019 Instructor Guide for Introduction
19/174
.....................................................................................................................................................Oracle Education Products 19
.....................................................................................................................................................Lesson 1: Writing Basic Select Statements
Lesson 1: Writing Basic Select Statements
Additional Information
Explain that selection retrieves only
selected rows, projection retrieves only
selected columns and joins can retrieve
rows, columns, or both depending on the
SELECT clause.
Hint
If time permits, you can include the
explanation of other relational operators
like PRODUCT, INTERSECTION, and
DIFFERENCE.
PRODUCT: the result of a query that
concatenates rows from two sets of data.
All rows in the first set are concatenatedwith all rows in the second set, often
producing a very large new set.
INTERSECTION: displays all rows that
appear in both of two relations.
DIFFERENCE: displays rows that appear
in one relation only. (SQL uses operator
minus.)
Hint
Explain that all clauses mentioned within
[ ] are optional. Also mention that other
clauses like GROUP BY and ORDER BYare also part of a SELECT statement and
will be explained in the later lessons.
Capabilities of SQL SELECTStatements
Selection Projection
Table 1 Table 2
Table 1 Table 1Join
Basic SELECT Statement
SELECT [DISTINCT] {*, column [alias],...}
FROM table;
SELECT [DISTINCT] {*, column [alias],...}
FROM table;
SELECT identifies whatcolumns.
FROM identifies whichtable.
8/8/2019 Instructor Guide for Introduction
20/174
.....................................................................................................................................................20 Oracle Education Products
.....................................................................................................................................................
Hint
Point out that using tabs and indents, and
placing different clauses on separate lines
I increases readability of the SQL
statement.
Hint
Revisit slide 4 here. Explain SELECT and
FROM as keywords here.
Highlight that this is not a projection as allcolumns are being selected.
Hint
Highlight that this is a projection as only
the selected columns are being displayed.Also all rows are selected.
Basic SELECT Statement
SELECT [DISTINCT] {*, column [alias],...}
FROM table;
SELECT [DISTINCT] {*, column [alias],...}
FROM table;
SELECT identifies whatcolumns.
FROM identifies whichtable.
Selecting All Columns
DEPTNO DNAME LOC
--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
SQL> SELECT *
2 FROM dept;
Selecting Specific Columns
DEPTNO LOC
--------- -------------
10 NEW YORK
20 DALLAS
30 CHICAGO
40 BOSTON
SQL> SELECT deptno, loc
2 FROM dept;
8/8/2019 Instructor Guide for Introduction
21/174
.....................................................................................................................................................Oracle Education Products 21
.....................................................................................................................................................Lesson 1: Writing Basic Select Statements
Hint
Highlight that the case of the columns
specified in the SELECT list does not
influence the case of the headings in the
results set. Mention that these headingscan be customized and will be covered in
the subsequent slides.
Hint
The explanation can include that
sometimes there is a requirement to
perform certain calculations with the datafrom the tables. Highlight that these
calculated values can be displayed on the
screen or used to update the data in the
underlying tables. Mention that arithmetic
operators cannot be used in the FROM
clause.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
operator.htm#997746
Hint
Explain that an expression is a
combination of one or more values,
operators, and functions that evaluate to a
value. Highlight that SQL*PLUS ignores
blank spaces before and after the
arithmetic operators.
Column Heading Defaults
Default justification
Left: Date and character data
Right: Numeric data
Default display: Uppercase
Arithmetic Expressions
Create expressions on NUMBER and DATEdata by using arithmetic operators.
Operator
+
-
*
/
Description
Add
Subtract
Multiply
Divide
Using Arithmetic Operators
SQL> SELECT ename, sal, sal+300
2 FROM emp;
ENAME SAL SAL+300
---------- --------- ---------
KING 5000 5300
BLAKE 2850 3150
CLARK 2450 2750
JONES 2975 3275
MARTIN 1250 1550
ALLEN 1600 1900
...
14 rows selected.
8/8/2019 Instructor Guide for Introduction
22/174
.....................................................................................................................................................22 Oracle Education Products
.....................................................................................................................................................
Hint
Explain that if your arithmetic expression
contains more than one operator, the
priority is *, / first then +, -. (left to right if
there are several operators with the samepriority).
Hint
Mention that only one kind of parenthesis
( ) is accepted as part of SQL*Plus syntax.
Additional Example
Explain the difference between in the
output of these two SELECT statements:
SELECT ename, sal + 250 * 12
FROM emp;
SELECT ename, (sal + 250) *
12
FROM emp;
Hint
Mention that no two NULLS compare as
equal. Demonstrate the structure of the
EMP table and highlight that the EMPNO
has been defined as NOT NULL, so no
NULLs will be accepted. Explain that this
will be addressed in detail in the later
lessons.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
ch2.htm#4008
Operator Precedence
Multiplication and division take priorityover addition and subtraction.
Operators of the same priority areevaluated from left to right.
Parentheses are used to forceprioritized evaluation and to clarifystatements.
* / +_
Using Parentheses
SQL> SELECT ename, sal, 12*(sal+100)
2 FROM emp;
ENAME SAL 12*(SAL+100)
---------- --------- -----------
KING 5000 61200
BLAKE 2850 35400
CLARK 2450 30600
JONES 2975 36900
MARTIN 1250 16200
...
14 rows selected.
Defining a Null Value
A null is a value that is unavailable,unassigned, unknown, or inapplicable.
A null is not the same as zero or a blankspace.
SQL> SELECT ename, job, comm
2 FROM emp;
ENAME JOB COMM
---------- --------- ---------
KING PRESIDENT
BLAKE MANAGER
...
TURNER SALESMAN 0
...
14 rows selected.
8/8/2019 Instructor Guide for Introduction
23/174
.....................................................................................................................................................Oracle Education Products 23
.....................................................................................................................................................Lesson 1: Writing Basic Select Statements
Hint
Highlight that including a NULL column
value in an arithmetic expression will give
wrong results, though SQL*PLUS will not
report any error. We might be fooled bythe erroneous results.
Additional Reference
Oracle SQL Reference Manual, Release 8,
Elements of SQL
Hint
Explain that column aliases produce more
readable and meaningful output. You can
have descriptive column aliases. You canset the case of the column alias to lower
case, mixed case, or upper case. Highlight
that you cannot use column aliases in a
WHERE clause and that a column alias
does not change the actual name of the
column. Mention that column aliases can
be generated using both AS and by using
double quotes.
Hint
Explain the use of the double quotes and
that you must use them if the column aliascontains a space.
Null Valuesin Arithmetic Expressions
Arithmetic expressions containing a null
value evaluate to null.
SQL> select ename, 12*sal+comm
2 from emp
3 WHERE ename=KING;
ENAME 12*SAL+COMM
---------- -----------
KING
Defining a Column Alias
Renames a column heading Is useful with calculations
Immediately follows column name;optional AS keyword between columnname and alias
Requires double quotation marks if itcontains spaces or special charactersor is case sensitive
Using Column Aliases
SQL> SELECT ename AS name, sal salary2 FROM emp;
NAME SALARY
------------- ---------
...
SQL> SELECT ename "Name",
2 sal*12 "Annual Salary"
3 FROM emp;
Name Annual Salary
------------- -------------
...
8/8/2019 Instructor Guide for Introduction
24/174
.....................................................................................................................................................24 Oracle Education Products
.....................................................................................................................................................
Hint
Highlight that the resulting value is a
character value. Ask the participants to
note that the symbol for the concatenation
operator is ||.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
operator.htm#997790
Additional Example
SELECT
substr(ename,1,1)||empno
Email IDFROM emp;
The result set will now contain the first
character of the employees name
concatenated with his employee number.
For example, the e-mail ID for King will
be K7839. Explain the SUBSTR function
in brief.
Hint
Highlight that the literal is a part of every
row of the results set. Literal characterstrings can be used to generate reports.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
ch2.htm#3305
Concatenation Operator
Concatenates columns or character
strings to other columns Is represented by two vertical bars (||)
Creates a resultant column that is acharacter expression
Using the ConcatenationOperator
SQL> SELECT ename||job AS "Employees"
2 FROM emp;
Employees
-------------------
KINGPRESIDENT
BLAKEMANAGER
CLARKMANAGER
JONESMANAGER
MARTINSALESMAN
ALLENSALESMAN
...
14 rows selected.
Literal Character Strings
A literal is a character, expression, ornumber included in the SELECT list.
Date and character literal values mustbe enclosed within single quotationmarks.
Each character string is output once foreach row returned.
8/8/2019 Instructor Guide for Introduction
25/174
.....................................................................................................................................................Oracle Education Products 25
.....................................................................................................................................................Lesson 1: Writing Basic Select Statements
Hint
Revisit the concatenation operator here.
Explain how a space can be a part of the
results set by enclosing a space between
two single quotes. Revisit column aliashere.
Hint
Alternatively to get a list of the unique
departments, they can select DEPTNO
from the DEPT table.
Additional Example
SELECT job
FROM emp;
Additional Example
SELECT DISTINCT(job)
FROM emp;
Using Literal Character Strings
Employee Details
-------------------------
KING is a PRESIDENT
BLAKE is a MANAGER
CLARK is a MANAGER
JONES is a MANAGER
MARTIN is a SALESMAN
...
14 rows selected.
SQL> SELECT ename || ||is a|| ||job
2 AS "Employee Details"
3 FROM emp;
Duplicate Rows
The default display of queries is all rows,
including duplicate rows.SQL> SELECT deptno
2 FROM emp;
SQL> SELECT deptno
2 FROM emp;
DEPTNO
---------
10
30
10
20
...
14 rows selected.
Eliminating Duplicate Rows
Eliminate duplicate rows by using theDISTINCT keyword in the SELECT clause.
SQL> SELECT DISTINCT deptno
2 FROM emp;
DEPTNO
---------
10
20
30
8/8/2019 Instructor Guide for Introduction
26/174
.....................................................................................................................................................26 Oracle Education Products
.....................................................................................................................................................
Hint
Give an overview of all the uses of the
SQL statements. Explain SQL as a
nonprocedural language. It does not
support procedural constructs like IF,LOOP, etc. Explain SQL*Plus commands
as being very useful to modify the
command in the buffer, without which we
would have to retype the entire command
again or use an editor.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
ch1.htm#216
HintFor SQL commands, demostrate:
How the lines are automatically
numbered as they are entered
How commands cannot be
abbreviated. Type a keyword,
abbreviated command, and demostrate
the error message
Both the termination characters ; and /
Some simple case functions like
upper() and lower()
How to rerun a command from thebuffer using RUN or /
For SQL*Plus commands, mention a few
commonly used commands like
A[PPEND], C[HANGE], and so on and
say they will be discussed in detail as you
proceed in the same lesson.
SQL and SQL*Plus Interaction
SQL*Plus
SQL StatementsBuffer
SQL Statements
Server
Query ResultsSQL*PlusCommands
Formatted Report
SQL Statements VersusSQL*Plus Commands
SQLstatements
SQL
A language
ANSI standard
Keyword cannot beabbreviated
Statements manipulatedata and tabledefinitions in thedatabase
SQL*Plus
An environment
Oracle proprietary
Keywords can beabbreviated
Commands do notallow manipulation ofvalues in the database
SQLbuffer
SQL*Pluscommands
SQL*Plusbuffer
8/8/2019 Instructor Guide for Introduction
27/174
.....................................................................................................................................................Oracle Education Products 27
.....................................................................................................................................................Lesson 1: Writing Basic Select Statements
Hint
Explain the main categories of the
SQL*Plus commands: environment,
format, file manipulation, execution, edit,
interaction, miscellaneous (as in notespages).
Hint
Explain the scott/tiger account.
Explain that the password is not case-
sensitive. Explain the host string. If thefacility permits, demostrate how to use
SQL*Net easy configure or Net8 (if you
are using Oracle8) to configure a database
alias name.
Hint
Explain that DESC will also work. Also
include that the DESC is mandatory andeven something like DESCRI would
work.
SQL Statements VersusSQL*Plus Commands
SQLstatements
SQL
A language
ANSI standard
Keyword cannot beabbreviated
Statements manipulatedata and tabledefinitions in thedatabase
SQL*Plus
An environment
Oracle proprietary
Keywords can beabbreviated
Commands do notallow manipulation ofvalues in the database
SQLbuffer
SQL*Pluscommands
SQL*Plusbuffer
Logging In to SQL*Plus
From Windows environment:
From command line:
sqlplus [username[/password
[@database]]]
Displaying Table Structure
Use the SQL*Plus DESCRIBE command todisplay the structure of a table.
DESC[RIBE] tablenameDESC[RIBE] tablename
8/8/2019 Instructor Guide for Introduction
28/174
.....................................................................................................................................................28 Oracle Education Products
.....................................................................................................................................................
Hint
Revisit NOT NULL. Review the datatypes
shown in brief.
Additional Referencehttp://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
ch2.htm#3463
Hint
Demostrate the commands on the slide.
Displaying Table Structure
SQL> DESCRIBE deptSQL> DESCRIBE dept
Name Null? Type
----------------- -------- ------------
DEPTNO NOT NULL NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
SQL*Plus Editing Commands
A[PPEND] text C[HANGE] / old/ new
C[HANGE] / text/
CL[EAR] BUFF[ER]
DEL
DEL n
DEL m n
8/8/2019 Instructor Guide for Introduction
29/174
.....................................................................................................................................................Oracle Education Products 29
.....................................................................................................................................................Lesson 1: Writing Basic Select Statements
Hint
Demostrate the commands on the slide.
Hint
Demostrate the commands on the slide.
SQL*Plus Editing Commands
I[NPUT]
I[NPUT] text
L[IST]
L[IST] n
L[IST] m n
R[UN]
n
ntext
0 text
SQL*Plus File Commands
SAVE filename GET filename
START filename
@ filename
EDIT filename
SPOOL filename
8/8/2019 Instructor Guide for Introduction
30/174
.....................................................................................................................................................30 Oracle Education Products
.....................................................................................................................................................
Lesson 2: Restricting and Sorting Data
Hint
Revisit selection. Mention that all
columns are retrieved unless explicitly
specified.
Hint
Explain that the WHERE clause should
start on a separate line to increase
readability. Explain that the WHERE
clause consists of the column name,
comparison operator, and condition.
Mention that there can be more than one
condition and this will be explained later
in the lesson.
5
Hint
Explain that the condition is case-
sensitive. Also explain that characters and
dates, when included as part of the
condition, should be enclosed within
single quotes.
Additional Example
WHERE job = Clerk
Demostrate a condition with clerk in
mixed/lower/title case and show that there
are no rows selected.
Limiting Rows Using a Selection
"retrieve allemployees
in department 10"
EMP
EMPNO ENAME JOB ... DEPTNO
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
...
EMP
EMPNO ENAME JOB ... DEPTNO
7839 KING PRESIDENT 107782 CLARK MANAGER 10
7934 MILLER CLERK 10
Limiting Rows Selected
Restrict the rows returned by using theWHERE clause.
The WHERE clause follows the FROMclause.
SELECT [DISTINCT] {*| column [alias], ...}
FROM table
[WHERE condition(s)];
Using the WHERE Clause
SQL> SELECT ename, job, deptno
2 FROM emp
3 WHERE job=CLERK;
ENAME JOB DEPTNO
---------- --------- ---------
JAMES CLERK 30
SMITH CLERK 20
ADAMS CLERK 20
MILLER CLERK 10
8/8/2019 Instructor Guide for Introduction
31/174
.....................................................................................................................................................Oracle Education Products 31
.....................................................................................................................................................Lesson 2: Restricting and Sorting Data
6
Hint
Explain that date formats are also
sensitive, and the default is DD-MON-
YY. Highlight that MON is not case-
sensitive. Explain that case sensitivity canbe overridden using UPPER and LOWER
functions, which will be covered in the
later lessons.
Hint
Explain that in a >= or = or SELECT ename, job, deptno
2 FROM emp
3 WHERE ename = JAMES;
SQL> SELECT ename, job, deptno
2 FROM emp
3 WHERE ename = JAMES;
Comparison Operators
Operator
=
>
>=
SELECT ename, sal
2 FROM emp
3 WHERE sal BETWEEN 1000 AND 1500;
Lowerlimit
Higherlimit
Use the BETWEEN operator to displayrows based on a range of values.
Using the IN Operator
Use the IN operator to test for values in a
list.
SQL> SELECT empno, ename, sal, mgr
2 FROM emp
3 WHERE mgr IN (7902, 7566, 7788);
EMPNO ENAME SAL MGR
--------- ---------- --------- ---------
7902 FORD 3000 7566
7369 SMITH 800 7902
7788 SCOTT 3000 7566
7876 ADAMS 1100 7788
8/8/2019 Instructor Guide for Introduction
33/174
.....................................................................................................................................................Oracle Education Products 33
.....................................................................................................................................................Lesson 2: Restricting and Sorting Data
Hint
Explain that it can be used with the
NUMBER, VARCHAR2, CHAR, and
DATE datatypes. You might want to draw
an analogy to the DOS ? and * wildcardsto help understanding.
Additional Example
SELECT *
FROM emp
WHERE hiredate
LIKE __-JAN%;
Hint
Demostrate the use of the ESCAPE
character.
Hint
Explain that it would be a good idea to use
the NVL function and check for a field forNULL values before including the field in
any calculations.
Using the LIKE Operator
Use the LIKE operator to performwildcard searches of valid search string
values. Search conditions can contain either
literal characters or numbers.
% denotes zero or many characters.
_ denotes one character.
SQL> SELECT ename
2 FROM emp
3 WHERE ename LIKE S%;
Using the LIKE Operator
You can combine pattern-matchingcharacters.
You can use the ESCAPE identifier tosearch for "%" or "_".
SQL> SELECT ename
2 FROM emp
3 WHERE ename LIKE _A%;
ENAME
----------
MARTIN
JAMES
WARD
Using the IS NULL Operator
Test for null values with the IS NULLoperator.
SQL> SELECT ename, mgr
2 FROM emp
3 WHERE mgr IS NULL;
ENAME MGR
---------- ---------
KING
8/8/2019 Instructor Guide for Introduction
34/174
.....................................................................................................................................................34 Oracle Education Products
.....................................................................................................................................................
Hint
Revisit case sensitivity and use of quotes.
Explain what happens if a NULL value is
encountered. Explain the truth table in the
notes pages.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
operator.htm#998054
Hint
Revisit case sensitivity and use of quotes.
Explain what happens if a NULL value is
encountered. Explain the truth table in thenotes pages.
Hint
Revisit case sensitivity, use of quotes
Explain what happens if a NULL value isencountered. Explain the truth table in the
notes pages.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
operator.htm#998054
Using the AND Operator
AND requires both conditions to be TRUE.
SQL> SELECT empno, ename, job, sal2 FROM emp
3 WHERE sal>=1100
4 AND job=CLERK;
EMPNO ENAME JOB SAL
--------- ---------- --------- ---------
7876 ADAMS CLERK 1100
7934 MILLER CLERK 1300
Using the OR Operator
OR requires either condition to be TRUE.SQL> SELECT empno, ename, job, sal
2 FROM emp
3 WHERE sal>=1100
4 OR job=CLERK;
EMPNO ENAME JOB SAL
--------- ---------- --------- ---------
7839 KING PRESIDENT 5000
7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7566 JONES MANAGER 2975
7654 MARTIN SALESMAN 1250
...
7900 JAMES CLERK 950
...
14 rows selected.
Using the NOT Operator
SQL> SELECT ename, job
2 FROM emp
3 WHERE job NOT IN (CLERK,MANAGER,ANALYST);
ENAME JOB
---------- ---------
KING PRESIDENT
MARTIN SALESMAN
ALLEN SALESMAN
TURNER SALESMAN
WARD SALESMAN
8/8/2019 Instructor Guide for Introduction
35/174
.....................................................................................................................................................Oracle Education Products 35
.....................................................................................................................................................Lesson 2: Restricting and Sorting Data
Hint
Explain that usaging parenthesis increases
readability.
Additional Referencehttp://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
operator.htm#997667
Hint
Explain that usaging parenthesis increases
readability.
Hint
Explain that usaging parenthesis increases
readability.
Rules of Precedence
Override rules of precedence by usingparentheses.
Order Evaluated Operator
1 All comparisonoperators
2 NOT
3 AND
4 OR
Rules of Precedence
ENAME JOB SAL
---------- --------- ---------
KING PRESIDENT 5000
MARTIN SALESMAN 1250
ALLEN SALESMAN 1600
TURNER SALESMAN 1500
WARD SALESMAN 1250
ENAME JOB SAL
---------- --------- ---------
KING PRESIDENT 5000
MARTIN SALESMAN 1250
ALLEN SALESMAN 1600
TURNER SALESMAN 1500
WARD SALESMAN 1250
SQL> SELECT ename, job, sal
2 FROM emp3 WHERE job=SALESMAN
4 OR job=PRESIDENT
5 AND sal>1500;
Rules of Precedence
ENAME JOB SAL
---------- --------- ---------
KING PRESIDENT 5000
ALLEN SALESMAN 1600
ENAME JOB SAL
---------- --------- ---------
KING PRESIDENT 5000
ALLEN SALESMAN 1600
Use parentheses to force priority.
SQL> SELECT ename, job, sal
2 FROM emp
3 WHERE (job=SALESMAN
4 OR job=PRESIDENT)
5 AND sal>1500;
8/8/2019 Instructor Guide for Introduction
36/174
.....................................................................................................................................................36 Oracle Education Products
.....................................................................................................................................................
Hint
Explain that by default the results set is in
the same order as the order in which the
records where input into the table. ASC is
specified implicitly. You can order by acolumn alias. You can order by a column
that is not there in the SELECT list.
Hint
Explain the order of output for every
datatype: numbers, dates, character, and
null.
Hint
You might want to use the within-which.
For example, the results set is sorted byDEPTNO, within-which it is sorted by
SAL.
ORDER BY Clause Sort rows with the ORDER BY clause
ASC: ascending order, default
DESC: descending order
The ORDER BY clause comes last in theSELECT statement.
SQL> SELECT ename, job, deptno, hiredate
2 FROM emp
3 ORDER BY hiredate;
ENAME JOB DEPTNO HIREDATE
---------- --------- --------- ---------
SMITH CLERK 20 17-DEC-80
ALLEN SALESMAN 30 20-FEB-81
...
14 rows selected.
Sorting in Descending Order
SQL> SELECT ename, job, deptno, hiredate
2 FROM emp3 ORDER BY hiredate DESC;
ENAME JOB DEPTNO HIREDATE
---------- --------- --------- ---------
ADAMS CLERK 20 12-JAN-83
SCOTT ANALYST 20 09-DEC-82
MILLER CLERK 10 23-JAN-82
JAMES CLERK 30 03-DEC-81
FORD ANALYST 20 03-DEC-81
KING PRESIDENT 10 17-NOV-81
MARTIN SALESMAN 30 28-SEP-81
...
14 rows selected.
Sorting by Multiple Columns
The order of ORDER BY list is the order ofsort.
You can sort by a column that is not in theSELECT list.
SQL> SELECT ename, deptno, sal
2 FROM emp
3 ORDER BY deptno, sal DESC;
ENAME DEPTNO SAL
---------- --------- ---------
KING 10 5000
CLARK 10 2450
MILLER 10 1300
FORD 20 3000
...
14 rows selected.
8/8/2019 Instructor Guide for Introduction
37/174
.....................................................................................................................................................Oracle Education Products 37
.....................................................................................................................................................Lesson 3: Single-Row Functions
Lesson 3: Single-Row Functions
Hint
Explain that a function is a built-in
formula that can accept one or more
arguments and returns one value as a
result.
4
Additional Reference
Oracle Server SQL Reference, Release 8,
for the complete list of available functions
and syntax.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
function.htm#1028572
SQL Functions
FunctionInput
arg 1
arg 2
arg n
Functionperforms action
Output
Resultvalue
Two Types of SQL Functions
Functions
Single-rowfunctions
Multiple-rowfunctions
Single-Row Functions
Manipulate data items
Accept arguments and return one value
Act on each row returned
Return one result per row
May modify the datatype
Can be nested
function_name(column|expression, [arg1, arg2,...])function_name(column|expression, [arg1, arg2,...])
8/8/2019 Instructor Guide for Introduction
38/174
.....................................................................................................................................................38 Oracle Education Products
.....................................................................................................................................................
Hint
Explain the input that each of these
functions accept and the output (datatype)
that they return
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
function.htm#1028572
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/function.htm#1028572
Single-Row Functions
Conversion
Character
Number
Date
GeneralSingle-rowfunctions
Character Functions
Character
functions
LOWER
UPPER
INITCAP
CONCAT
SUBSTR
LENGTH
INSTR
LPAD
Case conversionfunctions
Character manipulationfunctions
Function Result
Case Conversion Functions
Convert case for character strings
LOWER(SQL Course)
UPPER(SQL Course)
INITCAP(SQL Course)
sql course
SQL COURSE
Sql Course
8/8/2019 Instructor Guide for Introduction
39/174
.....................................................................................................................................................Oracle Education Products 39
.....................................................................................................................................................Lesson 3: Single-Row Functions
Hint
Explain the RPAD function, as this
function will be needed in a practice. Also,
LTRIM and RTRIM are replaced by one
function TRIM, in Oracle8i.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
function.htm#1028572
Hint
Explain the syntax of the ROUND
function.
ROUND(n, [,m])
The ROUND function returns n rounded
to m places right of the decimal point; ifm
is omitted, to 0 places. m can be negative
to round off digits left of the decimal
point. m must be an integer.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
function.htm#1028572
HintExplain the syntax of the TRUNC
function.
TRUNC(n, [,m])
The TRUNC function returns n truncated
to m decimal places; ifm is omitted, to 0
places. m can be negative to truncate
(make zero) m digits left of the decimal
point.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
function.htm#1028572
CONCAT(Good, String)
SUBSTR(String,1,3)
LENGTH(String)
INSTR(String, r)
LPAD(sal,10,*)
GoodString
Str
6
3
******5000
Function Result
Character Manipulation Functions
Manipulate character strings
Using the ROUND Function
SQL> SELECT ROUND(45.923,2), ROUND(45.923,0),
2 ROUND(45.923,-1)
3 FROM DUAL;
ROUND(45.923,2) ROUND(45.923,0) ROUND(45.923,-1)
--------------- -------------- -----------------45.92 46 50
SQL> SELECT TRUNC(45.923,2), TRUNC(45.923),
2 TRUNC(45.923,-1)
3 FROM DUAL;
TRUNC(45.923,2) TRUNC(45.923) TRUNC(45.923,-1)--------------- ------------- ---------------
45.92 45 40
Using the TRUNC Function
8/8/2019 Instructor Guide for Introduction
40/174
.....................................................................................................................................................40 Oracle Education Products
.....................................................................................................................................................
Hint
Explain the syntax of the MOD function
MOD(n, m)
The MOD function returns the reminder of
m divided by n. Returns m ifn is 0.
Additional Example
SELECT MOD(11,4) Modulus
FROM DUAL;
Modulus
-----------
3
Hint
If you specify a date value without a timecomponent, the default time is 12:00:00
AM (midnight). If you specify a time
value without a date, the default date is the
first day of the current month.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
ch2.htm#3463
Additional ExampleSELECT ename,
ROUND((SYSDATE-HIREDATE)/
365,1) YEARS
FROM emp;
The above example returns the name and
the number of years of service for all
employees rounded to the first decimal
place.
Using the MOD Function
Calculate the remainder of the ratio ofsalary to commission for all employees
whose job title is salesman.
SQL> SELECT ename, sal, comm, MOD(sal, comm)
2 FROM emp
3 WHERE job = SALESMAN;
ENAME SAL COMM MOD(SAL,COMM)---------- --------- --------- -------------
MARTIN 1250 1400 1250 ALLEN 1600 300 100TURNER 1500 0 1500
WARD 1250 500 250
Working with Dates
Oracle stores dates in an internalnumeric format: century, year, month,day, hours, minutes, seconds.
The default date format is DD-MON-YY.
SYSDATE is a function returning dateand time.
DUAL is a dummy table used to viewSYSDATE.
Using Arithmetic Operatorswith Dates
SQL> SELECT ename, (SYSDATE-hiredate)/7 WEEKS
2 FROM emp
3 WHERE deptno = 10;
ENAME WEEKS---------- ---------KING 830.93709CLARK 853.93709
MILLER 821.36566
8/8/2019 Instructor Guide for Introduction
41/174
.....................................................................................................................................................Oracle Education Products 41
.....................................................................................................................................................Lesson 3: Single-Row Functions
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
function.htm#1028572
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
function.htm#1028572
Hint
Explain that if you call a SQL function
with an argument of a datatype other thanthe datatype expected by the SQL
function, Oracle implicitly converts the
argument to the expected datatype before
performing the SQL function.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
ch2.htm#21067
Date Functions
Number of monthsbetween two dates
MONTHS_BETWEEN
ADD_MONTHS
NEXT_DAY
LAST_DAY
ROUND
TRUNC
Add calendar months todate
Next day of the datespecified
Last day of the month
Round date
Truncate date
Function Description
MONTHS_BETWEEN ('01-SEP-95','11-JAN-94')
Using Date Functions
ADD_MONTHS ('11-JAN-94',6)
NEXT_DAY ('01-SEP-95','FRIDAY')
LAST_DAY('01-SEP-95')
19.6774194
'11-JUL-94'
'08-SEP-95'
'30-SEP-95'
Conversion Functions
Implicit datatypeconversion
Explicit datatypeconversion
Datatypeconversion
8/8/2019 Instructor Guide for Introduction
42/174
.....................................................................................................................................................42 Oracle Education Products
.....................................................................................................................................................
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
ch2.htm#21067
Hint
Explain that you can use date format
models in a TO_CHAR function to do the
following: In the TO_CHAR function to translate
a DATE value that is in a format other
than the default date format
In the TO_DATE function to translate
a character value that is in a format
other than the default date format
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
ch2.htm#35921
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
function.htm#1026046
Explicit Datatype Conversion
NUMBER CHARACTER
TO_CHAR
TO_NUMBER
DATE
TO_CHAR
TO_DATE
TO_CHAR Function with Dates
The format model:
Must be enclosed in single quotation marksand is case sensitive
Can include any valid date format element
Has an fmelement to remove paddedblanks or suppress leading zeros
Is separated from the date value by acomma
TO_CHAR(date, fmt)TO_CHAR(date, fmt)
Using TO_CHAR Functionwith Numbers
SQL> SELECT TO_CHAR(sal,$99,999) SALARY
2 FROM emp
3 WHERE ename = SCOTT;
SALARY--------
$3,000
8/8/2019 Instructor Guide for Introduction
43/174
.....................................................................................................................................................Oracle Education Products 43
.....................................................................................................................................................Lesson 3: Single-Row Functions
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
function.htm#1026230
Additional Information
If time permits, share the following
information in the class. The RR date
format element is similar to the YY dateformat element, but it provides additional
flexibility for storing date values in other
centuries. The RR date format element
allows you to store 21st century dates in
the 20th century by specifying only the
last two digits of the year. It will also
allow you to store 20th century dates in
the 21st century in the same way if
necessary.
If you use the TO_DATE function with
the YY date format element, the date
value returned is always in the current
century. If you use the RR date format
element instead, the century of the return
value varies according to the specified
two-digit year and the last two digits of the
current year
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
ch2.htm#21067
TO_NUMBER and TO_DATEFunctions
Convert a character string to a number
format using the TO_NUMBER function
TO_NUMBER(char[, fmt])
Convert a character string to a dateformat using the TO_DATE function
TO_DATE(char[, fmt])TO_DATE(char[, fmt])
TO_NUMBER and TO_DATEFunctions
Convert a character string to a numberformat using the TO_NUMBER function
TO_NUMBER(char[, fmt])
Convert a character string to a dateformat using the TO_DATE function
TO_DATE(char[, fmt])TO_DATE(char[, fmt])
8/8/2019 Instructor Guide for Introduction
44/174
.....................................................................................................................................................44 Oracle Education Products
.....................................................................................................................................................
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
function.htm#1026778
NVL Function
Converts null to an actual value
Datatypes that can be used are date,character, and number.
Datatypes must match
NVL(comm,0)
NVL(hiredate,01-JAN-97)
NVL(job,No Job Yet)
8/8/2019 Instructor Guide for Introduction
45/174
.....................................................................................................................................................Oracle Education Products 45
.....................................................................................................................................................Lesson 3: Single-Row Functions
Additional Example
SELECT ename,
NVL(TO_CHAR(COMM),NOT
APPLICABLE)"COMMISSION"
FROM emp
WHERE deptno = 30;
ENAME COMMISSION
-------- ----------------
ALLEN 300
WARD 500
MARTIN 1400
BLAKE NOT APPLICABLE
TURNER 0
JAMES NOT APPLICABLE
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
function.htm#1026778
Hint
Explain that in a DECODE expression,
Oracle considers two nulls to be
equivalent. The maximum number of
components in the DECODE expression,
including expr, searches, results, and
default is 255.
Additional Reference:
SQL Language Reference Manual,
pp. 3 to 62
SQL> SELECT ename, sal, comm, (sal*12)+NVL(comm,0)
2 FROM emp;
Using the NVL Function
ENAME SAL COMM (SAL*12)+NVL(COMM,0)---------- --------- --------- --------------------
KING 5000 60000BLAKE 2850 34200CLARK 2450 29400JONES 2975 35700
MARTIN 1250 1400 16400 ALLEN 1600 300 19500...14 rows selected.
DECODE Function
Facilitates conditional inquiries by doingthe work of a CASE or IF-THEN-ELSEstatement
DECODE(col/expression, search1, result1
[, search2, result2,...,]
[, default])
8/8/2019 Instructor Guide for Introduction
46/174
.....................................................................................................................................................46 Oracle Education Products
.....................................................................................................................................................
Lesson 4: Displaying Data from Multiple Tables
Additional Information
If time permits, share the following
information in class. JOINS make it
possible to select data from more than one
table by means of a single statement.
The joining of tables is done in SQL by
specifying the tables to be joined in the
FROM clause of the SELECT statement.
When you join two tables a Cartesian
product is formed. The conditions for
selecting rows from the product are
determined by the predicates in the where
clause. All the subsequent WHERE,
GROUP BY, HAVING, and ORDER BY
clauses work on this product.
Additional Example
To get the details of all departments with
number of employees assigned to it (even
0 employees)
What Is a Join?
Use a join to query data from more thanone table.
Write the join condition in the WHEREclause.
Prefix the column name with the tablename when the same column nameappears in more than one table.
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2;
Outer Joins
EMP DEPT
No employee in theOPERATIONS department
ENAME DEPTNO----- ------
KING 10BLAKE 30
CLARK 10
JONES 20
...
DEPTNO DNAME
------ ----------
10 ACCOUNTING30 SALES
10 ACCOUNTING20 RESEARCH
...40 OPERATIONS
8/8/2019 Instructor Guide for Introduction
47/174
.....................................................................................................................................................Oracle Education Products 47
.....................................................................................................................................................Lesson 4: Displaying Data from Multiple Tables
SELECT d.deptno,d.dname,d.loc, count(empno) No of Employees
FROM d.dept, emp
WHERE emp.deptno(+) = d.deptno
GROUP BY d.deptno, d.dname,d.loc;
DEPTNO DNAME LOC No of Employees
------- ---------------- ---------- ---------------
10 ACCOUNTING NEW YORK 3
20 RESEARCH DALLAS 5
30 SALES CHICAGO 6
40 OPERATIONS BOSTON 0
Hint
Explain that if the same table is used more
than once in a FROM clause then to
remove conflicts and ambiguities table
aliases are used. They are also called asco-relation names or range variables.
Once aliases are used, table names cannot
be used in further clauses.
Self Joins
EMP (WORKER) EMP (MANAGER)
MGR in the WORKER table is equal to EMPNO in theMANAGER table
EMPNO ENAME MGR----- ------ ----
7839 KING
7698 BLAKE 78397782 CLARK 7839
7566 JONES 7839
7654 MARTIN 76987499 ALLEN 7698
EMPNO ENAME----- --------
7839 KING7839 KING
7839 KING
7698 BLAKE7698 BLAKE
8/8/2019 Instructor Guide for Introduction
48/174
.....................................................................................................................................................48 Oracle Education Products
.....................................................................................................................................................
Lesson 5: Aggregating Data Using Group Functions
Hint
Explain that aggregate functions return a
single row based on groups of rows, rather
than on single rows.
Additional Reference
http://st-doc.us.oracle.com/
8.0/815/server.815/a67779/
function.htm#1028572
Hint
Highlight that all aggregate functions
except COUNT(*) and GROUPING
ignore nulls. You can use the NVL in the
argument to an aggregate function to
substitute a value for a null. If a query
with an aggregate function returns no rows
or only rows with nulls for the argument to
the aggregate function, the aggregate
function returns null.
What Are Group Functions?Group functions operate on sets of rows to give
one result per group.EMP
maximumsalary in
the EMP table
DEPTNO SAL--------- ---------
10 245010 500010 1300
20 80020 110020 300020 300020 297530 160030 285030 125030 95030 150030 1250
MAX(SAL)
---------
5000
Types of Group Functions
AVG
COUNT
MAX
MIN
STDDEV
SUM
VARIANCE
Group Functions and Null Values
Group functions ignore null values in thecolumn.
SQL> SELECT AVG(comm)
2 FROM emp;
AVG(COMM)
---------
550
8/8/2019 Instructor Guide for Introduction
49/174
.....................................................................................................................................................Oracle Education Products 49
.....................................................................................................................................................Lesson 5: Aggregating Data Using Group Functions
Hint
Highlight that all aggregate functions
except COUNT(*) and GROUPING
ignore nulls. You can use the NVL in the
argument to an aggregate function tosubstitute a value for a null. If a query
with an aggregate function returns no rows
or only rows with nulls for the argument to
the aggregate function, the aggregate
function returns null.
Additional Information
If time permits, include that all the
SELECT statements we have used until
now have acted on data as if it is in a
single group. But the rows of data in some
of the tables can be thought of as being
part of different groups. For example, the
EMP table contains employees who are
clerks, sales representative, etc. If we want
to find the minimum salary of each group
of employees, then none of the clauses
that we have seen until now are of any use.
The GROUP BY clause is used here.
When a GROUP BY clause is used, each
row of the resulting table will represent a
group having same values in the columns
used for grouping.
Creating Groups of Data
EMP
average
salaryin EMPtable
for eachdepartment
2916.6667
2175
1566.6667
DEPTNO SAL--------- ---------
10 245010 500010 130020 80020 110020 300020 300020 2975
30 160030 285030 1250
30 95030 150030 1250
DEPTNO AVG(SAL)
------- ---------
10 2916.6667
20 2175
30 1566.6667
8/8/2019 Instructor Guide for Introduction
50/174
.....................................................................................................................................................50 Oracle Education Products
.....................................................................................................................................................
Additional Example
SELECT job, max(sal)
FROM emp
GROUP BY job;
Hint
Highlight that the HAVING clause acts on
the resulting grouped table, from the
GROUP BY clause to remove the rowwhich does not satisfy the criteria in the
HAVIN