...Lesson 1: Writing Basic Select StatementsLesson 1: Writing Basic Select Statements Additional Information Explain that selection retrieves only selected rows, projection retrieves onl
Trang 2Priya Nathan
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 find any 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.
Trang 3Introduction
Introduction 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 of your 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 here—and 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 yourself
This 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
Trang 4The 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 students—welcome 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
Thought for the Day
Never do for the learners what they can do for themselves
Trang 5The 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
Trang 6Lecture 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
it can be done through discussion in groups
The mind is like the stomach It’s 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
Trang 7Lecture 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 student’s question
– Reverse: Mirror a student’s 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 it—never 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 “That’s a good
question We will be covering that in a few minutes.”
Trang 8Eitlington, 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.
O’Connor, Joseph, and John Seymour Introducing Neuro-Linguistic
Programming Thorsons, 1995.
O’Connor, 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
Trang 9About 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 everyone—lecturer and students—at the start of every lesson
The topics covered in each lesson should give students enough information to complete the required part of each practice
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:
Trang 10seems, 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
information related to the subject of the slide
Trang 11Beginning with strategy and analysis, the project team’s 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 project team 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
Transition
Production
Trang 12(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 the product 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
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 model
for database systems in 1970.
• It is the basis for the relational database
management 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
Trang 13Additional 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
Definition of a Relational Database
A relational database is a collection of
relations 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 ENAME JOB DEPTNO
Trang 14Additional Reference
http://cis.csustan.edu/courses/ lodewyck/4720/ERModel/index.htm http://coba.usf.edu/trimmer/ Chap3/index.htm
http://www.musc.edu/hap/
Phoenix3/index.htm
• Create an entity relationship diagram from
business specifications or narratives
Trang 15Additional 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 The use 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
Process Iterative/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
sys.com/oofaq2/
http://www.cyberdyne-object-Oracle8: Object Relational
Database Management System
• User-defined data types and objects
• Fully compatible with relational
database
• Support of multimedia and large objects
• High-quality database server features
Trang 16Additional Reference
sys.com/oofaq2/
Trang 17Additional 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 manipulation capabilities 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
• Data manipulation and query statements
of SQL are included within procedural
units of code.
Trang 18statements 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 SQL
SQL Statement Executor PL/SQL
block
Trang 19Lesson 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 concatenated with all rows in the second set, often producing a very large new set
INTERSECTION: displays all rows thatappear in both of two relations
DIFFERENCE: displays rows that appear
in one relation only (SQL uses operatorminus.)
Hint
Explain that all clauses mentioned within [ ] are optional Also mention that other clauses like GROUP BY and ORDER BY are also part of a SELECT statement and will be explained in the later lessons
Basic SELECT Statement
SELECT [DISTINCT] {*, column [alias], }
FROM table;
SELECT [DISTINCT] {*, column [alias], }
FROM table;
• SELECT identifies what columns.
• FROM identifies which table.
Trang 20Basic SELECT Statement
SELECT [DISTINCT] {*, column [alias], }
FROM table;
SELECT [DISTINCT] {*, column [alias], }
FROM table;
• SELECT identifies what columns.
• FROM identifies which table.
Selecting All Columns
DEPTNO DNAME LOC
Trang 21Lesson 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 headings can 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 data from 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
• Default display: Uppercase
Arithmetic Expressions
Create expressions on NUMBER and DATE
data by using arithmetic operators.
Using Arithmetic Operators
SQL> SELECT ename, sal, sal+300
Trang 22Explain 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 same priority)
Additional Reference
Operator Precedence
• Multiplication and division take priority
over addition and subtraction.
• Operators of the same priority are
evaluated from left to right.
• Parentheses are used to force
prioritized evaluation and to clarify
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 blank
Trang 23Lesson 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 by the erroneous results
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 alias contains a space
Null Values
in Arithmetic Expressions
Arithmetic expressions containing a null
value evaluate to null.
SQL> select ename, 12*sal+comm
Defining a Column Alias
• Renames a column heading
• Is useful with calculations
• Immediately follows column name;
optional AS keyword between column
name and alias
• Requires double quotation marks if it
contains spaces or special characters
or is case sensitive
Using Column Aliases
SQL> SELECT ename AS name, sal salary
2 FROM emp;
NAME SALARY
-
SQL> SELECT ename "Name",
2 sal*12 "Annual Salary"
3 FROM emp;
Name Annual Salary
-
Trang 24Highlight 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 ID”
FROM emp;
The result set will now contain the first character of the employee’s 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 character strings 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 a
Literal Character Strings
• A literal is a character, expression, or
number included in the SELECT list.
• Date and character literal values must
be enclosed within single quotation
marks.
• Each character string is output once for
each row returned.
Trang 25Lesson 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 alias here
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
including duplicate rows.
Eliminating Duplicate Rows
Eliminate duplicate rows by using the
DISTINCT keyword in the SELECT clause.
SQL> SELECT DISTINCT deptno
Trang 26Give 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
Hint
For 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 the buffer 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
• Commands do not allow manipulation of values in the database
SQL buffer
SQL*Plus commands
SQL*Plus buffer
Trang 27Lesson 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 notes pages)
Hint
Explain the scott/tiger account Explain that the password is not case-sensitive Explain the host string If the facility 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 and even something like DESCRI would work
• Commands do not allow manipulation of values in the database
SQL buffer
SQL*Plus commands
SQL*Plus buffer
Logging In to SQL*Plus
• From Windows environment:
• From command line:
sqlplus [username[/password
[@database]]]
Displaying Table Structure
Use the SQL*Plus DESCRIBE command to
display the structure of a table.
DESC[RIBE] tablename
DESC[RIBE] tablename
Trang 28Hint
Demostrate the commands on the slide
Displaying Table Structure
Trang 29Lesson 1: Writing Basic Select Statements
Hint
Demostrate the commands on the slide
Hint
Demostrate the commands on the slide
SQL*Plus Editing Commands
Trang 30Lesson 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
case-Additional Example
WHERE job = ‘Clerk’
Demostrate a condition with “clerk” in
Limiting Rows Using a Selection
"…retrieve all employees
Limiting Rows Selected
• Restrict the rows returned by using the
Using the WHERE Clause
SQL> SELECT ename, job, deptno
Trang 31Lesson 2: Restricting and Sorting Data
Hint
Explain that in a >= or <= condition, the equal-to operator should appear after the less-than or greater-than operator
SQL*Plus ignores spaces between the operators Mention that != can also be used for not-equal-to
Hint
Explain that in a >= or <= condition, the equal-to operator should appear after the less-than or greater-than operator
SQL*Plus ignores spaces between the operators
Character Strings and Dates
• Character strings and date values are
enclosed in single quotation marks.
• Character values are case sensitive and
date values are format sensitive.
SQL> SELECT ename, job, deptno
2 FROM emp
3 WHERE ename = ’JAMES’;
SQL> SELECT ename, job, deptno
Less than or equal to Not equal to
Using the Comparison
Trang 32Additional Example
SELECT ename, sal FROM emp
WHERE job IN (‘CLERK’,’MANAGER’);
SELECT ename,sal FROM emp
WHERE job = ‘CLERK’
Use the BETWEEN operator to display
rows based on a range of values.
Using the IN Operator
Use the IN operator to test for values in a
Trang 33Lesson 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 * wildcards
to help understanding
Additional Example
SELECT * FROM emp WHERE hiredate LIKE ‘ -JAN%’;
Using the LIKE Operator
• Use the LIKE operator to perform
wildcard searches of valid search string
values.
• Search conditions can contain either
literal characters or numbers.
SQL> SELECT ename
2 FROM emp
3 WHERE ename LIKE ’S%’;
Using the LIKE Operator
• You can combine pattern-matching
Using the IS NULL Operator
Test for null values with the IS NULL
Trang 34Revisit 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 the notes pages
Hint
Revisit case sensitivity, 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
Using the AND Operator
AND requires both conditions to be TRUE.
SQL> SELECT empno, ename, job, sal
Using the OR Operator
OR requires either condition to be TRUE.
SQL> SELECT empno, ename, job, sal
Using the NOT Operator
SQL> SELECT ename, job
Trang 35Lesson 2: Restricting and Sorting Data
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;
Trang 36Explain 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 a column 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 by DEPTNO, within-which it is sorted by SAL
ORDER BY Clause
• Sort rows with the ORDER BY clause
• The ORDER BY clause comes last in the
Sorting in Descending Order
SQL> SELECT ename, job, deptno, hiredate
2 FROM emp
3 ORDER BY hiredate DESC;
ENAME JOB DEPTNO HIREDATE
-
-SCOTT ANALYST 20 09-DEC-82
MILLER CLERK 10 23-JAN-82
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 of
3 ORDER BY deptno, sal DESC;
ENAME DEPTNO SAL
Trang 37Lesson 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
Function Input
arg 1
arg 2
arg n
Function performs action
Output
Result value
Two Types of SQL Functions
Functions
Single-row
functions
Multiple-row functions
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, ])
Trang 38Explain 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/
Character Functions
Character functions
LOWER
UPPER
INITCAP
CONCAT SUBSTR LENGTH INSTR LPAD
Case conversion
functions
Character manipulation functions
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
Trang 39Lesson 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/
The ROUND function returns n rounded
to m places right of the decimal point; if m
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/
The TRUNC function returns n truncated
to m decimal places; if m is omitted, to 0 places m can be negative to truncate (make zero) m digits left of the decimal
******5000 Function Result
Character Manipulation Functions
Manipulate character strings
Using the ROUND Function
SQL> SELECT ROUND(45.923,2), ROUND(45.923,0),
Trang 40Additional Reference
http://st-doc.us.oracle.com/ 8.0/815/server.815/a67779/
ch2.htm#3463
Additional Example
SELECT 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 of
salary 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
TURNER 1500 0 1500
Working with Dates
• Oracle stores dates in an internal
numeric format: century, year, month,
day, hours, minutes, seconds.
• The default date format is DD-MON-YY.
• SYSDATE is a function returning date