Académique Documents
Professionnel Documents
Culture Documents
Fundamentals I
Electronic Presentation
D17108GC20
Edition 2.0
May 2006
D46259
®
Authors Copyright © 2006, Oracle. All rights reserved.
Disclaimer
Chaitanya Koratamaddi
Nancy Greenberg This document contains proprietary information and is protected by copyright and
other intellectual property laws. You may copy and print this document solely for your
own use in an Oracle training course. The document may not be modified or altered in
Technical Contributors any way. Except where your use constitutes "fair use" under copyright law, you may
and Reviewers not use, share, download, upload, copy, print, display, perform, reproduce, publish,
Wayne Abbott license, post, transmit, or distribute this document in whole or in part without the
express authorization of Oracle.
Christian Bauwens
Claire Bennett The information contained in this document is subject to change without notice. If you
Perry Benson find any problems in the document, please report them in writing to: Oracle University,
Brian Boxx 500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
warranted to be error-free.
Zarko Cesljas
Dairy Chan Restricted Rights Notice
Laszlo Czinkoczki
If this documentation is delivered to the United States Government or anyone using
Joel Goodman the documentation on behalf of the United States Government, the following notice is
Matthew Gregory applicable:
Sushma Jagannath
U.S. GOVERNMENT RIGHTS
Angelika Krupp The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or
Isabelle Marchand disclose these training materials are restricted by the terms of the applicable Oracle
Malika Marghadi license agreement and/or the applicable U.S. Government contract.
Valli Pataballa Trademark Notice
Bryan Roberts
Helen Robertson Oracle, JD Edwards, and PeopleSoft, and Siebel are registered trademarks of Oracle
Corporation and/or its affiliates. Other names may be trademarks of their respective
Lata Shivaprasad owners.
John Soltani
Priya Vennapusa
Editors
Arijit Ghosh
Raj Kumar
Graphic Designer
Rajiv Chandrabhanu
Publisher
Veena Narasimhan
Introduction
One
Scalability
vendor
Unified
Reliability
management
Single
Common
development
skillsets
model
Object-relational data
Documents
Multimedia
Messages
Portals
Transactional applications
Business intelligence
Integration
Application Application
development server
framework
• Software provisioning
• Application service level monitoring
Clients
Development tools
Internet applications
System management
SQL
Business logic Presentation and
and data business logic
PL/SQL
Databases Application
servers Java
Network services
Strategy
and
analysis
Design
Build
and
document
Transition
Production
Electronic Database
spreadsheet Filing cabinet
… …
Model of
system
Entity model of
in client’s
client’s model
mind
Table model
of entity model Oracle
server
Tables on disk
EMPLOYEE DEPARTMENT
assigned to
#* number #* number
* name * name
o job title composed of o location
• Scenario
– “. . . Assign one or more employees to a
department . . .”
– “. . . Some departments do not yet have assigned
employees . . .”
Entity Attribute
• Singular, unique name • Singular name
• Uppercase • Lowercase
• Soft box • Mandatory marked with *
• Synonym in parentheses • Optional marked with “o”
EMPLOYEE DEPARTMENT
#* number assigned to
#* number
* name * name
o job title composed of o location
…
Primary key Foreign key Primary key
3 4
2
A relational database:
• Can be accessed and modified by executing
structured query language (SQL) statements
• Contains a collection of tables with no physical
pointers
• Uses a set of operators
Oracle
server
SELECT
INSERT
UPDATE Data manipulation language (DML)
DELETE
MERGE
CREATE
ALTER
DROP Data definition language (DDL)
RENAME
TRUNCATE
COMMENT
COMMIT
ROLLBACK Transaction control
SAVEPOINT
EMPLOYEES
DEPARTMENTS JOB_GRADES
Projection Selection
Table 1 Table 1
Join
Table 1 Table 2
SELECT *
FROM departments;
• iSQL*Plus:
– Default heading alignment: Center
– Default heading display: Uppercase
• SQL*Plus:
– Character and Date column headings are left-aligned
– Number column headings are right-aligned
– Default heading display: Uppercase
…
SELECT last_name, salary, 12*(salary+100)
FROM employees;
2
A column alias:
• Renames a column heading
• Is useful with calculations
• Immediately follows the column name (There can
also be the optional AS keyword between the
column name and alias.)
• Requires double quotation marks if it contains
spaces or special characters or if it is case
sensitive
A concatenation operator:
• Links columns or character strings to other
columns
• Is represented by two vertical bars (||)
• Creates a resultant column that is a character
expression
SELECT last_name||job_id AS "Employees"
FROM employees;
…
SELECT DISTINCT department_id
FROM employees; 2
SQL statements
Oracle
server
Internet
browser
Formatted report
Client
SQL iSQL*Plus
statements commands
1
6
2 3 4 5
DESC[RIBE] tablename
DESCRIBE employees
D:\TEMP\emp_data.sql
2
3
2
3
EMPLOYEES
“retrieve all
employees in
department 90”
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to
BETWEEN Between two values
...AND... (inclusive)
IN(set) Match any of a list of values
LIKE Match a character pattern
IS NULL Is a null value
SELECT first_name
FROM employees
WHERE first_name LIKE 'S%' ;
Operator Meaning
AND Returns TRUE if both component
conditions are true
OR Returns TRUE if either component
condition is true
NOT Returns TRUE if the following
condition is false
Operator Meaning
1 Arithmetic operators
2 Concatenation operator
3 Comparison conditions
4 IS [NOT] NULL, LIKE, [NOT] IN
5 [NOT] BETWEEN
6 Not equal to
7 NOT logical condition
8 AND logical condition
9 OR logical condition
... salary = ? …
… department_id = ? …
... last_name = ? ...
I want
to query
different
values.
101
1
2
salary
last_name
UNDEFINE employee_num
SET VERIFY ON
SELECT employee_id, last_name, salary, department_id
FROM employees
WHERE employee_id = &employee_num;
Input Output
Function
arg n
Functions
Single-row Multiple-row
functions functions
Single-row functions:
• Manipulate data items
• Accept arguments and return one value
• Act on each row that is returned
• Return one result per row
• May modify the data type
• Can be nested
• Accept arguments that can be a column or an
expression
Character
Single-row
General Number
functions
Conversion Date
Character
functions
Case-manipulation Character-manipulation
functions functions
LOWER CONCAT
UPPER SUBSTR
INITCAP LENGTH
INSTR
LPAD | RPAD
TRIM
REPLACE
1
SELECT employee_id, CONCAT(first_name, last_name) NAME,
job_id, LENGTH (last_name), 2
INSTR(last_name, 'a') "Contains 'a'?"
FROM employees 3
WHERE SUBSTR(job_id, 4) = 'REP';
1 2 3
1 2
SELECT ROUND(45.923,2), ROUND(45.923,0),
ROUND(45.923,-1) 3
FROM DUAL;
1 2 3
DUAL is a dummy table that you can use to view results
from functions and calculations.
1 2
SELECT TRUNC(45.923,2), TRUNC(45.923),
TRUNC(45.923,-1) 3
FROM DUAL;
1 2 3
Function Result
MONTHS_BETWEEN Number of months between two dates
ADD_MONTHS Add calendar months to date
NEXT_DAY Next day of the date specified
LAST_DAY Last day of the month
ROUND Round date
TRUNC Truncate date
Function Result
MONTHS_BETWEEN 19.6774194
('01-SEP-95','11-JAN-94')
ADD_MONTHS ('11-JAN-94',6) '11-JUL-94'
NEXT_DAY ('01-SEP-95','FRIDAY') '08-SEP-95'
LAST_DAY ('01-FEB-95') '28-FEB-95'
Data type
conversion
From To
VARCHAR2 or CHAR NUMBER
VARCHAR2 or CHAR DATE
NUMBER VARCHAR2
DATE VARCHAR2
From To
VARCHAR2 or CHAR NUMBER
VARCHAR2 or CHAR DATE
TO_NUMBER TO_DATE
TO_CHAR TO_CHAR
TO_NUMBER TO_DATE
TO_CHAR TO_CHAR
TO_CHAR(date, 'format_model')
Element Result
YYYY Full year in numbers
YEAR Year spelled out (in English)
MM Two-digit value for month
MONTH Full name of the month
MON Three-letter abbreviation of the month
DY Three-letter abbreviation of the day of the
week
DAY Full name of the day of the week
DD Numeric day of the month
SELECT last_name,
TO_CHAR(hire_date, 'fmDD Month YYYY')
AS HIREDATE
FROM employees;
TO_CHAR(number, 'format_model')
These are some of the format elements that you can use
with the TO_CHAR function to display a number value as a
character:
Element Result
9 Represents a number
0 Forces a zero to be displayed
$ Places a floating dollar sign
L Uses the floating local currency symbol
. Prints a decimal point
, Prints a comma as thousands indicator
TO_NUMBER(char[, 'format_model'])
0–49 50–99
If two digits The return date is in The return date is in
of the 0–49 the current century the century before
current the current one
year are: The return date is in The return date is in
50–99 the century after the current century
the current one
F3(F2(F1(col,arg1),arg2),arg3)
Step 1 = Result 1
Step 2 = Result 2
Step 3 = Result 3
SELECT last_name,
UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8), '_US'))
FROM employees
WHERE department_id = 60;
1 2
1 2
1
SELECT first_name, LENGTH(first_name) "expr1",
last_name, LENGTH(last_name) "expr2", 2
NULLIF(LENGTH(first_name), LENGTH(last_name)) result 3
FROM employees;
…
1 2 3
SELECT last_name,
COALESCE(manager_id,commission_pct, -1) comm
FROM employees
ORDER BY commission_pct;
Maximum salary in
EMPLOYEES table
• AVG
• COUNT
• MAX
Group
• MIN functions
• STDDEV
• SUM
• VARIANCE
You can use MIN and MAX for numeric, character, and date
data types.
SELECT MIN(hire_date), MAX(hire_date)
FROM employees;
EMPLOYEES
4400
9500
3500 Average
salary in
EMPLOYEES
6400 table for each
department
10033
EMPLOYEES
Add the
salaries in
the EMPLOYEES
table for
each job,
grouped by
department
…
EMPLOYEES
The maximum
salary
per department
when it is
greater than
$10,000
…
EMPLOYEES DEPARTMENTS
EMPLOYEES DEPARTMENTS
… …
Foreign key Primary key
… …
EMPLOYEES JOB_GRADES
DEPARTMENTS EMPLOYEES
Cartesian product:
20 x 8 = 160 rows
Main query:
Subquery:
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
• Single-row subquery
Main query
returns
Subquery ST_CLERK
• Multiple-row subquery
Main query
returns ST_CLERK
Subquery
SA_MAN
ERROR at line 4:
ORA-01427: single-row subquery returns more than
one row
no rows selected
Operator Meaning
IN Equal to any member in the list
ANY Compare value to each value returned by the
subquery
ALL Compare value to every value returned by
the subquery
SELECT emp.last_name
FROM employees emp
WHERE emp.employee_id NOT IN
(SELECT mgr.manager_id
FROM employees mgr);
no rows selected
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
UNION/UNION ALL
A B
INTERSECT
A B
MINUS
A B
…
…
A B
A B
A B
Using the UNION operator, display the employee ID, job ID,
and salary of all employees.
New
DEPARTMENTS row
1 row created.
4 rows created.
EMPLOYEES
UPDATE employees
SET job_id = (SELECT job_id
FROM employees
WHERE employee_id = 205),
salary = (SELECT salary
FROM employees
WHERE employee_id = 205)
WHERE employee_id = 114;
1 row updated.
DEPARTMENTS
• Example:
INSERT INTO
(SELECT employee_id, last_name,
email, hire_date, job_id, salary,
department_id
FROM employees
WHERE department_id = 50)
VALUES (99999, 'Taylor', 'DTAYLOR',
TO_DATE('07-JUN-99', 'DD-MON-RR'),
'ST_CLERK', 5000, 50);
1 row created.
Time COMMIT
Transaction
DELETE
SAVEPOINT A
INSERT
UPDATE
SAVEPOINT B
INSERT
ROLLBACK ROLLBACK ROLLBACK
to SAVEPOINT B to SAVEPOINT A
ROLLBACK;
Rollback complete.
COMMIT;
Commit complete.
User A
UPDATE employees Data
SET salary = 7000 blocks
WHERE last_name = 'Grant';
Undo
segments
Changed
SELECT * and
FROM userA.employees; Read- unchanged
consistent data
image Before
change
(“old” data)
User B
Function Description
INSERT Adds a new row to the table
UPDATE Modifies existing rows in the table
DELETE Removes existing rows from the table
COMMIT Makes all pending changes permanent
SAVEPOINT Is used to roll back to the savepoint marker
ROLLBACK Discards all pending data changes
Object Description
Table Basic unit of storage; composed of rows
View Logically represents subsets of data from
one or more tables
Sequence Generates numeric values
Index Improves the performance of some
queries
Synonym Gives alternative names to objects
• You specify:
– Table name
– Column name, column data type, and column size
USERA USERB
SELECT * SELECT *
FROM userB.employees; FROM userA.employees;
TIMESTAMP[(fractional_seconds_precision)]
WITH TIME ZONE
TIMESTAMP[(fractional_seconds_precision)]
WITH LOCAL TIME ZONE
• Syntax:
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint][,...]);
• Column-level constraint:
column [CONSTRAINT constraint_name] constraint_type,
• Table-level constraint:
column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),
• Column-level constraint:
CREATE TABLE employees(
employee_id NUMBER(6)
CONSTRAINT emp_emp_id_pk PRIMARY KEY, 1
first_name VARCHAR2(20),
...);
• Table-level constraint:
CREATE TABLE employees(
employee_id NUMBER(6),
first_name VARCHAR2(20),
...
job_id VARCHAR2(10) NOT NULL,
2
CONSTRAINT emp_emp_id_pk
PRIMARY KEY (EMPLOYEE_ID));
Ensures that null values are not permitted for the column:
UNIQUE constraint
EMPLOYEES
…
INSERT INTO
Allowed
Not allowed:
already exists
DEPARTMENTS
PRIMARY KEY
…
Not allowed INSERT INTO
(null value)
Not allowed
(50 already exists)
PRIMARY
KEY
…
EMPLOYEES
FOREIGN
KEY
… Not allowed
INSERT INTO (9 does not
exist)
Allowed
UPDATE employees
SET department_id = 55
WHERE department_id = 110;
UPDATE employees
*
ERROR at line 1:
ORA-02291: integrity constraint (HR.EMP_DEPT_FK)
violated - parent key not found
DESCRIBE dept80
Object Description
EMPLOYEES table
To provide To present
data different views of
independence the same data
DESCRIBE empvu80
SELECT *
FROM salvu50;
Object Description
A sequence:
• Can automatically generate unique numbers
• Is a sharable object
• Can be used to create a primary key value
• Replaces application code
• Speeds up the efficiency of accessing sequence
values when cached in memory
2 4 6 8 10
1 3 5 7 9
Object Description
An index:
• Is a schema object
• Can be used by the Oracle server to speed up the
retrieval of rows by using a pointer
• Can reduce disk I/O by using a rapid path access
method to locate data quickly
• Is independent of the table that it indexes
• Is used and maintained automatically by the Oracle
server
Object Description
• Drop a synonym:
DROP SYNONYM d_sum;
Synonym dropped.
Oracle server
Oracle server
Consists of:
– Base tables
– User-accessible views
SELECT *
FROM dictionary
WHERE table_name = 'USER_OBJECTS';
USER_OBJECTS:
• Query USER_OBJECTS to see all of the objects that
are owned by you
• Is a useful way to obtain a listing of all object
names and types in your schema, plus the
following information:
– Date created
– Date of last modification
– Status (valid or invalid)
ALL_OBJECTS:
• Query ALL_OBJECTS to see all objects to which you
have access
USER_TABLES:
DESCRIBE user_tables
SELECT table_name
FROM user_tables;
…
Copyright © 2006, Oracle. All rights reserved.
Column Information
USER_TAB_COLUMNS:
DESCRIBE user_tab_columns
…
Copyright © 2006, Oracle. All rights reserved.
Constraint Information
DESCRIBE user_cons_columns
…
Copyright © 2006, Oracle. All rights reserved.
View Information
1 DESCRIBE user_views
DESCRIBE user_sequences
DESCRIBE user_synonyms
SELECT *
FROM user_synonyms;
EMPLOYEES DEPARTMENTS
Cartesian product:
20 x 8 = 160 rows
EMPLOYEES DEPARTMENTS
… …
Foreign key Primary key
EMPLOYEES DEPARTMENTS
… …
…
To join n tables together, you need a minimum of n–1
join conditions. For example, to join three tables, a
minimum of two joins is required.
EMPLOYEES JOB_GRADES
DEPARTMENTS EMPLOYEES
…
There are no employees
in department 190.
• You use an outer join to see rows that do not meet the
join condition.
• The outer join operator is the plus sign (+).
… …
SQL statements
Server
SQL*Plus
Query results
Buffer
SQL
scripts
SQL SQL*Plus
• A language • An environment
• ANSI-standard • Oracle-proprietary
• Keywords cannot be • Keywords can be
abbreviated abbreviated
• Statements manipulate • Commands do not
data and table allow manipulation of
definitions in the values in the database
database
• Log in to SQL*Plus
• Describe the table structure
• Edit your SQL statement
• Execute SQL from SQL*Plus
• Save SQL statements to files and append SQL
statements to files
• Execute saved files
• Load commands from file to buffer to edit
DESC[RIBE] tablename
• A[PPEND] text
• C[HANGE] / old / new
• C[HANGE] / text /
• CL[EAR] BUFF[ER]
• DEL
• DEL n
• DEL m n
• I[NPUT]
• I[NPUT] text
• L[IST]
• L[IST] n
• L[IST] m n
• R[UN]
• n
• n text
• 0 text
SQL> LIST
1 SELECT last_name
2* FROM employees
SQL> 1
1* SELECT last_name
SQL> A , job_id
SQL> L
SQL> L
SQL> c/employees/departments
SQL> L
• SAVE filename
• GET filename
• START filename
• @ filename
• EDIT filename
• SPOOL filename
• EXIT
SQL> L
1 SELECT last_name, manager_id, department_id
2* FROM employees
SQL> SAVE my_query
• Developed in Java
• Supports Windows, Linux, and Mac OS X platforms
• Default connectivity by using the JDBC Thin driver
• Does not require an installer
• Connects to any Oracle Database version 9.2.0.1 and
later
• Bundled with JRE 1.5
Download the Oracle SQL Developer kit and unzip into any
directory on your machine.
2 4 6
1 3 5
2 4 6
1 8
5 7
3
Before
Formatting
After
Formatting
Inserting a
snippet
Editing the
snippet