Oracle9i SQL
-
Upload
kamal-joshi -
Category
Documents
-
view
241 -
download
0
Transcript of Oracle9i SQL
-
8/6/2019 Oracle9i SQL
1/312
Oracle 9i SQLBeing Presented By
PM KarthickCorporate Trainer Executive
-
8/6/2019 Oracle9i SQL
2/312
-
8/6/2019 Oracle9i SQL
3/312
Structure Query Language
Structured Query
Language (SQL) is the setof statements with which all
programs and users access
data in an Oracle database.
-
8/6/2019 Oracle9i SQL
4/312
-
8/6/2019 Oracle9i SQL
5/312
Introduction to ORACLE
-
8/6/2019 Oracle9i SQL
6/312
Objectives
What is RDBMS ?
Advantages of SQL and PLSQL
RDBMS Vs ORDBMS
Uses and benefits of PL/SQL
-
8/6/2019 Oracle9i SQL
7/312
Relational Database Definition
A relational database is a collection of relations ortwo-dimensional tables.
DatabaseDatabase
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Table Name:Table Name: DEPTDEPT
EMPNO ENAME JOB DEPTNO
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
Table Name:Table Name: EMPEMP
-
8/6/2019 Oracle9i SQL
8/312
Data Models
Entitymodel ofEntitymodel ofclients modelclients model
Tables on diskTables on disk
ServerServer
TablemodelTablemodelof entity modelof entity model
Model ofModel ofsystemsystem
in clientsin clientsmindmind
-
8/6/2019 Oracle9i SQL
9/312
Relating Multiple Tables
EACH AND EVERY ROW ISIDENTIFIEDBY A UNIQUE KEY CALLED PRIMARY KEY
EMPEMP DEPTDEPT
Primary keyPrimary key Primary keyPrimary key
LOGICAL RELATED ROWSSHARED the
PKEY as FOREIGN KEY.
Foreign keyForeign key
EMPNO ENAME JOB DEPTNO
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
-
8/6/2019 Oracle9i SQL
10/312
Relational DB Properties
A relational database
- SQL Statements to be used for
manipulating the database.- No Physical Pointers to access and store
relations between Tables.
-Set of Operators for Functionality
-
8/6/2019 Oracle9i SQL
11/312
RDBMS Using SQL
DatabaseDatabase
SQL> SELECT loc2 FROM dept;
SQL statementSQL statementis enteredis entered
Message is sentMessage is sentto the Clientto the Client
Query is sent toQuery is sent toDatabaseDatabase
LocationLocation--------------------------DallasDallasNew YorkNew YorkSanta ClaraSanta Clara
DeptDept
-
8/6/2019 Oracle9i SQL
12/312
RDBMS
User tablesUser tables DataDatadictionarydictionary
ServerServer
-
8/6/2019 Oracle9i SQL
13/312
ORACLE 9i An Overview
Objects : User Defined Typesvery much in line to C++ Classes.
Fully relational compatible
LOBS / Multimedia Files in Database !
Oracle Enterprise Manager
-
8/6/2019 Oracle9i SQL
14/312
Why use OOPs Methodology
SIMPLIFY To SOLVE.
Objects and Interactions
They replicate real time environment.
-
8/6/2019 Oracle9i SQL
15/312
-
8/6/2019 Oracle9i SQL
16/312
PlatformIndependency
Data files in the DiskData files in the Disk
OSOS
ORACLE SERVERORACLE SERVER
USER 1USER 1 USER 2USER 2 USER 4USER 4USER 3USER 3
OSmanages DataOSmanages Data
filesfiles
Server simply satisfiesServer simply satisfiesthe requestthe request
-
8/6/2019 Oracle9i SQL
17/312
SQL Statements
SELECT
INSERTUPDATEDELETEMERGE
CREATEALTERDROPRENAMETRUNCATE
Data retrievalData retrieval
Data Manipulation Language (DML)Data Manipulation Language (DML)
Data Definition Language (DDL)Data Definition Language (DDL)
-
8/6/2019 Oracle9i SQL
18/312
SQL Statements
Transaction Control Language (TCL)Transaction Control Language (TCL)
Data Control Language (DCL)Data Control Language (DCL)
COMMITCOMMIT
ROLLBACKROLLBACK
SAVEPOINTSAVEPOINT
GRANTGRANT
REVOKEREVOKE
-
8/6/2019 Oracle9i SQL
19/312
Objectives
SQL SELECT statements
A basic SELECT statement
SQL statements and SQL*Plus commands
-
8/6/2019 Oracle9i SQL
20/312
Basic SELECT Statement
SELECT [DISTINCT] {*, column [alias],...}FROM table;
Select Clause determines what columns
The From Clause determines which table.
-
8/6/2019 Oracle9i SQL
21/312
Writing SQL Statements
SQL is not Case Sensitive.Keywords cannot be split or abbreviated.SQL Statements can be split across lines.Clauses are placed in different lines, to
promote readability.
-
8/6/2019 Oracle9i SQL
22/312
-
8/6/2019 Oracle9i SQL
23/312
Selecting Specific Columns
DEPTNO LOC--------- -------------
10 NEW YORK20 DALLAS30 CHICAGO40 BOSTON
SQL> SELECT deptno, loc2 FROM departments;
-
8/6/2019 Oracle9i SQL
24/312
Default Column Headings
Default justification- Date and Character Data is Left Justified- Numeric Data is Right Justified
Display Headings in UPPERCASE. Character / Date Columns headings will be
Truncated. Numerical Columns headings are not truncated.
Column name can be replaced by the Alias name
-
8/6/2019 Oracle9i SQL
25/312
Arithmetic Expressions
Basic Arithmetic operators
Operator
+
-
*
/
Description
Add
Subtract
Multiply
Divide
-
8/6/2019 Oracle9i SQL
26/312
Using Arithmetic Operators
SQL> SELECT ename, sal, sal+3002 FROM employees;
ENAME SAL SAL+300
---------- --------- ---------KING 5000 5300BLAKE 2850 3150CLARK 2450 2750JONES 2975 3275 MARTIN 1250 1550
ALLEN 1600 1900...14 rows selected.
-
8/6/2019 Oracle9i SQL
27/312
Operator Precedence
Parentheses can force precedence
Multiplication and Division followed by
Addition and subtraction.
** // ++__
-
8/6/2019 Oracle9i SQL
28/312
Operator Precedence
SQL> SELECT ename, sal, 12*sal+1002 FROM employees;
ENAME SAL 12*SAL+100
---------- --------- ----------KING 5000 60100BLAKE 2850 34300CLARK 2450 29500JONES 2975 35800 MARTIN 1250 15100
ALLEN 1600 19300...14 rows selected.
-
8/6/2019 Oracle9i SQL
29/312
Using Parentheses
SQL> SELECT ename, sal, 12*(sal+100)2 FROM employees;
ENAME SAL 12*(SAL+100)
---------- --------- -----------KING 5000 61200BLAKE 2850 35400CLARK 2450 30600JONES 2975 36900 MARTIN 1250 16200
...14 rows selected.
-
8/6/2019 Oracle9i SQL
30/312
Defining a Null Value
NULL is UNASSIGNED Value.
SQL> SELECT ename, job, comm2 FROM emp;
ENAME JOB COMM---------- --------- ---------KING PRESIDENTBLAKE MANAGER
...TURNER SALESMAN 0
...14 rows selected.
-
8/6/2019 Oracle9i SQL
31/312
Null Values in Arithmetic Expr
NULL as an operand will result NULL
SQL> select ename NAME, 12*sal+comm2 from emp3 WHERE ename='KING';
NAME 12*SAL+COMM
---------- -----------KING
-
8/6/2019 Oracle9i SQL
32/312
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.
-
8/6/2019 Oracle9i SQL
33/312
Defining Column Alias
The Heading name is replaced for thecurrent SELECT Statement.
AS Keyword [ Optional ] between thecolumn name and the actual alias name
Double Quotation Marks.
-
8/6/2019 Oracle9i SQL
34/312
Using Column Aliases
SQL> SELECT ename AS name, sal salary2 FROM employees;
NAME SALARY
------------- ---------
...
SQL> SELECT ename "Name",2 sal*12 "Annual Salary"3 FROM employees;
Name Annual Salary
------------- -------------
...
-
8/6/2019 Oracle9i SQL
35/312
Concatenation Operator (||)
Concatenates the Columns of any data
type.
A Resultant column will be a Single column.
-
8/6/2019 Oracle9i SQL
36/312
-
8/6/2019 Oracle9i SQL
37/312
Literal Character Strings
Date and character literal values must beenclosed within single quotation marks.
-
8/6/2019 Oracle9i SQL
38/312
Using DISTINCT Clause
Eliminate duplicate rows by using the
DISTINCT keyword
SQL> SELECT DISTINCT deptno
2 FROM employees;
DEPTNO---------
10
2030
-
8/6/2019 Oracle9i SQL
39/312
Summary
Use SQL*Plus as an environment to:
- Execute SQL statements- Edit SQL statements
SELECT [DISTINCT] {*,column[alias],...}FROM table;
-
8/6/2019 Oracle9i SQL
40/312
-
8/6/2019 Oracle9i SQL
41/312
Objectives
Limit the rows required
Arrange the rows in a particular order.
-
8/6/2019 Oracle9i SQL
42/312
Using WHERE Clause
Specify the Selection of rows retrieved bythe WHERE Clause.
The WHERE clause follows the FROMclause.
SELECT [DISTINCT] {*, column [alias], ...}
FROM table[WHERE condition(s)];
-
8/6/2019 Oracle9i SQL
43/312
Using WHERE Clause
SQL> SELECT ename, job, deptno2 FROM employees3 WHERE job='CLERK';
ENAME JOB DEPTNO---------- --------- ---------JAMES CLERK 30SMITH CLERK 20 ADAMS CLERK 20
MILLER CLERK 10
-
8/6/2019 Oracle9i SQL
44/312
Character Strings and Dates
Character / Dates are Represented by theSingle Quotation Marks.
Default date format is 'DD-MON-YY'
SQL> SELECT ename, job, deptno2 FROM emp3 WHERE ename = 'JAMES';
-
8/6/2019 Oracle9i SQL
45/312
Comparison Operators
Operator
=
>
>=
SELECT ename, sal, comm2 FROM employees
3 WHERE sal
-
8/6/2019 Oracle9i SQL
47/312
-
8/6/2019 Oracle9i SQL
48/312
Using BETWEEN Operator
ENAME SAL
---------- --------- MARTIN 1250TURNER 1500 WARD 1250 ADAMS 1100 MILLER 1300
SQL> SELECT ename, sal2 FROM employees3 WHERE sal BETWEEN 1000 AND 1500;
Low
erlimitH
igherlimit
Used to compare between range of values.Values Specified are inclusive.
-
8/6/2019 Oracle9i SQL
49/312
Using IN Operator
IN Operator to check with a List of Values.
SQL> SELECT empno, ename, sal, mgr
2 FROM emp3 WHERE mgr IN (7902, 7566, 7788);
EMPNO ENAME SAL MGR--------- ---------- --------- ---------
7902 FORD 3000 75667369 SMITH 800 79027788 SCOTT 3000 75667876 ADAMS 1100 7788
-
8/6/2019 Oracle9i SQL
50/312
Using LIKE Operator
Like Keyword Does Wildcard Searches inValid String Values..
% ---------- zeroormany characters
_ ----------- one character
SQL> SELECT ename2 FROM emp3 WHERE ename LIKE 'S%';
-
8/6/2019 Oracle9i SQL
51/312
Using LIKE Operator
ESCAPE identifier to search for "%" or "_".
SQL> SELECT ename
2 FROM emp3 WHERE ename LIKE _A%;
ENAME----------
JAMESWARD
-
8/6/2019 Oracle9i SQL
52/312
-
8/6/2019 Oracle9i SQL
53/312
Logical Operators
Operator
AND
OR
NOT
Meaning
Returns TRUE ifboth component
conditions are TRUE
Returns TRUE ifeithercomponent
condition is TRUE
Returns TRUE if the following
condition is FALSE
-
8/6/2019 Oracle9i SQL
54/312
Using AND Operator
AND requires both conditions to be TRUE.AND requires both conditions to be TRUE.
SQL> SELECT empno, ename, job, sal2 FROM emp
3 WHERE sal>=11004 AND job='CLERK';
EMPNO ENAME JOB SAL--------- ---------- --------- ---------
7876 ADAMS CLERK 1100
7934 MILLER CLERK 1300
-
8/6/2019 Oracle9i SQL
55/312
Using OR Operator
OR requires either condition to be TRUE.OR requires either condition to be TRUE.
SQL> SELECT empno, ename, job, sal2 FROM emp3 WHERE sal>=11004 OR job='CLERK';
EMPNO ENAME JOB SAL--------- ---------- --------- ---------
7839 KING PRESIDENT 50007698 BLAKE MANAGER 28507782 CLARK MANAGER 2450
7566 JONES MANAGER 29757654 MARTIN SALESMAN 1250
...14 rows selected.
-
8/6/2019 Oracle9i SQL
56/312
Using NOT Operator
SQL> SELECT ename, job2 FROM emp3 WHERE job NOT IN ('CLERK','MANAGER','ANALYST');
ENAME JOB---------- ---------KING PRESIDENT MARTIN SALESMAN ALLEN SALESMAN
TURNER SALESMAN WARD SALESMAN
-
8/6/2019 Oracle9i SQL
57/312
Rules of Precedence
Order Evaluated Operator
1 All comparisonoperators
2 NOT3 AND
4 OR
-
8/6/2019 Oracle9i SQL
58/312
ORDER BY Clause
Sort rows specified by the order: ASC/DESC
SQL> SELECT ename, job, deptno, hiredate
2 FROM emp3 ORDER BY hiredate;
ENAME JOB DEPTNO HIREDATE---------- --------- --------- ---------SMITH CLERK 20 17-DEC-80 ALLEN SALESMAN 30 20-FEB-81...14 rows selected.
-
8/6/2019 Oracle9i SQL
59/312
Sorting in Descending Order
SQL> SELECT ename, job, deptno, hiredate2 FROM emp3 ORDER BY hiredate DESC;
ENAME JOB DEPTNO HIREDATE
---------- --------- --------- --------- ADAMS CLERK 20 12-JAN-83SCOTT ANALYST 20 09-DEC-82 MILLER CLERK 10 23-JAN-82JAMES CLERK 30 03-DEC-81FORD ANALYST 20 03-DEC-81
KING PRESIDENT 10 17-NOV-81 MARTIN SALESMAN 30 28-SEP-81...14 rows selected.
-
8/6/2019 Oracle9i SQL
60/312
Sorting the rows by Alias
SQL> SELECT empno, ename, sal*12 annsal2 FROM emp3 ORDER BY annsal;
EMPNO ENAME ANNSAL
--------- ---------- ---------7369 SMITH 96007900 JAMES 114007876 ADAMS 132007654 MARTIN 150007521 WARD 15000
7934 MILLER 156007844 TURNER 18000
...14 rows selected.
-
8/6/2019 Oracle9i SQL
61/312
-
8/6/2019 Oracle9i SQL
62/312
-
8/6/2019 Oracle9i SQL
63/312
SQL Functions
-
8/6/2019 Oracle9i SQL
64/312
Objectives
Get an awareness of the Various SQLFunctions available.
Types of Functions in the SELECTStatement.Conversion functions
-
8/6/2019 Oracle9i SQL
65/312
Types of SQL Functions
FunctionsFunctions
SingleSingle--rowrow
functio
nsfunctio
ns
MultipleMultiple--rowrowfunctionsfunctions
-
8/6/2019 Oracle9i SQL
66/312
-
8/6/2019 Oracle9i SQL
67/312
-
8/6/2019 Oracle9i SQL
68/312
CharacterFunctions
CharacterCharacterfunctionsfunctions
LOWERLOWER
UPPERUPPERINITCAPINITCAP
CONCATCONCAT
SUBSTRSUBSTRLENGTHLENGTH
INSTRINSTR
LPADLPAD
Case conversionCase conversionfunctionsfunctions
CharactermanipulationCharactermanipulationfunctionsfunctions
-
8/6/2019 Oracle9i SQL
69/312
Function Result
Case Conversion Functions
Convert case for character strings
LOWER('SQL Course')UPPER('SQL Course')
INITCAP('SQLCourse')
sql courseSQL COURSE
Sql Course
-
8/6/2019 Oracle9i SQL
70/312
Case Conversion Functions
Display the employee number, name, anddepartment number for employee Blake.
SQL> SELECT empno, ename, deptno2 FROM emp
3 WHERE ename = 'blake';no rows selectedno rows selected
EMPNO ENAME DEPTNO--------- ---------- ---------
7698 BLAKE 30
SQL> SELECT empno, ename, deptno2 FROM emp3 WHERE LOWER(ename) = 'blake';
-
8/6/2019 Oracle9i SQL
71/312
CONCAT('Goo
d', 'String')SUBSTR('String',1,3)
LENGTH('String')
INSTR('String', 'r')
LPAD(sal,10,'*')
GoodStringStr
6
3
******5000
Function Result
CharacterFunctions
-
8/6/2019 Oracle9i SQL
72/312
Using CharacterFunctions
SQL> SELECT ename, CONCAT (ename, job), LENGTH(ename),
2 INSTR(ename, 'A')
3 FROM emp
4 WHERE SUBSTR(job,1,5) = 'SALES';
ENAME CONCAT(ENAME,JOB) LENGTH(ENAME) INSTR(ENAME,'A')---------- ------------------- ------------- ----------------
MARTIN MARTINSALESMAN 6 ALLEN ALLENSALESMAN 5
TURNER TURNERSALESMAN 6 0 WARD WARDSALESMAN 4
-
8/6/2019 Oracle9i SQL
73/312
NumberFunctions
- ROUND:Rounds value to specified decimal- ROUND(45.926, 2) 45.93
- TRUNC: Truncates value to specified decimal- TRUNC(45.926, 2) 45.92
- MOD:Returns remainder of division- MOD(1600, 300) 100
- FLOOR (num): It returns the largest integer smallerthan the given value
FLOOR(123.456) 123
- CEIL (num): It returns the smallest integer greaterthan the given number.
CEIL (123.456) 124
-
8/6/2019 Oracle9i SQL
74/312
-
8/6/2019 Oracle9i SQL
75/312
Arithmetic with Dates
Add/Subtract a Number to the Date.
Add/Subtract hours to a date by dividingthe number of hours by 24.
-
8/6/2019 Oracle9i SQL
76/312
-
8/6/2019 Oracle9i SQL
77/312
I li it D t t C i
-
8/6/2019 Oracle9i SQL
78/312
Implicit Data type Conversion
For assignments, Oracle can automaticallyconvert
VARCHAR2 or CHAR
From To
VARCHAR2 or CHAR
NUMBER
DATE
NUMBER
DATE
VARCHAR2
VARCHAR2
E li it D t t C i
-
8/6/2019 Oracle9i SQL
79/312
Explicit Data type Conversion
NUMBERNUMBER CHARACTERCHARACTER
TO_CHARTO_CHAR
TO_NUMBERTO_NUMBER
DATEDATE
TO_CHARTO_CHAR
TO_DATETO_DATE
TO CHAR ith D t
-
8/6/2019 Oracle9i SQL
80/312
TO_CHAR with Dates
The format model:
Enclosed in Single Quote Marks. Include any Valid date format.
TO_CHAR(date, 'fmt')
D t F t
-
8/6/2019 Oracle9i SQL
81/312
YYYY
Date Format
YEAR
MM
MONTH
DY
DAY
Full year in numbers
Year spelled out
2-digit value formonth
3-letter abbreviation of the day
of the week
Full name of the day
Full name of the month
-
8/6/2019 Oracle9i SQL
82/312
DATE & TIME formats continued
-
8/6/2019 Oracle9i SQL
83/312
DATE & TIME formats ..continued.
MONTH name ofmonth (char(9))
MONabbreviated name ofmonth (char(3))
Q quarter ofyear
RMroman month (I.. XII )
SS Seconds(0-59) SSSSS secondssincemidnight
TS short timeformat
TZDdaylight saving information
TZH time zone hour
TZMTime zoneminute
W week ofmonth (first weekdays 1 through 7 in month) YEAR-year willbespelled out.
-
8/6/2019 Oracle9i SQL
84/312
TO CHAR ith N b
-
8/6/2019 Oracle9i SQL
85/312
TO_CHAR with Numbers
To display a number value as a character.
TO_CHAR(number, 'fmt')
9
0
$
L.
,
Represents a number
Forces a zero to be displayed
Places a floating dollar sign
Uses the floating local currency symbolPrints a decimal point
Prints a thousand indicator
TO NUMBER & TO DATE
-
8/6/2019 Oracle9i SQL
86/312
TO_NUMBER & TO_DATE
A character string to a number format usingthe TO_NUMBER function
TO_NUMBER(char)
A character string to a date format usingthe TO_DATE function
TO_DATE(char[, 'fmt'])
SELECT TO_DATE('MAR 05 01','MON YY DD') FROM DUAL
RR Date Format
-
8/6/2019 Oracle9i SQL
87/312
RR Date Format
Current Year199519952001
2001
Specified Date27-OCT-9527-OCT-1727-OCT-17
27-OCT-95
RR Format199520172017
1995
YY Format199519172017
2095
If two digits
of thecurrentyear are
0-49
0-49 50-99
50-99
The return date is in
the current century.
The return date is inthe century afterthe current one.
The return date is in
the century beforethe current one.
The return date is inthe current century.
If the specified two-digit year is
Windowing Technique using the RR Date Format
Using Date Functions
-
8/6/2019 Oracle9i SQL
88/312
Using Date Functions
ROUND('25ROUND('25--JULJUL--95','MONTH') 0195','MONTH') 01--AUGAUG--9595
ROUND('25ROUND('25--JULJUL--95','YEAR')95','YEAR') 0101--JANJAN--9696
TRUNC('25TRUNC('25--JULJUL--95','MONTH')95','MONTH') 0101--JULJUL--9595
TRUNC('25TRUNC('25--JULJUL--95','YEAR')95','YEAR') 0101--JANJAN--9595
Using the NVL Function
-
8/6/2019 Oracle9i SQL
89/312
Using the NVL Function
NVL( exp1, exp2)
Purpose
NVL lets you replace a null with a string in the results of a query.
- If expr1 is null, then NVL returns expr2. If expr1 is not null, then NVL
returns expr1.- The arguments expr1 and expr2 can have any data type. Iftheir data types
are different, then Oracle converts expr2 to the data type of expr1 before
comparing them.
- The data type ofthe return value is always the same as the data type of
expr1, unless expr1 is character data, in which case the return values datatype is VARCHAR2 and is in the character set of expr1.
Using the DECODE Function
-
8/6/2019 Oracle9i SQL
90/312
Using the DECODE Function
CASE or IF-THEN-ELSE statement
DECODE(col/expression, search1, result1[, search2, result2,...,]
[, default])
U i th DECODE F ti
-
8/6/2019 Oracle9i SQL
91/312
Using the DECODE Function
SQL> SELECT job, sal,2 DECODE(job, 'ANALYST', SAL*1.1,3 'CLERK', SAL*1.15,4 'MANAGER', SAL*1.20,5 SAL)
6 REVISED_SALARY7 FROM emp;
JOB SAL REVISED_SALARY--------- --------- --------------PRESIDENT 5000 5000
MANAGER 2850 3420 MANAGER 2450 2940...14 rows selected.
Nesting Functions
-
8/6/2019 Oracle9i SQL
92/312
Nesting Functions
Single-row functions can be nested to anynumber of levels.
Function of Function rule
F3(F2(F1(col,arg1),arg2),arg3)
Step 1 = Result 1
Step 2 = Result 2
Step 3 = Result 3
-
8/6/2019 Oracle9i SQL
93/312
-
8/6/2019 Oracle9i SQL
94/312
Using Joins
Objectives
-
8/6/2019 Oracle9i SQL
95/312
Objectives
Cartesian JoinTo access data from more than one Table
using Equality and Non-Equality ConditionOuter and Inner JoinJoin a table to itself
Data from Multiple Tables
-
8/6/2019 Oracle9i SQL
96/312
EMPNO DEPTNO LOC----- ------- --------7839 10 NEW YORK7698 30 CHICAGO7782 10 NEW YORK7566 20 DALLAS7654 30 CHICAGO7499 30 CHICAGO...14 rows selected.
Data from Multiple Tables
EMPEMP DEPTDEPT
EMPNO ENAME ... DEPTNO------ ----- ... ------7839 KING ... 107698 BLAKE ... 30...7934 MILLER ... 10
DEPTNO DNAME LOC------ ---------- --------
10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON
What Is a Join?
-
8/6/2019 Oracle9i SQL
97/312
What Is a Join?
AJOIN Basically involves more than one Table to interactwith.
Where clause specifies the JOINCondition.
Ambiguous Column names are identifiedby the Table name.
SELECT table1.column, table2.columnFROM table1, table2
WHERE table1.column1 = table2.column2;
Cartesian Product
-
8/6/2019 Oracle9i SQL
98/312
Cartesian Product
A Cartesian product is formed when:
A Join Condition is completely omitted
All rows in the first table are joined to all
rows in the second table
Cartesian Product
-
8/6/2019 Oracle9i SQL
99/312
ENAME DNAME------ ----------KING ACCOUNTINGBLAKE ACCOUNTING
...KING RESEARCHBLAKE RESEARCH...56 rows selected.
EMP (14 rows)EMP (14 rows) DEPT (4 rows)DEPT (4 rows)
EMPNO ENAME ... DEPTNO------ ----- ... ------7839 KING ... 107698 BLAKE ... 30...7934 MILLER ... 10
DEPTNO DNAME LOC------ ---------- --------
10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON
CartesianCartesian
product:product:14*4=56 rows14*4=56 rows
Types of Joins
-
8/6/2019 Oracle9i SQL
100/312
Types of Joins
Inner J
oin
Equi Join
Non Equi Join
Self Join
Outer join
Left Outer Join
Right Outer Join
Full Outer Join
-
8/6/2019 Oracle9i SQL
101/312
What Is an Equijoin?
-
8/6/2019 Oracle9i SQL
102/312
What Is an Equijoin?
An equijoin is a join with a join conditioncontaining an equality operator. An equijoincombines rows that have equivalent values
fo
r the specified co
lum
ns.
-
8/6/2019 Oracle9i SQL
103/312
Retrieving Rows: Equijoin
-
8/6/2019 Oracle9i SQL
104/312
g q j
SQL> SELECT emp.empno, emp.ename, emp.deptno,2 dept.deptno, dept.loc3 FROM emp, dept4 WHERE emp.deptno=dept.deptno;
EMPNO ENAME DEPTNO DEPTNO LOC----- ------ ------ ------ ---------7839 KING 10 10 NEW YORK7698 BLAKE 30 30 CHICAGO7782 CLARK 10 10 NEW YORK
7566 JONES 20 20 DALLAS...14 rows selected.
Using Table Aliases
-
8/6/2019 Oracle9i SQL
105/312
g
Simplify queries by using table aliases.
SQL> SELECT emp.empno, emp.ename, emp.deptno,
2 dept.deptno, dept.loc
3 FROM emp, dept
4 WHERE emp.deptno=dept.deptno;
SQL> SELECT e.empno, e.ename, e.deptno,
2 d.deptno, d.loc
3 FROM emp e, dept d
4 WHERE e.deptno=d.deptno;
Joining More Than Two Tables
-
8/6/2019 Oracle9i SQL
106/312
g
NAME CUSTID----------- ------JOCKSPORTS 100TKB SPORT SHOP 101VOLLYRITE 102JUST TENNIS 103K+T SPORTS 105SHAPE UP 106 WOMENS SPORTS 107... ...9 rows selected.
CUSTOMERCUSTOMER
CUSTID ORDID------- -------
101 610102 611104 612106 601
102 602106 604106 605
...21 rows selected.
ORDORD
ORDID ITEMID------ -------
610 3
611 1612 1601 1602 1
...64 rows selected.
ITEMITEM
Non-Equijoins
-
8/6/2019 Oracle9i SQL
107/312
q j
An non-equijoin is a join with a joincondition containing an non-equality operator.
An non-equijoin combines rows that have
non-equivalent values for the specifiedcolumns.
Non-Equijoins
-
8/6/2019 Oracle9i SQL
108/312
q j
EMPEMP SALG
RADESALG
RADE
salary in the EMPsalary in the EMP
table is betweentable is between
low salary and highlow salary and highsalary in the SALGRADEsalary in the SALGRADE
tabletable
EMPNO ENAME SAL------ ------- ------7839 KING 50007698 BLAKE 28507782 CLARK 2450
7566 JONES 29757654 MARTIN 12507499 ALLEN 16007844 TURNER 15007900 JAMES 950
...14 rows selected.
GRADE LOSAL HISAL----- ----- ------1 700 12002 1201 14003 1401 2000
4 2001 30005 3001 9999
Retrieving Rows:Non-Equijoin
-
8/6/2019 Oracle9i SQL
109/312
Retrieving Rows:Non Equijoin
ENAME SAL GRADE---------- --------- ---------JAMES 950 1SMITH 800 1
ADAMS 1100 1...14 rows selected.
SQL> SELECT e.ename, e.sal, s.grade
2 FROM emp e, salgrade s
3 WHERE e.sal
4 BETWEEN s.losal AND s.hisal;
Self Joins
-
8/6/2019 Oracle9i SQL
110/312
A self join is a join of a table to itself. This tableappears twice in the FROM clause and is
followed by table aliases that qualify column
names in the join condition.
To perform a self join, Oracle combines and
returns rows of the table that satisfy the
join condition.
Self Joins
-
8/6/2019 Oracle9i SQL
111/312
EMP (WORKER)EMP (WORKER) EMP (MANAGER)EMP (MANAGER)
"MGR in the WORKER table is equal to EMPNO in the"MGR in the WORKER table is equal to EMPNO in theMANAGER table"MANAGER table"
EMPNO ENAME MGR ----- ------ ----7839 KING7698 BLAKE 78397782 CLARK 7839
7566 JONES 78397654 MARTIN 76987499 ALLEN 7698
EMPNO ENAME----- --------
7839 KING7839 KING
7839 KING7698 BLAKE7698 BLAKE
Joining a Table toItself
-
8/6/2019 Oracle9i SQL
112/312
g
WORKER.ENAME||'WORKSFOR'||MANAG-------------------------------BLAKE works for KINGCLARK works for KINGJONES works for KINGMARTIN works for BLAKE
...13 rows selected.
SQL> SELECT worker.ename||' works for '||manager.ename
2 FROM emp worker, emp manager
3 WHERE worker.mgr = manager.empno;
Outer Joins
-
8/6/2019 Oracle9i SQL
113/312
An outer join extends the result of a simple join. An outer join returns all rows that satisfy thejoin condition and also returns some or all of those rows from one table for which no rows from
the other satisfy the join condition.
To write a query that performs an outer join of tables A and B and returns all rows from A (a leftouter join), use the LEFT [OUTER]JOIN syntax in the FROM clause, or apply the outer joinoperator (+) to all columns of B in the join condition in the WHEREclause. For all rows in A that
have no matching rows in B, Oracle returns null for any select list expressions containing
columns of B.
n To write a query that performs an outer join of tables A and B and returns all rows from B (aright outer join), use the RIGHT [OUTER]JOIN syntax in the FROM clause, or apply theouter join operator (+) to all columns of A in the join condition in the WHEREclause. For all
rows in B that have no matching rows in A, Oracle returns null for any select list expressions
containing columns of A.
n To write a query that performs an outer join and returns all rows from A and B, extended withnulls if they do not satisfy the join condition (a full outer join), use the FULL[OUTER]JOINsyntax in the FROM clause.
Oracle Corporation recommends that you use the FROM clause OUTER JOIN syntax rather
than the Oracle join operator. Outer join queries that use the Oracle joinoperator (+) are subject to the following rules and restrictions, which do not applyto the FROM clause join syntax:
n You cannot specify the (+) operator in a query block that also contains FROM
clause join syntax.Joins
Outer Joins
-
8/6/2019 Oracle9i SQL
114/312
EMPEMP DEPTDEPT
No employee in theNo employee in the
OPERATIONS departmentOPERATIONS department
ENAME DEPTNO----- ------KING 10BLAKE 30CLARK 10
JONES 20...
DEPTNO DNAME------ ----------10 ACCOUNTING30 SALES10 ACCOUNTING
20 RESEARCH...40 OPERATIONS
Outer Joins
-
8/6/2019 Oracle9i SQL
115/312
To see also therows that do not usuallymeet the join condition.Outer join operator is the plus sign (+).
SELECT table.column, table.columnFROM table1, table2
WHERE table1.column(+) = table2.column;
SELECT table.column, table.column
FROM table1, table2
WHERE table1.column = table2.column(+);
Using Outer Joins
-
8/6/2019 Oracle9i SQL
116/312
SQL> SELECT e.ename, d.deptno, d.dname2 FROM emp e, dept d
3 WHERE e.deptno(+) = d.deptno
4 ORDER BY e.deptno;
ENAME DEPTNO DNAME---------- --------- -------------KING 10 ACCOUNTINGCLARK 10 ACCOUNTING...
40 OPERATIONS15 rows selected.
Summary
-
8/6/2019 Oracle9i SQL
117/312
SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column1 = table2.column2;
Types of Joins
Equijoins
Non- Equijoins
Outer Joins Self Joins
-
8/6/2019 Oracle9i SQL
118/312
Using Group Functions
Objectives
-
8/6/2019 Oracle9i SQL
119/312
Group Functions
GROUP BY clause HAVING Clause.
What Are Group Functions?
-
8/6/2019 Oracle9i SQL
120/312
Operate on sets of rows to give one result per group.
EMPEMP
maximummaximumsalary insalary in
the EMP tablethe EMP table
DEPTNO SAL--------- ---------
10 245010 500010 1300
20 80020 110020 300020 300020 297530 160030 2850
30 125030 95030 150030 1250
MAX(SAL)
---------
5000
Common Group Functions
-
8/6/2019 Oracle9i SQL
121/312
- AVG- COUNT
- MAX- MIN- STDDEV- SUM
- VARIANCE
Using Group Functions
-
8/6/2019 Oracle9i SQL
122/312
SELECT column, group_function(column)FROM table[WHERE condition]
[ORDER BY column];
Using the COUNT Function
-
8/6/2019 Oracle9i SQL
123/312
COUNT(*)---------
6
SQL> SELECT COUNT(*)2 FROM emp3 WHERE deptno = 30;
Using the COUNT Function
-
8/6/2019 Oracle9i SQL
124/312
COUNT(expr) returns the number of nonnull values in thegiven column.
SQL> SELECT COUNT(comm)2 FROM emp
3 WHERE deptno = 30;
COUNT(COMM)-----------
4
Group Functions & Null Values
-
8/6/2019 Oracle9i SQL
125/312
Group functions ignore null values in the column.
SQL> SELECT AVG(comm)2 FROM emp;
AVG(COMM)---------
550
NVL with Group Functions
-
8/6/2019 Oracle9i SQL
126/312
The NVL function forces group functions to include null values.
SQL> SELECT AVG(NVL(comm,0))2 FROM emp;
AVG(NVL(COMM,0))----------------
157.14286
Creating Groups of Data
-
8/6/2019 Oracle9i SQL
127/312
EMPEMP
averageaveragesalarysalaryin EMPin EMPtabletable
for eachfor eachdepartmentdepartment
2916.66672916.6667
21752175
1566.66671566.6667
DEPTNO SAL--------- ---------
10 245010 500010 1300
20 80020 110020 300020 300020 297530 160030 2850
30 125030 95030 150030 1250
DEPTNO AVG(SAL)------- ---------
10 2916.6667
20 2175
30 1566.6667
Using GROUP BY Clause
-
8/6/2019 Oracle9i SQL
128/312
SELECT column, group_function(column)FROM table[WHERE condition]
[GROUP BY group_by_expression][ORDER BY column];
Modularize rows in a table into smaller groups by using the
GROUP BY clause.
Using GROUP BY Clause
-
8/6/2019 Oracle9i SQL
129/312
Columns that are not a part of the Group Functions should beincluded in the Group by clause.
SQL> SELECT deptno, AVG(sal)
2 FROM emp3 GROUP BY deptno;
DEPTNO AVG(SAL)--------- ---------
10 2916.666720 217530 1566.6667
Grouping by Multiple Columns
-
8/6/2019 Oracle9i SQL
130/312
EMPEMP
sum salaries insum salaries inthe EMP tablethe EMP tablefor each job,for each job,grouped bygrouped bydepartmentdepartment
DEPTNO JOB SAL
--------- --------- ---------
10 MANAGER 2450
10 PRESIDENT 5000
10 CLERK 1300
20 CLERK 80020 CLERK 1100
20 ANALYST 3000
20 ANALYST 3000
20 MANAGER 2975
30 SALESMAN 1600
30 MANAGER 2850
30 SALESMAN 1250
30 CLERK 950
30 SALESMAN 1500
30 SALESMAN 1250
JOB SUM(SAL)
--------- ---------
CLERK 1300
MANAGER 2450
PRESIDENT 5000
ANALYST 6000
CLERK 1900
MANAGER 2975
CLERK 950
MANAGER 2850SALESMAN 5600
DEPTNO
--------
10
10
10
20
20
20
30
3030
GROUP BY: Multiple Columns
-
8/6/2019 Oracle9i SQL
131/312
SQL> SELECT deptno, job, sum(sal)2 FROM emp3 GROUP BY deptno, job;
DEPTNO JOB SUM(SAL)--------- --------- ---------
10 CLERK 130010 MANAGER 245010 PRESIDENT 5000
20 ANALYST 600020 CLERK 1900
...9 rows selected.
Illegal Queries
-
8/6/2019 Oracle9i SQL
132/312
Any column or expression in the SELECT list that is not an aggregatefunction must be in the GROUP BY clause.
SQL> SELECT deptno, COUNT(ename)2 FROM emp;
SELECT deptno, COUNT(ename)
*ERROR at line 1:ORA-00937: not a single-group group function
Illegal Queries
-
8/6/2019 Oracle9i SQL
133/312
Group Functions cannot be placed inthe where clause.
SQL> SELECT deptno, AVG(sal)
2 FROM emp3 WHERE AVG(sal) > 20004 GROUP BY deptno;
WHERE AVG(sal) > 2000*
ERROR at line 3:ORA-00934: group function is not allowed here
Segregating Group Results
-
8/6/2019 Oracle9i SQL
134/312
maximummaximumsalarysalary
per departmentper departmentgreater thangreater than
$2900$2900
EMPEMP
50005000
30003000
28502850
DEPTNO SAL
--------- ---------
10 2450
10 5000
10 1300
20 800
20 1100
20 3000
20 3000
20 2975
30 1600
30 2850
30 125030 950
30 1500
30 1250
DEPTNO MAX(SAL)--------- ---------
10 5000
20 3000
Using the HAVING Clause
-
8/6/2019 Oracle9i SQL
135/312
HAVING clause is to restrict groups Groups satisfying the HAVINGcondition are displayed.
SELECT column, group_functionFROM table[WHERE condition][GROUP BY group_by_expression]
[HAVING group_condition][ORDER BY column];
Using HAVING Clause
-
8/6/2019 Oracle9i SQL
136/312
SQL> SELECT deptno, max(sal)2 FROM emp3 GROUP BY deptno4 HAVING max(sal)>2900;
DEPTNO MAX(SAL)--------- ---------
10 500020 3000
Using HAVING Clause
-
8/6/2019 Oracle9i SQL
137/312
SQL> SELECT job, SUM(sal) PAYROLL2 FROM emp3 WHERE job NOT LIKE 'SALES%'4 GROUP BY job
5 HAVING SUM(sal)>50006 ORDER BY SUM(sal);
JOB PAYROLL--------- --------- ANALYST 6000
MANAGER 8275
Nesting Group Functions
-
8/6/2019 Oracle9i SQL
138/312
SQL> SELECT max(avg(sal))2 FROM emp3 GROUP BY deptno;
MAX(AVG(SAL))-------------
2916.6667
Display the maximum average salary.
Summary
-
8/6/2019 Oracle9i SQL
139/312
SELECT column, group_function (column)
FROM table[WHERE condition][GROUP BY group_by_expression][HAVING group_condition][ORDER BY column];
Order of evaluation of the clauses:
WHERE clauseGROUP BY clause
HAVING clause
-
8/6/2019 Oracle9i SQL
140/312
Subqueries
Objectives
-
8/6/2019 Oracle9i SQL
141/312
Describe the types of problems thatsubqueries can solve
Define subqueriesList the types of subqueriesWrite Single-row , Multiple-row ,Inline
views and Multiple column subqueries
Subquery to Solve a Problem
-
8/6/2019 Oracle9i SQL
142/312
Who has a salary greater than Joness?
Which employees have a salary greaterthan Joness salary?
Main Query
??
What is Joness salary?
??
Subquery
Subqueries
-
8/6/2019 Oracle9i SQL
143/312
The subquery (inner query) executes once beforethe main query.
The result of the subquery is used by the mainquery (outer query).
SELECT select_listFROM tableWHERE expr operator
(SELECT select_listFROM table);
Using a Subquery
-
8/6/2019 Oracle9i SQL
144/312
2975
SQL> SELECT ename2 FROM employee3 WHERE sal >4 (SELECT sal5 FROM employee6 WHERE empno=7566);
ENAME----------KINGFORDSCOTT
Guidelines for Subqueries
-
8/6/2019 Oracle9i SQL
145/312
Enclose subqueries in parentheses.Place subqueries on the right side of the
comparison operator.Do not add an ORDER BY clause to a
subquery.Use single-row operators with single-row
subqueries.Use multiple-row operators with multiple-
row subqueries.
Types of Subqueries
-
8/6/2019 Oracle9i SQL
146/312
Single-row subquery
CLERKCLERK
Multiple-row subquery
CLERKCLERKMANAGERMANAGER
Main query
Subqueryreturnsreturns
Multiple-column subquery
CLERK 7900CLERK 7900MANAGER 7698MANAGER 7698
Main querySubquery
returnsreturns
Main query
Subqueryreturnsreturns
Inline Views
From Clause of Main Query
Subqueryreturnsreturns
SingleSingle--rowrowMultipleMultiple--rowrow
MultipleMultiple--columncolumn
Single-Row Subqueries
-
8/6/2019 Oracle9i SQL
147/312
Return only one rowUse single-row comparison operators
Operator
=
>
>=
SELECT ename, job2 FROM employee3 WHERE job =4 (SELECT job5 FROM employee6 WHERE empno = 7369)7 AND sal >8 (SELECT sal9 FROM employee10 WHERE empno = 7876);
Group Functions in Subquery
-
8/6/2019 Oracle9i SQL
149/312
800
ENAME JOB SAL---------- --------- ---------SMITH CLERK 800
SQL> SELECT ename, job, sal2 FROM employee3 WHERE sal =4 (SELECT MIN(sal)
5 FROM employee);
HAVINGwith Subqueries
-
8/6/2019 Oracle9i SQL
150/312
The Oracle Server executes subqueries first.
800
SQL> SELECT deptno, MIN(sal)2 FROM employee3 GROUP BY deptno4 HAVING MIN(sal) > 5 (SELECT MIN(sal)6 FROM employee7 WHERE deptno = 20);
What Is Wrong ?
-
8/6/2019 Oracle9i SQL
151/312
ERROR:ORA-01427: single-row subquery returns more thanone row
no rows selected
SQL> SELECT empno, ename2 FROM employee3 WHERE sal =4 (SELECT MIN(sal)5 FROM employee
6 GROUP BY deptno);
Will This Statement Work?
-
8/6/2019 Oracle9i SQL
152/312
no rows selected
SQL> SELECT ename, job2 FROM employee3 WHERE job =4 (SELECT job5 FROM employee6 WHERE ename='SMYTHE');
Multiple-Row Subqueries
-
8/6/2019 Oracle9i SQL
153/312
Return more than one rowUse multiple-row comparison operators
Operator
IN
ANY
ALL
Meaning
Equal to any member in the list
Compare value to each value returned by
the subquery
Compare value to every value returned by
the subquery
ANY: Multiple-Row Subqueries
-
8/6/2019 Oracle9i SQL
154/312
9508001100
1300
EMPNO ENAME JOB--------- ---------- ---------
7654 MARTIN SALESMAN7521 WARD SALESMAN
SQL> SELECT empno, ename, job2 FROM employee3 WHERE sal < ANY4 (SELECT sal5 FROM employee
6 WHERE job = 'CLERK')7 AND job 'CLERK';
ALL: Multiple-Row Subqueries
-
8/6/2019 Oracle9i SQL
155/312
2916.6667
2175
1566.6667
EMPNO ENAME JOB--------- ---------- ---------
7839 KING PRESIDENT
7566 JONES MANAGER7902 FORD ANALYST7788 SCOTT ANALYST
SQL> SELECT empno, ename, job2 FROM employee3 WHERE sal > ALL4 (SELECT avg(sal)5 FROM employee6 GROUP BY deptno);
Multiple-Column Subqueries
-
8/6/2019 Oracle9i SQL
156/312
Main queryMANAGER 10
Subquery
SALESMAN 30
MANAGER 10CLERK 20
Main queryMain querycomparescompares
MANAGER 10MANAGER 10
Values from a multipleValues from a multiple--row androw andmultiplemultiple--column subquerycolumn subquery
SALESMANSALESMAN 3030
MANAGERMANAGER 1010
CLERKCLERK 2020
toto
Multiple-Column Subqueries
-
8/6/2019 Oracle9i SQL
157/312
Display the name, dept. no, salary, and commission of any employeewhose salary and commission matches both the commission and salaryof any employee in department 30.
SQL> SELECT ename, deptno, sal, comm2 FROM employee3 WHERE (sal, NVL(comm,-1)) IN4 (SELECT sal, NVL(comm,-1)
5 FROM employee6 WHERE deptno = 30);
Subquery in FROM Clause
-
8/6/2019 Oracle9i SQL
158/312
ENAME SAL DEPTNO SALAVG---------- --------- --------- ----------KING 5000 10 2916.6667JONES 2975 20 2175
SCOTT 3000 20 2175...6 rows selected.
SQL> SELECT a.ename, a.sal, a.deptno, b.salavg2 FROM employee a, (SELECT deptno, avg(sal) salavg3 FROM employee4 GROUP BY deptno) b5 WHERE a.deptno = b.deptno
6 AND a.sal > b.salavg;
Subquery in WITH Clause
-
8/6/2019 Oracle9i SQL
159/312
DNAME DEPT_TOTAL--------------- ----------RESEARCH 10875
SQL> WITH summary AS2 (SELECT dname,sum(sal) as dept_total3 FROM emp a , dept b4 WHERE a.deptno = b.deptno5 GROUP BY dname);
6 SELECT dname,dept_total7 FROM summary8 WHERE dept_total > (SELECT sum(dept_total)*1/39 FROM summary)10 ORDER BY dept_total desc;
Non-Correlated
-
8/6/2019 Oracle9i SQL
160/312
SELECT dept.name FROM deptWHERE dept.id NOT IN
( SELECT dept_idFROM empWHERE dept_id IS NOT NULL)
-
8/6/2019 Oracle9i SQL
161/312
-
8/6/2019 Oracle9i SQL
162/312
Summary
-
8/6/2019 Oracle9i SQL
163/312
Single row subqueries
A multiple- ROW subquery returns morethan one column.
A multiple-column subquery can also be
used in the FROM clause of a SELECTstatement.
-
8/6/2019 Oracle9i SQL
164/312
DML Statements
Objectives
-
8/6/2019 Oracle9i SQL
165/312
Insert rows into a tableUpdate rows in a table
Delete rows from a tableControlling the Transactions
-
8/6/2019 Oracle9i SQL
166/312
INSERT Statement
-
8/6/2019 Oracle9i SQL
167/312
Add new rows to a table by using theINSERT statement.
Only one row is inserted at a time with thissyntax.
INSERT INTO table [(column [, column...])]
VALUES (value [, value...]);
Inserting New Rows
-
8/6/2019 Oracle9i SQL
168/312
Insert a new row containing values foreach column.
List values in the default order of thecolumns in the table.
Optionally list the columns in the INSERTclause.
Enclose character and date values withinsingle quotation marks.SQL> INSERT INTO department (deptno, dname, loc)2 VALUES (50, 'DEVELOPMENT', 'DETROIT');
1 row created.1 row created.
-
8/6/2019 Oracle9i SQL
169/312
Inserting Special Values
-
8/6/2019 Oracle9i SQL
170/312
The SYSDATE and USER function records the current dateand time.
SQL> INSERT INTO employee (empno, ename, job,2 mgr, hiredate, sal, comm,
3 deptno)4 VALUES (7196, USER, 'SALESMAN',5 7782, SYSDATE, 2000, NULL,6 10);
1 row created.1 row created.
Inserting Specific Date Values
-
8/6/2019 Oracle9i SQL
171/312
Add a new employee.
SQL> INSERT INTO employee
2 VALUES (2296,'AROMANO','SALESMAN',7782,
3 TO_DATE('FEB 3,97', 'MON DD, YY'),
4 1300, NULL, 10);
1 row created.1 row created.
Verify your addition.EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ------- -------- ---- --------- ---- ---- ------
2296 AROMANO SALESMAN 7782 03-FEB-97 1300 10
Substitution Variables (&)
-
8/6/2019 Oracle9i SQL
172/312
Create an interactive script by using SQL*Plus substitution parameters.
SQL> INSERT INTO DEPARTMENT(deptno, dname, loc)2 VALUES (&department_id,3 '&department_name', '&location');
Enter value for department_id: 8080Enter value for department_name: EDUCATIONEDUCATIONEnter value for location:ATLANTAATLANTA
1 row created.
-
8/6/2019 Oracle9i SQL
173/312
MULTIPLE TABLE CONDITIONAL INSERT
-
8/6/2019 Oracle9i SQL
174/312
INSERT ALL
WHEN JOB=CLERK then
INTO BONUS(EMPNO,ANN_SAL)
VALUES(EMPNO, SAL*12)
WHENJOB=SALESMAN then
INTO BONUS(EMPNO,ANN_SAL)
VALUES(EMPNO, (SAL+NVL(COMM,0))*12)
SELECT EMPNO,job,SAL,COMM FROM EMP
Copying from Another Table
W i INSERT i h
-
8/6/2019 Oracle9i SQL
175/312
Write your INSERT statement with a
subquery.
Do not use the VALUES clause.Match the number of columns in the INSERT
clause to those in the subquery.
SQL> INSERT INTO managers(id, name, salary, hiredate)2 SELECT empno, ename, sal, hiredate3 FROM employee4 WHERE job = 'MANAGER';
3 rows created.3 rows created.
UPDATE Statement
-
8/6/2019 Oracle9i SQL
176/312
Modify existing rows with the UPDATEstatement.
Update more than one row at a time, ifrequired.
UPDATE tableSET column = value [, column = value]
[WHERE condition];
Updating Rows in a Table
-
8/6/2019 Oracle9i SQL
177/312
All rows in the table are modified if youomit the WHERE clause.
SQL> UPDATE employee2 SET deptno = 20;
14 rows updated.14 rows updated.
Updating Rows:
-
8/6/2019 Oracle9i SQL
178/312
UPDATE emp*
ERROR at line 1:
ORA-02291: integrity constraint (USR.EMP_DEPTNO_FK)violated - parent key not found
SQL> UPDATE employee2 SET deptno = 553 WHERE deptno = 10;
Integrity Constraint Error
DELETE Statement
-
8/6/2019 Oracle9i SQL
179/312
You can remove existing rows from a table by using the DELETEstatement.
DELETE [FROM] table[WHERE condition];
Deleting Rows from a Table
-
8/6/2019 Oracle9i SQL
180/312
Specific row or rows are deleted when youspecify the WHERE clause.
All rows in the table are deleted if youomit the WHERE clause.
SQL> DELETE FROM department2 WHERE dname = 'DEVELOPMENT';
1 row deleted.1 row deleted.
SQL> DELETE FROM department;4 rows deleted.4 rows deleted.
-
8/6/2019 Oracle9i SQL
181/312
-
8/6/2019 Oracle9i SQL
182/312
-
8/6/2019 Oracle9i SQL
183/312
DDL Statements
Objectives
-
8/6/2019 Oracle9i SQL
184/312
Describe the main database objectsCreate tablesDescribe the data types that can be used
when specifying column definitionAlter table definitionsDrop, rename, and truncate tables
-
8/6/2019 Oracle9i SQL
185/312
Naming Conventions
-
8/6/2019 Oracle9i SQL
186/312
Must begin with a letterCan be 130 characters longMust contain only AZ, az, 09, _, $, and #Must not duplicate the name of another object
owned by the same userMust not be an Oracle Server reserved word
CREATE TABLE Statement
-
8/6/2019 Oracle9i SQL
187/312
You must have :- CREATE TABLE privilege- A storage area
You specify:- Table name
- Column name, column data type, and columnsize
CREATE TABLE [schema.]table(column data type [DEFAULT expr];
Reference other Users Tables
-
8/6/2019 Oracle9i SQL
188/312
Tables belonging to other users are not in
the users schema.You should use the owners name as a prefix
to the table.
-
8/6/2019 Oracle9i SQL
189/312
Creating Tables
Create the table.
-
8/6/2019 Oracle9i SQL
190/312
SQL> CREATE TABLE department2 (deptno NUMBER(2),3 dname VARCHAR2(14),4 loc VARCHAR2(13));
Table created.Table created.
Confirm table creation.SQL> DESCRIBE department
Name Null? Type--------------------------- -------- ---------
DEPTNO NOT NULL NUMBER(2)DNAME VARCHAR2(14)LOC VARCHAR2(13)
Querying the Data Dictionary
Describe tables owned by the user
-
8/6/2019 Oracle9i SQL
191/312
Describe tables ownedby theuser.
View distinct object types owned by the user.
View tables, views, synonyms, and sequencesowned by the user.
SQL> SELECT *2 FROM user_tables;
SQL> SELECT DISTINCT object_type2 FROM user_objects;
SQL> SELECT *2 FROM user_catalog;
Data types
Data type Description
-
8/6/2019 Oracle9i SQL
192/312
VARCHAR2(size) Variable-length character data
CHAR(size) Fixed-length character data
NUMBER(p,s) Variable-length numeric data
DATE Date and time values
LONG Variable-length character data
up to 2 gigabytes
CLOB Single-byte character data up to 4gigabytes
RAW and LONG RAW Raw binary data
BLOB Binary data up to 4 gigabytes
BFILE Binary data stored in an externalfile; up to 4 gigabytes
MAXIMUM SIZE
-
8/6/2019 Oracle9i SQL
193/312
CHAR- 4000 bytes NUMBER- The precision p can range from 1 to 38.The scales can range
from -84 to 127. DATE- from January 1, 4712 BC to December 31, 9999 AD.
LONG- 2 Gigabytes CLOB/BLOB 4GB
Create Table Using Subquery
-
8/6/2019 Oracle9i SQL
194/312
Create a table and insert rows by combiningthe CREATE TABLE statement and ASsubqueryoption.
Match the number of specified columns to thenumber of subquery columns.
Define columns with column names anddefault values.
CREATE TABLE table
[column(, column...)]AS subquery;
Create Table Using Subquery
-
8/6/2019 Oracle9i SQL
195/312
Name Null? Type---------------------------- -------- -----EMPNO NOT NULL NUMBER(4)ENAME VARCHAR2(10) ANNSAL HIREDATE DATE
SQL> DESCRIBE dept30
SQL> CREATE TABLE dept302 AS3 SELECT empno, ename, sal*12 ANNSAL, hiredate4 FROM employee5 WHERE deptno = 30;
Table created.Table created.
ALTER TABLE Statement
Add a new column
-
8/6/2019 Oracle9i SQL
196/312
Modify an existing columnDrop an existing column,Define a default value for the new column
ALTER TABLE tableADD (column data type [DEFAULT expr]
[, column data type]...);
ALTER TABLE tableMODIFY (column data type [DEFAULT expr]
[, column data type]...);
ALTER TABLE tableDROP column column_name;
Adding a Column
DEPT30DEPT30add aadd anewnew
New columnNew column
-
8/6/2019 Oracle9i SQL
197/312
EMPNO ENAME ANNSAL HIREDATE------ ---------- --------7698 BLAKE 34200 01-MAY-817654 MARTIN 15000 28-SEP-817499 ALLEN 19200 20-FEB-817844 TURNER 18000 08-SEP-81
...
newnewcolumncolumnintointoDEPT30DEPT30tabletable
DEPT30DEPT30
EMPNO ENAME ANNSAL HIREDATE------ ---------- --------7698 BLAKE 34200 01-MAY-81
7654 MARTIN 15000 28-SEP-817499 ALLEN 19200 20-FEB-817844 TURNER 18000 08-SEP-81
...
JOB
JOB
oo
Adding a Column
-
8/6/2019 Oracle9i SQL
198/312
You use the ADD clause to add columns.
EMPNO ENAME ANNSAL HIREDATE JOB--------- ---------- --------- --------- ----
7698 BLAKE 34200 01-MAY-817654 MARTIN 15000 28-SEP-817499 ALLEN 19200 20-FEB-817844 TURNER 18000 08-SEP-81
...6 rows selected.
SQL> ALTER TABLE dept302 ADD (job VARCHAR2(9));
Table altered.Table altered.
The new column becomes the last column.
Modifying a Column
-
8/6/2019 Oracle9i SQL
199/312
You can change a column's data type, size,and default value.
A change to the default value affects onlysubsequent insertions to the table.
ALTER TABLE dept30MODIFY (ename VARCHAR2(15));Table altered.Table altered.
Set Column Unused
-
8/6/2019 Oracle9i SQL
200/312
SYNTAX:-
ALTER TABLE table_name SET UNUSED COLUMN column_name
Dropping a Column
You can remove a column and its contents
-
8/6/2019 Oracle9i SQL
201/312
entirely from the table.
You can ignore the column by set unusedcolumn
ALTER TABLE dept30DROP COLUMN ename;Table altered.Table altered.
SQL>ALTER TABLE dept30 set unused column ename;Table altered.Table altered.
SQL>SQL>ALTER TABLE dept30 drop unused columns;
Table altered.Table altered.
Dropping a Table
-
8/6/2019 Oracle9i SQL
202/312
All data and structure in the table isdeleted.
Any pending transactions are committed.
All indexes are dropped.You cannot roll back this statement.
SQL> DROP TABLE dept30;Table dropped.Table dropped.
Rename an Object
-
8/6/2019 Oracle9i SQL
203/312
To change the name of a table, view,sequence, or synonym, you execute theRENAME statement.
You must be the owner of the object.
SQL> RENAME dept TO department;Table renamed.Table renamed.
Adding Comments to a Table
You can add comments to a table or column
-
8/6/2019 Oracle9i SQL
204/312
by using the COMMENT statement.
Comments can be viewed through the datadictionary views.- ALL_COL_COMMENTS
- USER_COL_COMMENTS- ALL_TAB_COMMENTS- USER_TAB_COMMENTS
SQL> COMMENT ON TABLE employee2 IS 'Employee Information';
Comment created.Comment created.
-
8/6/2019 Oracle9i SQL
205/312
Constraints
Objectives
-
8/6/2019 Oracle9i SQL
206/312
Create the following types of constraints:- NOT NULL- UNIQUE key
- PRIMARY KEY- FOREIGN KEY- CHECK
Query the USER_CONSTRAINTS table to view allconstraint definitions and names.
What Are Constraints?
-
8/6/2019 Oracle9i SQL
207/312
Constraints enforce rules at the tablelevel.Constraints prevent the deletion of atable if there are dependencies.
The following constraint types are valid inOracle:- NOT NULL- UNIQUE Key- PRIMARY KEY
- FOREIGNKEY- CHECK
Constraint Guidelines
-
8/6/2019 Oracle9i SQL
208/312
Name a constraint or the Oracle Server willgenerate a name by using the SYS_Cn format.
Create a constraint:
- At the same time as the table is created- After the table has been createdDefine a constraint at the column or table level.View a constraint in the data dictionary.
Defining Constraints
-
8/6/2019 Oracle9i SQL
209/312
CREATE TABLE [schema.]table(column data type [DEFAULT expr][column_constraint],
[table_constraint]);
CREATE TABLE employee(empno NUMBER(4),ename VARCHAR2(10),
deptno NUMBER(7,2) NOT NULL,
CONSTRAINT emp_empno_pkPRIMARY KEY (EMPNO));
Defining Constraints
-
8/6/2019 Oracle9i SQL
210/312
Column constraint level
Table constraint level
column [CONSTRAINT constraint_name] constraint_type,
column,...[CONSTRAINT constraint_name] constraint_type(column, ...),
The NOT NULL Constraint
Ensures that null values are not permitted for the column
-
8/6/2019 Oracle9i SQL
211/312
p
EMPEMP
EMPNO ENAME JOB ... COMM DEPTNO
7839 KING PRESIDENT 107698 BLAKE MANAGER 307782 CLARK MANAGER 107566 JONES MANAGER 20...
NOT NULL constraintNOT NULL constraint(no rowmay contain(no rowmay containa null value fora null value forthis column)this column)
Absence of NOT NULLAbsence of NOT NULLconstraintconstraint(any row can contain(any row can containnull for this column)null for this column)
NOT NULL constraintNOT NULL constraint
The NOT NULL Constraint
Defined at the column level
-
8/6/2019 Oracle9i SQL
212/312
Defined at the column level
SQL> CREATE TABLE employee(2 empno NUMBER(4),3 ename VARCHAR2(10) NOT NULL,4 job VARCHAR2(9),
5 mgr NUMBER(4),6 hiredate DATE,7 sal NUMBER(7,2),8 comm NUMBER(7,2),9 deptno NUMBER(7,2) NOT NULL);
The UNIQUE Key Constraint
UNIQUE key constraintUNIQUE key constraint
-
8/6/2019 Oracle9i SQL
213/312
DEPARTMENTDEPARTMENTDEPTNO DNAME LOC------ ---------- --------
10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO
40 OPERATIONS BOSTON
Q yQ y
50 SALES DETROIT
60 BOSTON
Insert intoInsert into Not allowedNot allowed(DNAME(DNAMESALESalready exists)already exists)
AllowedAllowed
The UNIQUE Key Constraint
-
8/6/2019 Oracle9i SQL
214/312
Defined at either the table level or the column level
SQL> CREATE TABLE department(2 deptno NUMBER(2),3 dname VARCHAR2(14),4 loc VARCHAR2(13),5 CONSTRAINT dept_dname_uk UNIQUE(dname));
PRIMARY KEY Constraint
DEPARTMENTDEPARTMENTPRIMARY KEYPRIMARY KEY
-
8/6/2019 Oracle9i SQL
215/312
DEPTNO DNAME LOC------ ---------- --------
10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO
40 OPERATIONS BOSTON
Insert intoInsert into
20 MARKETING DALLAS
FINANCE NEW YORK
Not allowedNot allowed(DEPTNO(DEPTNO20 already20 alreadyexists)exists)
Not allowedNot allowed(DEPTNO is null)(DEPTNO is null)
PRIMARY KEY Constraint
-
8/6/2019 Oracle9i SQL
216/312
Defined at either the table level or the column level
SQL> CREATE TABLE department(2 deptno NUMBER(2),
3 dname VARCHAR2(14),4 loc VARCHAR2(13),5 CONSTRAINT dept_dname_uk UNIQUE (dname),6 CONSTRAINT dept_deptno_pk PRIMARY KEY(deptno));
FOREIGN KEY Constraint
DEPARTMENTDEPARTMENT
DEPTNO DNAME LOCPRIMARYPRIMARY
-
8/6/2019 Oracle9i SQL
217/312
DEPTNO DNAME LOC------ ---------- --------
10 ACCOUNTING NEW YORK20 RESEARCH DALLAS
...
PRIMARYPRIMARYKEYKEY
EMPLOYEEEMPLOYEE
EMPNO ENAME JOB ... COMM DEPTNO
7839 KING PRESIDENT 107698 BLAKE MANAGER 30...
FOREIGNFOREIGNKEYKEY
7571 FORD MANAGER ... 200 97571 FORD MANAGER ... 200
Insert intoInsert into
Not allowedNot allowed(DEPTNO(DEPTNO99
does not existdoes not existin the DEPTin the DEPTtable)table)AllowedAllowed
FOREIGN KEY Constraint
Defined at either the table level or the column level
-
8/6/2019 Oracle9i SQL
218/312
Defined at either the table level or the column level
SQL> CREATE TABLE employee(2 empno NUMBER(4),3 ename VARCHAR2(10) NOT NULL,
4 job VARCHAR2(9),5 mgr NUMBER(4),6 hiredate DATE,7 sal NUMBER(7,2),8 comm NUMBER(7,2),9 deptno NUMBER(7,2) NOT NULL,
10 CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno)11 REFERENCES dept (deptno));
FOREIGN KEY Constraint
Keywords :
-
8/6/2019 Oracle9i SQL
219/312
FOREIGN KEYDefines the column in the child table at
the table constraint level
REFERENCESIdentifies the table and column in the parenttable
ON DELETE CASCADE
Allows deletion in the parent table and deletionof the dependent rows in the child table
y
The CHECK Constraint
Defines a condition that each row must satisfy
-
8/6/2019 Oracle9i SQL
220/312
Defines a condition that each row must satisfyExpressions that are not allowed:
- References to pseudo columns CURRVAL,NEXTVAL, and ROWNUM
- Calls to SYSDATE, UID, USER, and USERENVfunctions
- Queries that refer to other values in otherrows
..., deptno NUMBER(2),CONSTRAINT emp_deptno_ck
CHECK (DEPTNO BETWEEN 10 AND 99),...
Adding a Constraint
-
8/6/2019 Oracle9i SQL
221/312
Add or drop, but not modify, a constraint
Enable or disable constraintsAdd a NOT NULL constraint by using the
MODIFY clause
ALTER TABLE tableADD [CONSTRAINT constraint] type (column);
Adding a Constraint
Add a FOREIGN KEY constraint to the EMP table indicating
-
8/6/2019 Oracle9i SQL
222/312
that a manager must already exist as a valid employee in theEMP table.
SQL> ALTER TABLE employee2 ADD CONSTRAINT emp_mgr_fk3 FOREIGN KEY(mgr) REFERENCES emp(empno);
Table altered.Table altered.
Dropping a Constraint
Remove the emp_mgr_fk constraint from
-
8/6/2019 Oracle9i SQL
223/312
the EMP table.SQL> ALTER TABLE EMP2 DROP CONSTRAINT emp_mgr_fk;
Table altered.Table altered.
Remove the PRIMARYKEY constraint on the DEPTtable and drop the associated FOREIGNKEYconstraint on the EMP.DEPTNO column.
SQL> ALTER TABLE DEPT2 DROP PRIMARY KEY CASCADE;Table altered.Table altered.
Disabling Constraints
Execute the DISABLE clause of the ALTER
-
8/6/2019 Oracle9i SQL
224/312
TABLE statement to deactivate anintegrity constraint.
Apply the CASCADE option to disabledependent integrity constraints.
SQL> ALTER TABLE EMP2 DISABLE CONSTRAINT emp_empno_pk CASCADE;
Table altered.Table altered.
Enabling Constraints
-
8/6/2019 Oracle9i SQL
225/312
Activate an integrity constraint currentlydisabled in the table definition by usingthe ENABLE clause.
A UNIQUE or PRIMARYK
EY index isautomatically created if you enable aUNIQUE key or PRIMARY KEY constraint.
SQL> ALTER TABLE EMP2 ENABLE CONSTRAINT emp_empno_pk;
Table altered.Table altered.
Viewing Constraints
Query the USER_CONSTRAINTS table to view all constraint definitions
-
8/6/2019 Oracle9i SQL
226/312
Q y _and names.
CONSTRAINT_NAME C SEARCH_CONDITION------------------------ - -------------------------SYS_C00674 C EMPNO IS NOT NULL
SYS_C00675 C DEPTNO IS NOT NULLEMP_EMPNO_PK P...
SQL> SELECT constraint_name, constraint_type,2 search_condition
3 FROM user_constraints4 WHERE table_name = 'EMPLOYEE';
Columns with Constraints
View the columns associated with the constraint names in theUSER_CONS_COLUMNS view
-
8/6/2019 Oracle9i SQL
227/312
CONSTRAINT_NAME COLUMN_NAME------------------------- ----------------------EMP_DEPTNO_FK DEPTNOEMP_EMPNO_PK EMPNOEMP_MGR_FK MGR
SYS_C00674 EMPNOSYS_C00675 DEPTNO
SQL> SELECT constraint_name, column_name2 FROM user_cons_columns3 WHERE table_name = 'EMPLOYEE';
Summary
Create the following types of constraints:
-
8/6/2019 Oracle9i SQL
228/312
g yp- NOT NULL- UNIQUE key- PRIMARY KEY
- FOREIGN KEY- CHECK
Query the USER_CONSTRAINTS table to view allconstraint definitions and names.
-
8/6/2019 Oracle9i SQL
229/312
Views
-
8/6/2019 Oracle9i SQL
230/312
Database Objects
-
8/6/2019 Oracle9i SQL
231/312
Description
Basic unit of storage; composed of rows
and columns
Logically represents subsets of data from
oneo
rmo
re tables
Generates primary key values
Improves the performance of some queries
Alternative name for an object
Object
Table
View
Sequence
Index
Synonym
Why Use Views?
-
8/6/2019 Oracle9i SQL
232/312
To restrict database accessTo make complex queries easyTo allow data independence
To present different views of the same data
Creating a View
You embed a subquery within the CREATE VIEW
-
8/6/2019 Oracle9i SQL
233/312
statement.
The subquery can contain complex SELECT
syntax. The subquery cannot contain an ORDER BYclause.
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEWview[(alias[, alias]...)]
AS subquery
[WITH READ ONLY]
Creating a View
Create a view, EMPVU10, that contains
-
8/6/2019 Oracle9i SQL
234/312
details of employees in department 10.
Describe the structure of the view by usingthe SQL*Plus DESCRIBE command.
SQL> DESCRIBE empvu10
SQL> CREATE VIEW empvu102 AS SELECT empno, ename, job3 FROM employee4 WHERE deptno = 10;
View created.View created.
Creating a View
Create a view by using column aliases in
-
8/6/2019 Oracle9i SQL
235/312
the subquery.
Select the columns from this view by the
given alias names.
SQL> CREATE VIEW salvu302 AS SELECT empno EMPLOYEE_NUMBER, ename NAME,3 sal SALARY4 FROM employee
5 WHERE deptno = 30;View created.View created.
Retrieving Data from a View
-
8/6/2019 Oracle9i SQL
236/312
EMPLOYEE_NUMBER NAME SALARY--------------- ---------- ---------
7698 BLAKE 2850
7654 MARTIN 12507499 ALLEN 16007844 TURNER 15007900 JAMES 9507521 WARD 1250
6 rows selected.
SQL> SELECT *2 FROM salvu30;
Querying a View
-
8/6/2019 Oracle9i SQL
237/312
USER_VIEWSUSER_VIEWSEMPVU10EMPVU10
SELECT empno, ename, jobFROM employeeWHERE deptno = 10;
USER_VIEWSUSER_VIEWSEMPVU10EMPVU10
SELECT empno, ename, jobFROM employeeWHERE deptno = 10;
SQL*PlusSQL*Plus
SELECT *FROM empvu10;
EMP
7839 KING PRESIDENT
7782 CLARK MANAGER7934 MILLER CLERK
Modifying a View
Modify the EMPVU10 view by using CREATE
-
8/6/2019 Oracle9i SQL
238/312
OR REPLACE VIEW clause. Add an alias foreach column name.
Column aliases in the CREATE VIEW clause
are listed in the same order as the columnsin the subquery.
SQL> CREATE OR REPLACE VIEW empvu102 (employee_number, employee_name, job_title)3 AS SELECT empno, ename, job
4 FROM employee5 WHERE deptno = 10;
View created.View created.
Creating a Complex View
Create a complex view that contains group functions to display valuesfrom two tables.
-
8/6/2019 Oracle9i SQL
239/312
SQL> CREATE VIEW dept_sum_vu
2 (name, minsal, maxsal, avgsal)3 AS SELECT d.dname, MIN(e.sal), MAX(e.sal),4 AVG(e.sal)5 FROM employee e, department d 6 WHERE e.deptno = d.deptno7 GROUP BY d.dname;
View created.View created.
DML Operations on a View
R l f P f i DML O ti Vi
-
8/6/2019 Oracle9i SQL
240/312
You can perform DML operations on simpleviews.
You cannot remove a row if the viewcontains the following:- Group functions- A GROUP BY clause- The DISTINCT keyword
Rules for Performing DML Operations on a View
DML Operations on a View
Rules for Performing DML Operations on a View
-
8/6/2019 Oracle9i SQL
241/312
You cannot modify data in a view if it contains:- Any of the conditions previously mentioned- Columns defined by expressions
- The ROWNUM pseudo columnYou cannot add data if:- The view contains any of the conditions
mentioned above or previously mentioned
- There are NOT NULL columns in the base tablesthat are not selected by the view
Denying DML Operations
Youcan ensure that no DML operations occurbyadding the WITH READONLYoption to yourview definition.
-
8/6/2019 Oracle9i SQL
242/312
SQL> CREATE OR REPLACE VIEW empvu102 (employee_number, employee_name, job_title)
3 AS SELECT empno, ename, job4 FROM employee5 WHERE deptno = 106 WITH READ ONLY;
View created.View created.
Any attem
pt to
perfo
rm
a DMLo
n any row
inthe viewwill result in Oracle Server error ORA-01752.
Removing a View
-
8/6/2019 Oracle9i SQL
243/312
Remove a view without losing data because a view is based on underlyingtables in the database.
SQL> DROP VIEW empvu10;View dropped.View dropped.
DROP VIEWview;
Summary
A view is derived from data in other tables or
h i
-
8/6/2019 Oracle9i SQL
244/312
other views.A view provides the following advantages:
- Restricts database access- Simplifies queries
- Provides data independence- Allows multiple views of the same data- Can be dropped without removing the
underlying data
-
8/6/2019 Oracle9i SQL
245/312
Synonyms, Indexes and Sequences
-
8/6/2019 Oracle9i SQL
246/312
Database Objects
DescriptionObject
-
8/6/2019 Oracle9i SQL
247/312
Basic unit of storage; composed of rows
and columns
Logically represents subsets of data from
one ormore tables
Generates primary key values
Improves the performance of some queries
Alternative name for an object
Table
View
Sequence
Index
Synonym
What Is a Sequence?
-
8/6/2019 Oracle9i SQL
248/312
Automatically generates unique numbers Is a sharable object Is typically used to create a primary key
valueReplaces application codeSpeeds up the efficiency of accessing
sequence values when cached in memory
Creating a Sequence
Define a sequence to generate sequential numbers
automatically
-
8/6/2019 Oracle9i SQL
249/312
automatically
CREATE SEQUENCE sequence[INCREMENT BY n]
[START WITH n][{MAXVALUE n | NOMAXVALUE}][{MINVALUE n | NOMINVALUE}][{CYCLE | NOCYCLE}][{CACHE n | NOCACHE}];
Creating a Sequence
Create a sequence named DEPT_DEPTNO to be used
f th i k f th
-
8/6/2019 Oracle9i SQL
250/312
for the primary key of theDEPARTMENT table.
Do not use the CYCLE option.
SQL> CREATE SEQUENCE dept_deptno2 INCREMENT BY 13 START WITH 914 MAXVALUE 1005
created.created.
Confirming Sequences
V if l i thUSER SEQUENCES d t di ti t bl
-
8/6/2019 Oracle9i SQL
251/312
Verify your sequence values in theUSER_SEQUENCES data dictionary table.
The LAST_NUMBER column displays thenext available sequence number.
SQL> SELECT sequence_name, min_value, max_value,2 increment_by, last_number3 FROM user_sequences;
Pseudo columns
NEXTVAL t th t il bll
-
8/6/2019 Oracle9i SQL
252/312
NEXTVAL returns the next availablesequence value.CURRVAL obtains the current sequence
value.
ROWID uniquely identify the rows in yourtable. LEVEL a special column you can
reference only in a hierarchical query
Using a Sequence
Insert a new department named
MARKETING in San Diego
-
8/6/2019 Oracle9i SQL
253/312
MARKETING in San Diego.
View the current value for theDEPT_DEPTNO sequence.
SQL> INSERT INTO departmnent(deptno, dname, loc)2 VALUES (dept_deptno.NEXTVAL,3 'MARKETING', 'SAN DIEGO');
1 row created.1 row created.
SQL> SELECT dept_deptno.CURRVAL2 FROM dual;
Using a Sequence
Caching sequence values in memory allowsf t t th l
-
8/6/2019 Oracle9i SQL
254/312
Caching sequence values in memory allowsfaster access to those values.Gaps in sequence values can occur when:
- A rollback occurs- The system crashes- A sequence is used in another table
View the next available sequence, if it wascreated with NOCACHE, by querying theUSER_SEQUENCES table.
Modifying a Sequence
Change the increment value maximum value minimum value
-
8/6/2019 Oracle9i SQL
255/312
Change the increment value, maximum value, minimum value,cycle option, or cache option.
SQL> ALTER SEQUENCE dept_deptno
2 INCREMENT BY 13 MAXVALUE 9999994 NOCACHE5 NOCYCLE;
Sequence altered.Sequence altered.
Removing a Sequence
-
8/6/2019 Oracle9i SQL
256/312
Remove a sequence from the datadictionary by using the DROP SEQUENCEstatement.
Once removed, the sequence can no longerbe referenced.SQL> DROP SEQUENCE dept_deptno;Sequence dropped.Sequence dropped.
What Is an Index?
-
8/6/2019 Oracle9i SQL
257/312
Schema objectUsed by the Oracle Server to speed up the
retrieval of rows by using a pointer
Reduces disk I/O by using rapid path accessmethod to locate the data quickly
Independent of the table it indexesAutomatically used and maintained by the
Oracle Server
How Are Indexes Created?
-
8/6/2019 Oracle9i SQL
258/312
Automatically- A unique index is created automatically when
you define a PRIMARY KEY or UNIQUE keyconstraint in a table definition.
Manually- Users can create nonunique indexes on columns
to speed up access time to the rows.
Creating an Index
Create an index on one or more columns
-
8/6/2019 Oracle9i SQL
259/312
Improve the speed of query access on theENAME column in the EMP tableSQL> CREATE INDEX emp_ename_idx2 ON employee(ename);
Index created.Index created.
CREATE INDEX indexON table (column[, column]...);
Confirming Indexes
The USER_INDEXES data dictionary view
contains the name of the index and its
-
8/6/2019 Oracle9i SQL
260/312
contains the name of the index and itsuniqueness.The USER_IND_COLUMNS view contains the
index name, the table name, and the
column name.
SQL> SELECT ic.index_name, ic.column_name,2 ic.column_position col_pos,ix.uniqueness3 FROM user_indexes ix, user_ind_columns ic
4 WHERE ic.index_name = ix.index_name5 AND ic.table_name = 'EMP';
Removing an Index
Remove an index from the data dictionary.
-
8/6/2019 Oracle9i SQL
261/312
Remove the EMP_ENAME_IDX index from thedata dictionary.
To drop an index, you must be the owner ofthe index or have the DROP ANY INDEXprivilege.
SQL> DROP INDEX emp_ename_idx;Index dropped.Index dropped.
SQL> DROP INDEX index;
Synonyms
Purpose
Use the CREATE SYNONYM statement to create a synonym, which is analternative name for a table, view, sequence, procedure, stored function,
-
8/6/2019 Oracle9i SQL
262/312
, , q , p , ,package, materialized view, Java class schema object, user-defined object type,or another synonym.
Synonyms provide both data independence and location transparency.
Synonyms permit applications to function without modification regardless of whichuser owns the table or view and regardless of which database holds the table or
view.However, synonyms are not a substitute for privileges on database objects. Such
privileges must be granted to a user before the user can use the synonym.
You can refer to synonyms in the following DML statements: SELECT, INSERT,UPDATE, DELETE, EXPLAIN PLAN, and LOCK TABLE.
You can refer to synonyms in the following DDL statements: AUDIT, NOAUDIT,
GRANT, REVOKE, and COMMENT.
Prerequisites
Synonyms
-
8/6/2019 Oracle9i SQL
263/312
q
To create a private synonym in your own schema, you must have CREATESYNONYM system privilege.
To create a private synonym in another users schema, you must have CREATE
ANY SYNONYM system privilege.
To create a PUBLIC synonym, you must have CREATE PUBLIC SYNONYM systemprivilege.
Synonyms
-
8/6/2019 Oracle9i SQL
264/312
Simplify access to objects by creating a synonym (another name for anobject).
Refer to a table owned by another user.Shorten lengthy object names.
CREATE [PUBLIC] SYNONYMsynonym
FOR object;
Create & Remove Synonyms
Create a shortened name / SYNONYM for theDEPT_SUM_VU view.
-
8/6/2019 Oracle9i SQL
265/312
SQL> CREATE SYNONYM d_sum2 FOR dept_sum_vu;
Synonym Created.Synonym Created.
SQL> DROP SYNONYM d_sum;
Synonym dropped.Synonym dropped.
Drop a synonym.
-
8/6/2019 Oracle9i SQL
266/312
DCL Statements
Objectives
-
8/6/2019 Oracle9i SQL
267/312
Create usersCreate roles to ease setup and maintenance
of the security modelGRANT and REVOKE object privileges
-
8/6/2019 Oracle9i SQL
268/312
Privileges
Database security
-
8/6/2019 Oracle9i SQL
269/312
Database security- System security- Data security
System privileges: Gain access to the
databaseObject privileges: Manipulate the content of
the database objectsSchema: Collection of objects, such as
tables, views, and sequences
System Privileges
M th 80 i il il bl
-
8/6/2019 Oracle9i SQL
270/312
More than 80 privileges are available.The DBA has high-level system privileges.
- Create new users
- Remove users- Remove tables- Backup tables
Creating Users
-
8/6/2019 Oracle9i SQL
271/312
The DBA creates users by using the CREATE USER statement.
SQL> CREATE USER scott2 IDENTIFIED BY tiger;
User created.User created.
CREATE USER userIDENTIFIED BY password;
User System Privileges
GRANT privilege [ privilege ]
Once a user is created, the DBA can grantspecific system privileges to a user.
-
8/6/2019 Oracle9i SQL
272/312
GRANTprivilege [,privilege...]TO user[, user...];
An application developermay have the followingsystem privileges:
CREATE SESSION
CREATE TABLE
CREATE SEQUENCE
CREATE VIEW
CREATE PROCEDURE
Granting System Privileges
-
8/6/2019 Oracle9i SQL
273/312
The DBA can grant a user specific system privileges.
SQL> GRANT create table, create sequence, create view2 TO scott;
Grant succeeded.Grant succeeded.
What Is a Role?
-
8/6/2019 Oracle9i SQL
274/312
Allocating privilegesAllocating privilegeswithout a rolewithout a role
Allocating privilegesAllocating privilegeswith a rolewith a role
PrivilegesPrivileges
UsersUsers
ManagerManager
Creating Roles
SQL> CREATE ROLE manager;
-
8/6/2019 Oracle9i SQL
275/312
Role created.Role created.
SQL> GRANT create table, create view
2 to manager;Grant succeeded.Grant succeeded.
SQL> GRANT manager to BLAKE, CLARK;Grant succeeded.Grant succeeded.
Changing Your Password
When the user account is created a password is
-
8/6/2019 Oracle9i SQL
276/312
When the user account is created, a password isinitialized.
Users can change their password by using the
ALTER USER statement.SQL> ALTER USER scott2 IDENTIFIED BY lion;
User altered.User altered.
ObjectPrivilege Table View Sequence Procedure
ALTER DELETE
Object Privileges
-
8/6/2019 Oracle9i SQL
277/312
DELETE
EXECUTE
INDEX
INSERT
REFERENCES SELECT
UPDATE
Object Privileges
Object privileges vary from object to object.An owner has all the privileges on the object.
-
8/6/2019 Oracle9i SQL
278/312
An owner has all the privileges on the object.An owner can give specific privileges on that
owners object.
GRANT object_priv[(columns)]ON objectTO {user|role|PUBLIC}[WITH GRANT OPTION];
Granting Object Privileges
SQL GRANT l t
Grant query privileges on the EMP table.
-
8/6/2019 Oracle9i SQL
279/312
SQL> GRANT select2 ON employee3 TO sue, rich;
Grant succeeded.Grant succeeded.
SQL> GRANT update (dname, loc)2 ON department
3 TO scott, manager;Grant succeeded.Grant succeeded.
Grant privileges to update specific columns tousers and roles.
GRANT Keywords
Give a user authority to pass along the privileges.
WITH GRANT OPTION & PUBLIC Keywords
-
8/6/2019 Oracle9i SQL
280/312
Allow all users on the system to query data fromAlices DEPARTMENT table.
SQL> GRANT select, insert2 ON department3 TO scott4 WITH GRANT OPTION;
Grant succeeded.Grant succeeded.
SQL> GRANT select
2 ON alice.department3 TO PUBLIC;Grant succeeded.Grant succeeded.
y p g p g
Confirming Privileges Granted
Data Dictionary Table Description
ROLE_SYS_PRIVS System privileges granted to rolesROLE TAB PRIVS T bl i il t d t l
-
8/6/2019 Oracle9i SQL
281/312
ROLE_TAB_PRIVS Table privileges granted to roles
USER_ROLE_PRIVS Roles accessible by the user
USER_TAB_PRIVS_MADE Object privileges granted on theuser's objects
USER_TAB_PRIVS_RECD Object privileges granted to theuser
USER_COL_PRIVS_MADE Object privileges granted on thecolumns of the user's objects
USER_COL_PRIVS_RECD Object privileges granted to theuseron specific columns
Revoke Object Privileges
You use the REVOKE statement to revokeprivileges granted to other users.
-
8/6/2019 Oracle9i SQL
282/312
p g gPrivileges granted to others through the
WITH GRANT OPTION will also be revoked.
REVOKE {privilege [, privilege...]|ALL}ON objectFROM {user[, user...]|role|PUBLIC}
[CASCADE CONSTRAINTS];
Revoking Object Privileges
As user Alice, revoke the SELECT and INSERT privileges given to
-
8/6/2019 Oracle9i SQL
283/312
As user Alice, revoke the SELECT and INSERT privileges given touser Scott on the DEPARTMENT table.
SQL> REVOKE select, insert2 ON department3 FROM scott;
Revoke succeeded.Revoke succeeded.
Summary
CREATE USER Allows the DBA to create a user
GRANT Allows the user to give other users
-
8/6/2019 Oracle9i SQL
284/312
gprivileges to access the user'sobjects
CREATE ROLE Allows the DBA to create acollection of privileges
ALTER USER Allows users to change theirpassword
REVOKE Removes privileges on an object from users
-
8/6/2019 Oracle9i SQL
285/312
The Oracle Architecture
Objectives
Oracle Architecture Oracle Database
-
8/6/2019 Oracle9i SQL
286/312
The Study Phases Objectives- The Memory Architecture
- The Disk Architecture- The Back Ground Processes The Logical Architecture The Physical Architecture
How Oracle Works
Understanding Oracle Database
Overview of oracle Database Architecture
-
8/6/2019 Oracle9i SQL
287/312
Memory Structure
Process Structure
Storage Structure
New Features
Overviewof Oracle Architecture
PMON
* Fixed Size :
* Total SGA Size :
1700 Mbyte
SMON RECO D000 S000 P000
-
8/6/2019 Oracle9i SQL
288/312
SGAShared SQL Area Database Buffer Cashe
KByte1,200,000 KByte
Redo LogBuffer
KByte2,100KByte
LGWR
Data File
Raw Device ARCH
TL-812
Archive Log Mode(50M)
* Fixed Size :
70 Kbyte
* Variavle Size :
490 MByte
4,000,000 KByte
DBW0 CKPT
Oracle Architecture
-
8/6/2019 Oracle9i SQL
289/312
Oracle Database
Oracle Database
-
8/6/2019 Oracle9i SQL
290/312
Physical Logical
DataFile
Control File
RedologFile
DB Files Non DB Files
Archived Log File
PWD File INIT File
Tablespaces
Segments
Extents
Data Blocks
The 3 Base
1. Memory Architecture
-
8/6/2019 Oracle9i SQL
291/312
2. Disk Architecture
3. Background Processes
Disk
Memory / Disk Architecture
-
8/6/2019 Oracle9i SQL
292/312
Disk
SGA
Disk Architecture
Background
processes
Disk Architecture
DATA LOG
-
8/6/2019 Oracle9i SQL
293/312
DATA
FILES
LOG
FILES
CONTROL
FILES