P. 1
Oracle9i SQL

Oracle9i SQL

|Views: 75|Likes:
Published by Kamal Joshi

More info:

Published by: Kamal Joshi on Aug 12, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PPT, PDF, TXT or read online from Scribd
See more
See less

10/18/2012

pdf

text

original

Sections

  • Structure Query Language
  • How SQL Works
  • Objectives
  • Relational Database Definition
  • Data Models
  • Relating Multiple Tables
  • Relational DB Properties
  • RDBMS Using SQL
  • RDBMS
  • ORACLE 9i ±An Overview
  • Why use OOPs Methodology
  • Characteristics of OOPS
  • Platform Independency
  • Basic SELECT Statement
  • Writing SQL Statements
  • Selecting All Columns
  • Selecting Specific Columns
  • Default Column Headings
  • Arithmetic Expressions
  • Using Arithmetic Operators
  • Operator Precedence
  • Using Parentheses
  • Defining a Null Value
  • Null Values in Arithmetic Expr
  • Defining Column Alias
  • Using Column Aliases
  • Concatenation Operator (||)
  • Using Concatenation Operator
  • Literal Character Strings
  • Summary
  • Using 'Where' and 'Order By' Clauses
  • Using µWHERE¶ Clause
  • Using WHERE Clause
  • Character Strings and Dates
  • Comparison Operators
  • Using Comparison Operators
  • More Comparison Operators
  • Using BETWEEN Operator
  • Using IN Operator
  • Using IS NULL Operator
  • Logical Operators
  • Using AND Operator
  • Using OR Operator
  • Using NOT Operator
  • Rules of Precedence
  • µORDER BY¶ Clause
  • Sorting in Descending Order
  • Sorting the rows by Alias
  • Sorting by Multiple Columns
  • SQL Functions
  • Types of SQL Functions
  • Character Functions
  • Using Character Functions
  • Number Functions
  • Working with Dates
  • Arithmetic with Dates
  • Working with Date Functions
  • Conversion Functions
  • Implicit Data type Conversion
  • Explicit Data type Conversion
  • µTO_CHAR¶ with Dates
  • Date Format
  • DATE & TIME formats
  • DATE & TIME formats ..continued«
  • Date Format Elements
  • µTO_CHAR¶ with Numbers
  • TO_NUMBER & TO_DATE
  • µRR¶ Date Format
  • Using Date Functions
  • Using the NVL Function
  • Nesting Functions
  • Data from Multiple Tables
  • What Is a Join?
  • Cartesian Product
  • Types of Joins
  • Inner Joins
  • Retrieving Rows: Equijoin
  • Using Table Aliases
  • Joining More Than Two Tables
  • Retrieving Rows:Non-Equijoin
  • Joining a Table to Itself
  • Using Outer Joins
  • What Are Group Functions?
  • Common Group Functions
  • Using Group Functions
  • Group Functions & Null Values
  • NVL with Group Functions
  • Creating Groups of Data
  • Using µGROUP BY¶ Clause
  • Using GROUP BY Clause
  • Grouping by Multiple Columns
  • GROUP BY: Multiple Columns
  • Segregating Group Results
  • Using the µHAVING¶ Clause
  • Nesting Group Functions
  • Subquery to Solve a Problem
  • Subqueries
  • Using a Subquery
  • Guidelines for Subqueries
  • Group Functions in Subquery
  • HAVING with Subqueries
  • What Is Wrong ?
  • Will This Statement Work?
  • Multiple-Row Subqueries
  • ANY: Multiple-Row Subqueries
  • ALL: Multiple-Row Subqueries
  • Subquery in FROM Clause
  • Subquery in WITH Clause
  • Non-Correlated
  • Correlated
  • Correlated Subqueries
  • Data Manipulation Language
  • INSERT Statement
  • Inserting New Rows
  • Insert Rows with Null Values
  • Inserting Special Values
  • Inserting Specific Date Values
  • Substitution Variables (&)
  • Multiple table insert
  • Copying from Another Table
  • UPDATE Statement
  • Updating Rows in a Table
  • Updating Rows:
  • DELETE Statement
  • Deleting Rows from a Table
  • Deleting Rows:
  • Naming Conventions
  • CREATE TABLE Statement
  • Reference other User¶s Tables
  • The DEFAULT Option
  • Creating Tables
  • Querying the Data Dictionary
  • Data types
  • MAXIMUM SIZE
  • ALTER TABLE Statement
  • Modifying a Column
  • Set Column Unused
  • Dropping a Column
  • Dropping a Table
  • Rename an Object
  • Adding Comments to a Table
  • What Are Constraints?
  • Constraint Guidelines
  • The UNIQUE Key Constraint
  • FOREIGN KEY Constraint
  • The CHECK Constraint
  • Dropping a Constraint
  • Disabling Constraints
  • Enabling Constraints
  • Viewing Constraints
  • Columns with Constraints
  • Database Objects
  • Why Use Views?
  • Retrieving Data from a View
  • Querying a View
  • Modifying a View
  • Creating a Complex View
  • Denying DML Operations
  • Removing a View
  • What Is a Sequence?
  • Confirming Sequences
  • Pseudo columns
  • Modifying a Sequence
  • Removing a Sequence
  • What Is an Index?
  • How Are Indexes Created?
  • Creating an Index
  • Confirming Indexes
  • Removing an Index
  • Synonyms
  • Create & Remove Synonyms
  • Controlling User Access
  • Privileges
  • System Privileges
  • Creating Users
  • User System Privileges
  • Granting System Privileges
  • What Is a Role?
  • Creating Roles
  • Changing Your Password
  • Granting Object Privileges
  • GRANT Keywords
  • Confirming Privileges Granted
  • Revoke Object Privileges
  • Revoking Object Privileges
  • Understanding Oracle Database
  • Overview of Oracle Architecture
  • The ³3´ Base
  • Memory / Disk Architecture
  • Disk Architecture
  • Data Files
  • Redo Log File
  • Control File
  • Memory Architecture
  • Oracle Instance
  • Shared Global Area
  • Database and Log Buffers
  • Shared Pool
  • Program Global Area
  • Logical Structure
  • Data Files and Tablespaces
  • Enlarging Tablespace
  • Enlarging Database
  • How Oracle Works

Oracle 9i SQL

Being Presented By

PM Karthick
Corporate Trainer Executive

Structure Query Language

Structured Query Language (SQL) is the set of statements with which all programs and users access data in an Oracle database.

How SQL Works 
It processes sets of data as groups rather than

as individual units. 
It provides automatic navigation to the data. It uses statements that are complex and

powerful individually ( PL/SQL). 
Essentially, SQL lets you work with data at the

logical level.

Introduction to ORACLE

Objectives 

What is RDBMS ?  Advantages of SQL and PLSQL  RDBMS Vs ORDBMS  Uses and benefits of PL/SQL

Relational Database Definition A relational database is a collection of two-dimensional tables. relations or Database Table Name: EMP EMPNO 7839 7698 7782 7566 ENAME KING BLAKE CLARK JONES JOB PRESIDENT MANAGER MANAGER MANAGER DEPTNO 10 30 10 20 Table Name: DEPT DEPTNO 10 20 30 40 DNAME ACCOUNTING RESEARCH SALES OPERATIONS LOC NEW YORK DALLAS CHICAGO BOSTON .

Data Models Model of system in client¶s mind Entity model of client¶s model Table model of entity model Server Tables on disk .

EMP EMPNO 7839 7698 7782 7566 ENAME KING BLAKE CLARK JONES JOB PRESIDENT MANAGER MANAGER MANAGER DEPTNO 10 30 10 20 DEPT DEPTNO 10 20 30 40 DNAME ACCOUNTING RESEARCH SALES OPERATIONS LOC NEW YORK DALLAS CHICAGO BOSTON Primary key Foreign key Primary key .Relating Multiple Tables EACH AND EVERY ROW IS IDENTIFIED BY A UNIQUE KEY CALLED PRIMARY KEY LOGICAL RELATED ROWS SHARED the PKEY as FOREIGN KEY.

Set of Operators for Functionality .SQL Statements to be used for manipulating the database. .Relational DB Properties  A relational database .No Physical Pointers to access and store relations between Tables. .

RDBMS Using SQL SQL statement is entered SQL> SELECT loc 2 FROM dept. Query is sent to Database Database Dept Location ------------Dallas New York Santa Clara Message is sent to the Client .

RDBMS Server User tables Data dictionary .

.ORACLE 9i ± An Overview  Objects : User Defined Types very much in line to C++  Fully relational compatible  LOBS / Multimedia Files in Database !  Oracle Enterprise Manager Classes.

. Objects and Interactions  They replicate real time environment.Why use OOPs Methodology SIMPLIFY To SOLVE.

Characteristics of OOPS  INHERITANCE  POLYMORPHISM  ENCAPSULATION .

Platform Independency USER 3 USER 1 USER 2 USER 4 ORACLE SERVER Server simply satisfies the request OS manages Data files OS Data files in the Disk .

SQL Statements SELECT Data retrieval INSERT UPDATE DELETE MERGE Data Manipulation Language (DML) CREATE ALTER DROP RENAME TRUNCATE Data Definition Language (DDL) .

SQL Statements COMMIT ROLLBACK SAVEPOINT GRANT REVOKE Transaction Control Language (TCL) Data Control Language (DCL) .

Objectives SQL SELECT statements A basic SELECT statement SQL statements and SQL*Plus commands .

. column [alias].. .Basic SELECT Statement SELECT FROM [DISTINCT] {*..} table. Select Clause determines what columns The From Clause determines which table.

Writing SQL Statements SQL is not Case Sensitive. Keywords cannot be split or abbreviated. SQL Statements can be split across lines. to promote readability. . Clauses are placed in different lines.

DEPTNO --------10 20 30 40 DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS LOC ------------NEW YORK DALLAS CHICAGO BOSTON .Selecting All Columns SQL> SELECT * 2 FROM departments.

DEPTNO --------10 20 30 40 LOC ------------NEW YORK DALLAS CHICAGO BOSTON .Selecting Specific Columns SQL> SELECT deptno. loc 2 FROM departments.

 Numerical Columns headings are not truncated. Column name can be replaced by the Alias name .Numeric Data is Right Justified  Display Headings in UPPER CASE.Default Column Headings Default justification .Date and Character Data is Left Justified .  Character / Date Columns headings will be Truncated.

Arithmetic Expressions Basic Arithmetic operators Operator + * / Description Add Subtract Multiply Divide .

--------..--------KING 5000 5300 BLAKE 2850 3150 CLARK 2450 2750 JONES 2975 3275 MARTIN 1250 1550 ALLEN 1600 1900 . 14 rows selected. sal.Using Arithmetic Operators SQL> SELECT ename. . sal+300 2 FROM employees.. ENAME SAL SAL+300 ---------.

Operator Precedence

*

/

+

_ 

Parentheses can force precedence  Multiplication and Division followed by Addition and subtraction.

Operator Precedence

SQL> SELECT ename, sal, 12*sal+100 2 FROM employees; ENAME SAL 12*SAL+100 ---------- --------- ---------KING 5000 60100 BLAKE 2850 34300 CLARK 2450 29500 JONES 2975 35800 MARTIN 1250 15100 ALLEN 1600 19300 ... 14 rows selected.

Using Parentheses

SQL> SELECT ename, sal, 12*(sal+100) 2 FROM employees; ENAME SAL 12*(SAL+100) ---------- --------- ----------KING 5000 61200 BLAKE 2850 35400 CLARK 2450 30600 JONES 2975 36900 MARTIN 1250 16200 ... 14 rows selected.

Defining a Null Value NULL is UNASSIGNED Value.
SQL> SELECT 2 FROM ename, job, comm emp;

ENAME JOB COMM ---------- --------- --------KING PRESIDENT BLAKE MANAGER ... TURNER SALESMAN 0 ... 14 rows selected.

Null Values in Arithmetic Expr 

NULL as an operand will result NULL
SQL> select ename NAME, 12*sal+comm 2 from emp 3 WHERE ename='KING';

NAME 12*SAL+COMM ---------- ----------KING

Using the NVL Function

SQL> SELECT ename, sal, comm, (sal*12)+NVL(comm,0) 2 FROM emp; ENAME SAL COMM (SAL*12)+NVL(COMM,0) ---------- --------- --------- -------------------KING 5000 60000 BLAKE 2850 34200 CLARK 2450 29400 JONES 2975 35700 MARTIN 1250 1400 16400 ALLEN 1600 300 19500 ... 14 rows selected.

. AS Keyword [ Optional ] between the column name and the actual alias name Double Quotation Marks.Defining Column Alias The Heading name is replaced for the current SELECT Statement.

... sal salary 2 FROM employees. NAME SALARY ------------. SQL> SELECT ename "Name"... 2 sal*12 "Annual Salary" 3 FROM employees.--------.------------.Using Column Aliases SQL> SELECT ename AS name. Name Annual Salary ------------.

.Concatenation Operator (||) Concatenates the Columns of any data type. A Resultant column will be a Single column.

14 rows selected. ... Employees ------------------KINGPRESIDENT BLAKEMANAGER CLARKMANAGER JONESMANAGER MARTINSALESMAN ALLENSALESMAN .Using Concatenation Operator SQL> SELECT 2 FROM ename||job AS "Employees" employees.

Literal Character Strings Date and character literal values must be enclosed within single quotation marks. .

Using µDISTINCT¶ Clause ‡Eliminate duplicate rows by using the DISTINCT keyword SQL> SELECT DISTINCT deptno 2 FROM employees. DEPTNO --------10 20 30 .

Edit SQL statements .Summary SELECT FROM [DISTINCT] {*.} table..column[alias]..Execute SQL statements . Use SQL*Plus as an environment to: ..

Using 'Where' and 'Order By' Clauses .

Objectives Limit the rows required Arrange the rows in a particular order. .

column [alias]. The WHERE clause follows the FROM clause. . SELECT FROM [WHERE [DISTINCT] {*. .} table condition(s)]..Using µWHERE¶ Clause Specify the Selection of rows retrieved by the WHERE Clause..

--------CLERK 30 CLERK 20 CLERK 20 CLERK 10 . deptno 2 FROM employees 3 WHERE job='CLERK'. job.Using WHERE Clause SQL> SELECT ename. ENAME ---------JAMES SMITH ADAMS MILLER JOB DEPTNO --------.

. Default date format is 'DD-MON-YY' SQL> SELECT 2 FROM 3 WHERE ename. deptno emp ename = 'JAMES'. job.Character Strings and Dates Character / Dates are Represented by the Single Quotation Marks.

Comparison Operators Operator = > >= < <= <> Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to .

Using Comparison Operators SQL> SELECT ename.--------MARTIN 1250 1400 . ENAME SAL COMM ---------. comm 2 FROM employees 3 WHERE sal<=comm.--------. sal.

IN(list) LIKE IS NULL Meaning Between two values (inclusive) Match any of a list of values Match a character pattern Is a null value .AND..More Comparison Operators Operator BETWEEN ....

Using BETWEEN Operator SQL> SELECT 2 FROM 3 WHERE ename.--------MARTIN 1250 TURNER 1500 WARD 1250 ADAMS 1100 MILLER 1300 Lower limit Higher limit Used to compare between range of values. Values Specified are inclusive. ENAME SAL ---------. . sal employees sal BETWEEN 1000 AND 1500.

sal. SQL> SELECT 2 FROM 3 WHERE empno.Using IN Operator IN Operator to check with a List of Values.--------FORD 3000 7566 SMITH 800 7902 SCOTT 3000 7566 ADAMS 1100 7788 . ename. 7566. EMPNO --------7902 7369 7788 7876 ENAME SAL MGR ---------.--------. mgr emp mgr IN (7902. 7788).

. % ---------.Using LIKE Operator Like Keyword Does Wildcard Searches in Valid String Values.one character SQL> SELECT 2 FROM 3 WHERE ename emp ename LIKE 'S%'..zero or many characters _ ----------.

Using LIKE Operator ESCAPE identifier to search for "%" or "_". . SQL> SELECT 2 FROM 3 WHERE ENAME ---------JAMES WARD ename emp ename LIKE µ_A%µ.

Using IS NULL Operator To Check for Null Values . ENAME MGR ---------.--------KING . mgr emp mgr IS NULL. IS NULL is used. SQL> SELECT 2 FROM 3 WHERE ename.

Logical Operators Operator AND OR Meaning Returns TRUE if both component conditions are TRUE Returns TRUE if either component condition is TRUE Returns TRUE if the following condition is FALSE NOT .

--------CLERK 1100 CLERK 1300 EMPNO --------7876 7934 ENAME ---------ADAMS MILLER . job. SQL> 2 3 4 SELECT FROM WHERE AND empno.Using AND Operator AND requires both conditions to be TRUE. sal emp sal>=1100 job='CLERK'. JOB SAL --------. ename.

.--------. 14 rows selected. sal emp sal>=1100 job='CLERK'.Using OR Operator OR requires either condition to be TRUE. SQL> 2 3 4 SELECT FROM WHERE OR empno. job.---------. EMPNO ENAME JOB SAL --------. ename. ..--------7839 7698 7782 7566 7654 KING BLAKE CLARK JONES MARTIN PRESIDENT MANAGER MANAGER MANAGER SALESMAN 5000 2850 2450 2975 1250 .

'MANAGER'.'ANALYST'). ENAME ---------KING MARTIN ALLEN TURNER WARD JOB --------PRESIDENT SALESMAN SALESMAN SALESMAN SALESMAN .Using NOT Operator SQL> SELECT ename. job 2 FROM emp 3 WHERE job NOT IN ('CLERK'.

Rules of Precedence Order Evaluated 1 2 3 4 Operator All comparison operators NOT AND OR .

µORDER BY¶ Clause Sort rows specified by the order: ASC/DESC SQL> SELECT ename.. job.--------SMITH CLERK 20 17-DEC-80 ALLEN SALESMAN 30 20-FEB-81 . hiredate 2 FROM emp 3 ORDER BY hiredate. ..--------. deptno. ENAME JOB DEPTNO HIREDATE ---------. 14 rows selected.--------.

--------. . deptno.--------ADAMS CLERK 20 12-JAN-83 SCOTT ANALYST 20 09-DEC-82 MILLER CLERK 10 23-JAN-82 JAMES CLERK 30 03-DEC-81 FORD ANALYST 20 03-DEC-81 KING PRESIDENT 10 17-NOV-81 MARTIN SALESMAN 30 28-SEP-81 .--------. 14 rows selected. hiredate 2 FROM emp 3 ORDER BY hiredate DESC.. ENAME JOB DEPTNO HIREDATE ---------.Sorting in Descending Order SQL> SELECT ename. job..

EMPNO ENAME ANNSAL --------.Sorting the rows by Alias SQL> SELECT empno. sal*12 annsal 2 FROM emp 3 ORDER BY annsal.--------7369 SMITH 9600 7900 JAMES 11400 7876 ADAMS 13200 7654 MARTIN 15000 7521 WARD 15000 7934 MILLER 15600 7844 TURNER 18000 . 14 rows selected... ename.---------. .

--------KING 10 5000 CLARK 10 2450 MILLER 10 1300 FORD 20 3000 . deptno. ENAME DEPTNO SAL ---------.--------. 14 rows selected.. . SQL> SELECT ename. sal DESC..Sorting by Multiple Columns The order of ORDER BY list is the order of sort. sal 2 FROM emp 3 ORDER BY deptno.

alias} [ASC|DESC]].Summary SELECT FROM [WHERE [ORDER BY [DISTINCT] {*. .. . expr.} table condition(s)] {column. column [alias]..

SQL Functions .

Objectives Get an awareness of the Various SQL Functions available. Types of Functions in the SELECT Statement. Conversion functions .

Types of SQL Functions Functions MultipleMultiple-row functions SingleSingle-row functions .

.]) .. arg2.Single-Row Functions Act on every row as a result of every row. [arg1. function_name (column|expression.. Invoke Nested Levels.

Single-Row Functions Character SingleSingle-row functions Number Conversion Date .

Character Functions Character functions Character manipulation functions CONCAT SUBSTR LENGTH INSTR LPAD Case conversion functions LOWER UPPER INITCAP .

Case Conversion Functions Convert case for character strings Function UPPER('SQL Course') Result SQL COURSE LOWER('SQL Course') sql course INITCAP('SQLCourse') Sql Course .

name. and department number for employee Blake. deptno emp LOWER(ename) = 'blake'.--------7698 BLAKE 30 . ename. SQL> SELECT empno. no rows selected SQL> SELECT 2 FROM 3 WHERE empno.Case Conversion Functions Display the employee number. deptno 2 FROM emp 3 WHERE ename = 'blake'.---------. EMPNO ENAME DEPTNO --------. ename.

3) LENGTH('String') INSTR('String'.10.1.'*') Str 6 3 Result CONCAT('Good'.Character Functions Function SUBSTR('String'. 'String') GoodString ******5000 . 'r') LPAD(sal.

1. CONCAT (ename. job).------------.---------------MARTINSALESMAN 6 2 ALLENSALESMAN 5 1 TURNERSALESMAN 6 0 WARDSALESMAN 4 2 .JOB) LENGTH(ENAME) INSTR(ENAME. 'A') 3 FROM emp 4 WHERE SUBSTR(job. 2 INSTR(ename. ENAME ---------MARTIN ALLEN TURNER WARD CONCAT(ENAME.5) = 'SALES'. LENGTH(ename).'A') ------------------.Using Character Functions SQL> SELECT ename.

CEIL (123.CEIL (num): It returns the smallest integer greater than the given number.926.FLOOR (num): It returns the largest integer smaller than the given value FLOOR(123.456) 123 .92 .TRUNC: Truncates value to specified decimal .ROUND:Rounds value to specified decimal . 2) 45.456) 124 .93 45.MOD:Returns remainder of division .Number Functions . 300) 100 . 2) .MOD(1600.ROUND(45.926.TRUNC(45.

Default date format is DD-MON-YY. . DUAL is a dummy table used to view SYSDATE. SYSDATE is a Function which returns the System date and time.Working with Dates Stores date with Century.

. Add/Subtract hours to a date by dividing the number of hours by 24.Arithmetic with Dates Add/Subtract a Number to the Date.

Working with Date Functions FUNCTION MONTHS_BETWEEN ADD_MONTHS NEXT_DAY LAST_DAY ROUND TRUNC DESCRIPTION Number of months between two dates Add calendar months to date Next day of the date specified Last day of the month Round date Truncate date .

Conversion Functions Conversion Functions Explicit data type conversion Implicit data type conversion .

Oracle can automatically convert From VARCHAR2 or CHAR VARCHAR2 or CHAR NUMBER DATE To NUMBER DATE VARCHAR2 VARCHAR2 .Implicit Data type Conversion For assignments.

Explicit Data type Conversion TO_NUMBER TO_DATE NUMBER CHARACTER DATE TO_CHAR TO_CHAR .

µTO_CHAR¶ with Dates TO_CHAR(date. 'fmt') The format model: ‡ Enclosed in Single Quote Marks. . ‡ Include any Valid date format.

Date Format YYYY YEAR MM MONTH DY DAY Full year in numbers Year spelled out 2-digit value for month Full name of the month 3-letter abbreviation of the day of the week Full name of the day .

             AD.e.31) DDD day of year (between 1 and 366) DL long date format (eg: Saturday. MONDAY etc ) DD day of month (1 . A. Sun. BC.D. AM. Mon) HH / HH12 hour of the day (between 1 and 12) HH24 hour of the day (between 1 and 24) WW week of the year (between 1 and 52/53) MI minute (between 0 and 59) MM month (between 1 and 12) . December 30. A.D.day of week (between Sun -1 and Sat -7 ) DAY spelled name of day in full(i. SUNDAY. PM as indicators D .DATE & TIME formats. 2006) DS short date format (eg: 12/30/2006) DY abbreviated name of day in 3 letters(i.e..

            MONTH name of month (char(9)) MON abbreviated name of month (char(3)) Q quarter of year RM roman month (I .. XII ) SS Seconds (0-59) SSSSS seconds since midnight TS short time format TZD daylight saving information TZH time zone hour TZM Time zone minute W week of month (first week days 1 through 7 in month) YEAR -year will be spelled out.continued«. .DATE & TIME formats ..

DD "of" MONTH 12 of OCTOBER ddspth fourteenth .Date Format Elements  Time elements format the time portion of the date.  Number suffixes spell out numbers. HH24:MI:SS AM 15:45:32 PM  Add character strings by enclosing them in double quotation marks.

µTO_CHAR¶ with Numbers TO_CHAR(number. . 'fmt') To display a number value as a character. 9 0 $ L . Represents a number Forces a zero to be displayed Places a floating dollar sign Uses the floating local currency symbol Prints a decimal point Prints a thousand indicator .

'fmt']) SELECT TO_DATE('MAR 05 01'.'MON YY DD') FROM DUAL .TO_NUMBER & TO_DATE A character string to a number format using the TO_NUMBER function TO_NUMBER(char) A character string to a date format using the TO_DATE function TO_DATE(char[.

The return date is in the current century. The return date is in the century after the current one. 50-99 .µRR¶ Date Format Windowing Technique using the µRR¶ Date Format Current Year 1995 1995 2001 2001 Specified Date 27-OCT-95 27-OCT-17 27-OCT-17 27-OCT-95 RR Format 1995 2017 2017 1995 YY Format 1995 1917 2017 2095 If the specified two-digit year is 0-49 If two digits of the current year are 0-49 The return date is in the current century. 50-99 The return date is in the century before the current one.

'YEAR') ROUND('25-JUL TRUNC('25-JUL-95'.'MONTH') TRUNC('25-JUL TRUNC('25-JUL-95'.Using Date Functions  ROUND('25-JUL-95'.'YEAR') TRUNC('25-JUL- 01-AUG-95 01-AUG01-JAN-96 01-JAN01-JUL-95 01-JUL01-JAN-95 01-JAN- .'MONTH') ROUND('25-JUL ROUND('25-JUL-95'.

The arguments expr1 and expr2 can have any data type. then NVL returns expr2. . exp2) Purpose NVL lets you replace a null with a string in the results of a query.Using the NVL Function NVL( exp1.If expr1 is null. in which case the return value¶s data type is VARCHAR2 and is in the character set of expr1. then NVL returns expr1. If their data types are different. . unless expr1 is character data. If expr1 is not null.The data type of the return value is always the same as the data type of expr1. . . then Oracle converts expr2 to the data type of expr1 before comparing them.

Using the DECODE Function 

CASE or IF-THEN-ELSE statement

DECODE(col/expression, search1, result1 [, search2, result2,...,] [, default])

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_SALARY 7 FROM emp; JOB SAL REVISED_SALARY --------- --------- -------------PRESIDENT 5000 5000 MANAGER 2850 3420 MANAGER 2450 2940 ... 14 rows selected.

Nesting Functions 

Single-row functions can be nested to any number 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

Summary 

Perform calculations on data Modify individual data items Alter date formats for display Convert column data types

Using µJoins¶

Objectives 

Cartesian Join To access data from more than one Table using Equality and Non-Equality Condition Outer and Inner Join Join a table to itself

30 10 DEPT DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON MILLER ....... ...Data from Multiple Tables EMP EMPNO -----7839 7698 . EMPNO DEPTNO LOC ----.. 10 . -----. DEPTNO .-------7839 10 NEW YORK 7698 30 CHICAGO 7782 10 NEW YORK 7566 20 DALLAS 7654 30 CHICAGO 7499 30 CHICAGO .. 14 rows selected...------. 7934 ENAME ----KING BLAKE ...

table2.What Is a Join? A JOIN Basically involves more than one Table to interact with.column2. . Ambiguous Column names are identified by the Table name. Where clause specifies the JOIN Condition.column. SELECT FROM WHERE table1.column table1. table2 table1.column1 = table2.

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 .

.. KING RESEARCH BLAKE RESEARCH ... -----.... ³Cartesian product: 14*4=56 rows´ ENAME DNAME --------------KING ACCOUNTING BLAKE ACCOUNTING . 30 10 DEPT (4 rows) DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON MILLER ... 7934 ENAME ----KING BLAKE .Cartesian Product EMP (14 rows) EMPNO -----7839 7698 ... DEPTNO .... 56 rows selected.. 10 .. .

Types of Joins Inner Join Equi Join Non Equi Join Self Join Outer join Left Outer Join Right Outer Join Full Outer Join .

Inner Joins An inner join (sometimes called a "simple join") is a join of two or more tables that returns only those rows that satisfy the join condition .

What Is an Equijoin? An equijoin is a join with a join condition containing an equality operator. An equijoin combines rows that have equivalent values for the specified columns. .

------7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20 .What Is an Equijoin? EMP EMPNO ENAME DEPTNO -----. LOC -------NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO DALLAS DALLAS . DEPT DEPTNO ------10 30 10 20 30 30 30 30 30 20 20 .------... 14 rows DNAME ---------ACCOUNTING SALES ACCOUNTING RESEARCH SALES SALES SALES SALES SALES RESEARCH RESEARCH selected. 14 rows selected...

.-----.-----. .loc emp. emp..empno.--------7839 KING 10 10 NEW YORK 7698 BLAKE 30 30 CHICAGO 7782 CLARK 10 10 NEW YORK 7566 JONES 20 20 DALLAS .deptno=dept.-----.Retrieving Rows: Equijoin SQL> SELECT 2 3 FROM 4 WHERE emp. EMPNO ENAME DEPTNO DEPTNO LOC ----. dept emp. emp. dept.deptno.deptno. 14 rows selected.ename.deptno. dept.

deptno. dept d 4 WHERE e.empno.deptno. e. SQL> SELECT e. SQL> SELECT emp.Using Table Aliases Simplify queries by using table aliases.deptno.deptno.ename.deptno. 2 dept.ename.empno. emp. 2 d. d. e.loc 3 FROM emp e.loc 3 FROM emp.deptno. dept 4 WHERE emp.deptno=d.deptno=dept. emp. dept. .

9 rows selected. .------101 610 102 611 104 612 106 601 102 602 106 604 ITEM 106 605 ORDID ITEMID ... . -----.------21 rows selected.. 610 3 611 1 612 1 601 1 602 1 .. 64 rows selected.Joining More Than Two Tables CUSTOMER NAME CUSTID ---------------JOCKSPORTS 100 TKB SPORT SHOP 101 VOLLYRITE 102 JUST TENNIS 103 K+T SPORTS 105 SHAPE UP 106 WOMENS SPORTS 107 . ORD CUSTID ORDID ------.....

.Non-Equijoins An non-equijoin is a join with a join condition containing an non-equality operator. An non-equijoin combines rows that have non-equivalent values for the specified columns.

----.Non-Equijoins EMP EMPNO ENAME SAL -----. 14 rows selected. SALGRADE GRADE LOSAL HISAL ----...-----1 700 1200 2 1201 1400 3 1401 2000 4 2001 3000 5 3001 9999 ³salary in the EMP table is between low salary and high salary in the SALGRADE table´ .------.-----7839 KING 5000 7698 BLAKE 2850 7782 CLARK 2450 7566 JONES 2975 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 .

s.Retrieving Rows:Non-Equijoin SQL> 2 3 4 SELECT FROM WHERE BETWEEN e.--------. 14 rows selected. ENAME SAL GRADE ---------. salgrade s e.grade emp e..sal.hisal.losal AND s.ename. .sal s.. e.--------JAMES 950 1 SMITH 800 1 ADAMS 1100 1 .

. Oracle combines and returns rows of the table that satisfy the join condition.Self Joins A self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by table aliases that qualify column names in the join condition. To perform a self join.

Self Joins EMP (WORKER) EMPNO ----7839 7698 7782 7566 7654 7499 ENAME -----KING BLAKE CLARK JONES MARTIN ALLEN MGR ---7839 7839 7839 7698 7698 EMP (MANAGER) EMPNO ENAME ----.-------7839 7839 7839 7698 7698 KING KING KING BLAKE BLAKE "MGR in the WORKER table is equal to EMPNO in the MANAGER table" .

emp manager 3 WHERE worker..ename 2 FROM emp worker. 13 rows selected. ..ENAME||'WORKSFOR'||MANAG ------------------------------BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE .empno.ename||' works for '||manager.Joining a Table to Itself SQL> SELECT worker.mgr = manager. WORKER.

use the FULL [OUTER] JOIN syntax in the FROM clause. extended with nulls if they do not satisfy the join condition (a full outer join). n To write a query that performs an outer join and returns all rows from A and B. use the LEFT [OUTER] JOIN syntax in the FROM clause. To write a query that performs an outer join of tables A and B and returns all rows from A (a left outer join). Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions. or apply the outer join operator (+) to all columns of A in the join condition in the WHERE clause.Joins . or apply the outer join operator (+) to all columns of B in the join condition in the WHERE clause. An outer join returns all rows that satisfy the join condition and also returns some or all of those rows from one table for which no rows from the other satisfy the join condition. which do not apply to the FROM clause join syntax: n You cannot specify the (+) operator in a query block that also contains FROM clause join syntax. use the RIGHT [OUTER] JOIN syntax in the FROM clause.Outer Joins An outer join extends the result of a simple join. For all rows in A that have no matching rows in B. Oracle Corporation recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. n To write a query that performs an outer join of tables A and B and returns all rows from B (a right outer join). Oracle returns null for any select list expressions containing columns of B. For all rows in B that have no matching rows in A. Oracle returns null for any select list expressions containing columns of A.

40 DNAME ---------ACCOUNTING SALES ACCOUNTING RESEARCH OPERATIONS No employee in the OPERATIONS department .... DEPTNO -----10 30 10 20 DEPT DEPTNO -----10 30 10 20 .Outer Joins EMP ENAME ----KING BLAKE CLARK JONES ..

column(+). SELECT table.column. . Outer join operator is the plus sign (+).column FROM table1.column. table. table.column FROM table1. table2 WHERE table1.Outer Joins To see also the rows that do not usually meet the join condition. table2 WHERE table1.column = table2.column(+) = table2. SELECT table.column.

dept d e.Using Outer Joins SQL> 2 3 4 SELECT FROM WHERE ORDER BY e. 40 OPERATIONS 15 rows selected.--------.ename.deptno e.deptno(+) = d.. . d.deptno. ENAME DEPTNO DNAME ---------.dname emp e.deptno. d..------------KING 10 ACCOUNTING CLARK 10 ACCOUNTING .

column table1. Types of Joins  Equijoins  Non. table2 table1.Equijoins  Outer Joins  Self Joins .column1 = table2. table2.column.column2.Summary SELECT FROM WHERE table1.

Using Group Functions .

Objectives  Group Functions  GROUP BY clause  HAVING Clause. .

What Are Group Functions? Operate on sets of rows to give one result per group.--------10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 3000 20 2975 30 1600 30 2850 30 1250 30 950 30 1500 30 1250 ³maximum salary in the EMP table´ MAX(SAL) --------5000 . EMP DEPTNO SAL --------.

Common Group Functions - AVG COUNT MAX MIN STDDEV SUM VARIANCE .

group_function(column) table condition] column]. .Using Group Functions SELECT FROM [WHERE [ORDER BY column.

Using the COUNT Function SQL> SELECT 2 FROM 3 WHERE COUNT(*) --------6 COUNT(*) emp deptno = 30. .

.Using the COUNT Function COUNT(expr) returns the number of nonnull values in the given column. SQL> SELECT 2 FROM 3 WHERE COUNT(COMM) ----------4 COUNT(comm) emp deptno = 30.

Group Functions & Null Values Group functions ignore null values in the column. SQL> SELECT AVG(comm) 2 FROM emp. AVG(COMM) --------550 .

14286 . SQL> SELECT AVG(NVL(comm.0)) 2 FROM emp. AVG(NVL(COMM.NVL with Group Functions The NVL function forces group functions to include null values.0)) ---------------157.

Creating Groups of Data EMP DEPTNO SAL --------.6667 .--------10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 3000 20 2975 30 1600 30 2850 30 1250 30 950 30 1500 30 1250 2916.6667 ³average DEPTNO AVG(SAL) salary ------.--------in EMP 2175 10 2916.6667 table 20 2175 for each department´ 30 1566.6667 1566.

group_function(column) table condition] group_by_expression] column].Using µGROUP BY¶ Clause SELECT FROM [WHERE [GROUP BY [ORDER BY column. . Modularize rows in a table into smaller groups by using the GROUP BY clause.

6667 .Using GROUP BY Clause Columns that are not a part of the Group Functions should be included in the Group by clause.--------10 2916. SQL> SELECT deptno. DEPTNO AVG(SAL) --------. AVG(sal) 2 FROM emp 3 GROUP BY deptno.6667 20 2175 30 1566.

--------DEPTNO -------10 10 10 20 20 20 30 30 30 JOB CLERK MANAGER PRESIDENT ANALYST CLERK MANAGER CLERK MANAGER SALESMAN SUM(SAL) 1300 2450 5000 6000 1900 2975 950 2850 5600 --------.Grouping by Multiple Columns EMP DEPTNO JOB 10 MANAGER 10 PRESIDENT 10 CLERK 20 CLERK 20 CLERK 20 ANALYST 20 ANALYST 20 MANAGER 30 SALESMAN 30 MANAGER 30 SALESMAN 30 CLERK 30 SALESMAN 30 SALESMAN SAL 2450 5000 1300 800 1100 3000 3000 2975 1600 2850 1250 950 1500 1250 --------.--------- ³sum salaries in the EMP table for each job.--------. grouped by department´ .

DEPTNO JOB SUM(SAL) --------.. job. .. 9 rows selected.GROUP BY: Multiple Columns SQL> SELECT deptno. sum(sal) 2 FROM emp 3 GROUP BY deptno.--------10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 ANALYST 6000 20 CLERK 1900 . job.--------.

SELECT deptno.Illegal Queries Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause. SQL> SELECT 2 FROM deptno. COUNT(ename) * ERROR at line 1: ORA-00937: not a single-group group function . COUNT(ename) emp.

SELECT FROM WHERE GROUP BY deptno.Illegal Queries  Group Functions cannot be placed in the where clause. SQL> 2 3 4 WHERE AVG(sal) > 2000 * ERROR at line 3: ORA-00934: group function is not allowed here . AVG(sal) emp AVG(sal) > 2000 deptno.

--------- 2850 .--------- 5000 ³maximum salary per department greater than $2900´ DEPTNO 10 20 MAX(SAL) 5000 3000 3000 --------.Segregating Group Results EMP DEPTNO 10 10 10 20 20 20 20 20 30 30 30 30 30 30 SAL 2450 5000 1300 800 1100 3000 3000 2975 1600 2850 1250 950 1500 1250 --------.

SELECT FROM [WHERE [GROUP BY [HAVING [ORDER BY column. . group_function table condition] group_by_expression] group_condition] column].Using the µHAVING¶ Clause HAVING clause is to restrict groups Groups satisfying the HAVING condition are displayed.

Using HAVING Clause SQL> 2 3 4 SELECT FROM GROUP BY HAVING deptno. DEPTNO MAX(SAL) --------.--------10 5000 20 3000 . max(sal) emp deptno max(sal)>2900.

Using HAVING Clause

SQL> 2 3 4 5 6

SELECT FROM WHERE GROUP BY HAVING ORDER BY

job, SUM(sal) PAYROLL emp job NOT LIKE 'SALES%' job SUM(sal)>5000 SUM(sal);

JOB PAYROLL --------- --------ANALYST 6000 MANAGER 8275

Nesting Group Functions 
Display the maximum average salary.

SQL> SELECT max(avg(sal)) 2 FROM emp 3 GROUP BY deptno;

MAX(AVG(SAL)) ------------2916.6667

Summary
SELECT FROM [WHERE [GROUP BY [HAVING [ORDER BY column, group_function (column) table condition] group_by_expression] group_condition] column]; 

Order of evaluation of the clauses:

‡ WHERE clause ‡ GROUP BY clause ‡ HAVING clause

Subqueries

Objectives 

Describe the types of problems that subqueries can solve Define subqueries List the types of subqueries Write Single-row , Multiple-row ,Inline views and Multiple column subqueries

Subquery to Solve a Problem 
´Who has a salary greater than Jones·s?µ

Main Query

?

³Which employees have a salary greater than Jones¶s salary?´
Subquery

?

³What is Jones¶s salary?´

The result of the subquery is used by the main query (outer query). The subquery (inner query) executes once before the main query. .Subqueries SELECT FROM WHERE select_list table expr operator (SELECT FROM select_list table).

Using a Subquery SQL> SELECT ename 2 FROM employee 2975 3 WHERE sal > 4 (SELECT sal 5 FROM employee 6 WHERE empno=7566). ENAME ---------KING FORD SCOTT .

Use single-row operators with single-row subqueries. .Guidelines for Subqueries Enclose subqueries in parentheses. Use multiple-row operators with multiplerow subqueries. Place subqueries on the right side of the comparison operator. Do not add an ORDER BY clause to a subquery.

Types of Subqueries Single-row subquery Main query Subquery returns CLERK  Multiple-row subquery Main query Subquery returns  Inline Views From Clause of Main Query Subquery CLERK MANAGER returns  Multiple-column subquery Main query Subquery returns SingleSingle-row MultipleMultiple-row MultipleMultiple-column CLERK 7900 MANAGER 7698 .

Single-Row Subqueries Return only one row Use single-row comparison operators Operator = > >= < <= <> Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to .

ENAME JOB ---------. job employee job = (SELECT FROM WHERE sal > (SELECT FROM WHERE CLERK job employee empno = 7369) 1100 sal employee empno = 7876).--------MILLER CLERK .Single-Row Subqueries SQL> 2 3 4 5 6 7 8 9 10 SELECT FROM WHERE AND ename.

--------. sal employee sal = (SELECT FROM 800 MIN(sal) employee).Group Functions in Subquery SQL> SELECT 2 FROM 3 WHERE 4 5 ename. job.--------SMITH CLERK 800 . ENAME JOB SAL ---------.

HAVING with Subqueries The Oracle Server executes subqueries first. MIN(sal) employee deptno MIN(sal) > (SELECT FROM WHERE 800 MIN(sal) employee deptno = 20). SQL> 2 3 4 5 6 7 SELECT FROM GROUP BY HAVING deptno. .

ERROR: ORA-01427: single-row subquery returns more than one row no rows selected . ename 2 FROM employee 3 WHERE sal = 4 (SELECT 5 FROM 6 GROUP BY MIN(sal) employee deptno).What Is Wrong ? SQL> SELECT empno.

job 2 FROM employee 3 WHERE job = 4 (SELECT job 5 FROM employee 6 WHERE ename='SMYTHE'). no rows selected .Will This Statement Work? SQL> SELECT ename.

Multiple-Row Subqueries Return more than one row Use multiple-row comparison operators Operator IN ANY 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 ALL .

JOB --------SALESMAN SALESMAN EMPNO --------7654 7521 ENAME ---------MARTIN WARD .ANY: Multiple-Row Subqueries SQL> 2 3 4 5 6 7 SELECT FROM WHERE AND empno. ename. job 1300 1100 employee 800 sal < ANY 950 (SELECT sal FROM employee WHERE job = 'CLERK') job <> 'CLERK'.

6667 sal > ALL (SELECT FROM GROUP BY JOB --------PRESIDENT MANAGER ANALYST ANALYST 1566.6667 avg(sal) employee deptno). ENAME ---------KING JONES FORD SCOTT . ename. job 2175 employee 2916.ALL: Multiple-Row Subqueries SQL> SELECT 2 FROM 3 WHERE 4 5 6 EMPNO --------7839 7566 7902 7788 empno.

Multiple-Column Subqueries Main query MANAGER 10 Subquery SALESMAN MANAGER CLERK 30 10 20 Main query compares MANAGER 10 to Values from a multiple-row and multiplemultiplemultiple-column subquery SALESMAN 30 MANAGER 10 CLERK 20 .

SQL> SELECT 2 FROM 3 WHERE 4 5 6 ename.Multiple-Column Subqueries Display the name. sal. dept.-1) FROM employee WHERE deptno = 30). no. and commission of any employee whose salary and commission matches both the commission and salary of any employee in department 30. salary. . NVL(comm. NVL(comm. comm employee (sal. deptno.-1)) IN (SELECT sal.

salavg employee a.6667 JONES 2975 20 2175 SCOTT 3000 20 2175 .sal > b.deptno a.Subquery in FROM Clause SQL> 2 3 4 5 6 SELECT FROM WHERE AND a.ename.--------.deptno = b.sal. a.salavg. ENAME SAL DEPTNO SALAVG ---------. 6 rows selected. a. b.--------.. avg(sal) salavg FROM employee GROUP BY deptno) b a.---------KING 5000 10 2916.deptno.. . (SELECT deptno.

deptno = b. SELECT dname.deptno GROUP BY dname). dept b WHERE a. DEPT_TOTAL ---------10875 DNAME --------------RESEARCH .sum(sal) as dept_total FROM emp a .dept_total FROM summary WHERE dept_total > (SELECT sum(dept_total)*1/3 FROM summary) ORDER BY dept_total desc.Subquery in WITH Clause SQL> 2 3 4 5 6 7 8 9 10 WITH summary AS (SELECT dname.

Non-Correlated  SELECT dept.name FROM dept WHERE dept.id NOT IN ( SELECT dept_id FROM emp WHERE dept_id IS NOT NULL) .

deptno = deptno) / .dname FROM dept WHERE EXISTS (SELECT deptno FROM emp WHERE emp.Correlated SELECT dept.

SAL < B.Correlated Subqueries  Query to diplay name of highest salary taker. ENAME FROM EMP A WHERE 1 > ( SELECT COUNT(*) FROM EMP B WHERE A.  SELECT EMPNO.SAL) .

ROW subquery returns more than one column. A multiple-column subquery can also be used in the FROM clause of a SELECT statement.Summary Single row subqueries A multiple. .

DML Statements .

Objectives Insert rows into a table Update rows in a table Delete rows from a table Controlling the Transactions .

Modify existing rows in a table .Remove existing rows from a table A transaction consists of a collection of DML statements that form a logical unit of work.Add new rows to a table . .Data Manipulation Language A DML statement is executed when you: .

])] (value [.. .. value.]). column.. Only one row is inserted at a time with this syntax.INSERT Statement Add new rows to a table by using the INSERT statement. INSERT INTO VALUES table [(column [..

'DEVELOPMENT'. ‡ Optionally list the columns in the INSERT clause.Inserting New Rows ‡ Insert a new row containing values for each column. 'DETROIT'). dname. ‡ Enclose character and date values within SQL> INSERT INTO department single quotation marks. ‡ List values in the default order of the columns in the table. 1 row created. (deptno. loc) 2 VALUES (50. .

'MIS'). SQL> INSERT INTO 2 VALUES 1 row created. department (70. Explicit method: Specify the NULL keyword.Insert Rows with Null Values Implicit method: Omit the column from the column list. dname ) (60. . NULL). department (deptno. 'FINANCE'. SQL> INSERT INTO 2 VALUES 1 row created.

10). SYSDATE. comm. job. mgr. USER. 'SALESMAN'. 2000. SQL> INSERT INTO 2 3 4 VALUES 5 6 1 row created. 7782. NULL. employee (empno. .Inserting Special Values The SYSDATE and USER function records the current date and time. deptno) (7196. sal. ename. hiredate.

------. SQL> INSERT INTO 2 VALUES 3 4 1 row created.7782.'SALESMAN'.'AROMANO'.---.97'. NULL. 'MON DD.-------. employee (2296.Inserting Specific Date Values Add a new employee. EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ----.-----2296 AROMANO SALESMAN 7782 03-FEB-97 1300 10 . YY').---.---. 10). TO_DATE('FEB 3. 1300.--------. Verify your addition.

loc) (&department_id. '&location'). Enter value for department_id: 80 Enter value for department_name: EDUCATION Enter value for location: ATLANTA 1 row created. '&department_name'. dname. SQL> INSERT INTO 2 VALUES 3 DEPARTMENT(deptno.Substitution Variables (&) Create an interactive script by using SQL*Plus substitution parameters. .

(SAL+NVL(COMM.Multiple table insert  Insert all the employees details who are managers into bonus and tax for further manipulation  INSERT ALL .COMM FROM EMP .ANNUAL_SAL) .VALUES(EMPNO. GROSS_INCOME) .SAL*12) .SELECT EMPNO.SAL.VALUES(EMPNO.INTO TAX(EMPNO.INTO BONUS (EMPNO.WHERE JOB=¶MANAGER· .0))*12) .

SAL*12) WHEN JOB=¶SALESMAN· then INTO BONUS(EMPNO.job.0))*12) SELECT EMPNO. (SAL+NVL(COMM.SAL.COMM FROM EMP .ANN_SAL) VALUES(EMPNO.ANN_SAL) VALUES(EMPNO.MULTIPLE TABLE CONDITIONAL INSERT         INSERT ALL WHEN JOB=¶CLERK· then INTO BONUS(EMPNO.

SQL> INSERT INTO managers(id. 3 rows created. Match the number of columns in the INSERT clause to those in the subquery. . salary. name. hiredate) 2 SELECT empno. ename. hiredate 3 FROM employee 4 WHERE job = 'MANAGER'. Do not use the VALUES clause. sal.Copying from Another Table Write your INSERT statement with a subquery.

. UPDATE SET  [WHERE table column = value [. Update more than one row at a time.UPDATE Statement Modify existing rows with the UPDATE statement. if required. column = value] condition].

. 14 rows updated. SQL> UPDATE employee 2 SET deptno = 20.Updating Rows in a Table All rows in the table are modified if you omit the WHERE clause.

UPDATE emp * ERROR at line 1: ORA-02291: integrity constraint (USR.EMP_DEPTNO_FK) violated .parent key not found .Updating Rows: Integrity Constraint Error SQL> UPDATE 2 SET 3 WHERE employee deptno = 55 deptno = 10.

DELETE [FROM] [WHERE table condition].DELETE Statement You can remove existing rows from a table by using the DELETE statement. .

SQL> DELETE FROM 2 WHERE 1 row deleted. . department dname = 'DEVELOPMENT'. department. SQL> DELETE FROM 4 rows deleted.Deleting Rows from a Table Specific row or rows are deleted when you specify the WHERE clause. All rows in the table are deleted if you omit the WHERE clause.

child record found . DELETE FROM dept * ERROR at line 1: ORA-02292: integrity constraint (USR.Deleting Rows: Integrity Constraint Error SQL> DELETE FROM 2 WHERE department deptno = 10.EMP_DEPTNO_FK) violated .

Summary Statement INSERT UPDATE DELETE COMMIT SAVEPOINT ROLLBACK Description Adds a new row to the table Modifies existing rows in the table Removes existing rows from the table Makes all pending changes permanent Allows a rollback to the savepoint marker Discards all pending data changes .

DDL Statements .

rename. and truncate tables .Objectives ‡ Describe the main database objects ‡ Create tables ‡ Describe the data types that can be used when specifying column definition ‡ Alter table definitions ‡ Drop.

composed of rows and columns View Logically represents subsets of data from one or more tables Sequence Index Synonym Generates primary key values Improves the performance of some queries Gives alternative names to objects .Database Objects Object Table Description Basic unit of storage.

and # ‡ Must not duplicate the name of another object owned by the same user ‡ Must not be an Oracle Server reserved word . _. a²z. $.Naming Conventions ‡ Must begin with a letter ‡ Can be 1²30 characters long ‡ Must contain only A²Z. 0²9.

A storage area CREATE TABLE [schema. ‡ You specify: .CREATE TABLE Statement ‡ You must have : . and column size .Table name .Column name.CREATE TABLE privilege . column data type.]table (column data type [DEFAULT expr].

.Reference other User¶s Tables ‡ Tables belonging to other users are not in the user·s schema. ‡ You should use the owner·s name as a prefix to the table.

« hiredate DATE DEFAULT SYSDATE. . or SQL function.The DEFAULT Option ‡ Specify a default value for a column during an insert. ‡ Illegal values are another column¶s name or pseudo column. ‡ The default data type must match the column data type. « ‡ Legal values are literal value. expression.

SQL> DESCRIBE department Name Null? --------------------------. ‡ Confirm table creation. Table created. SQL> CREATE TABLE department 2 (deptno NUMBER(2). 4 loc VARCHAR2(13)).Creating Tables ‡ Create the table.-------DEPTNO NOT NULL DNAME LOC Type --------NUMBER(2) VARCHAR2(14) VARCHAR2(13) . 3 dname VARCHAR2(14).

‡ View tables. .Querying the Data Dictionary ‡ Describe tables owned by the user. SQL> SELECT 2 FROM * user_tables. SQL> SELECT 2 FROM DISTINCT object_type user_objects. synonyms. ‡ View distinct object types owned by the user. views. SQL> SELECT 2 FROM * user_catalog. and sequences owned by the user.

s) DATE LONG CLOB RAW and LONG RAW BLOB BFILE Description Variable-length character data Fixed-length character data Variable-length numeric data Date and time values Variable-length character data up to 2 gigabytes Single-byte character data up to 4 gigabytes Raw binary data Binary data up to 4 gigabytes Binary data stored in an external file. up to 4 gigabytes .Data types Data type VARCHAR2(size) CHAR(size) NUMBER(p.

The scales can range from -84 to 127.from January 1. 4712 BC to December 31.4000 bytes  NUMBER.  LONG.  DATE. 9999 AD.MAXIMUM SIZE  CHAR.The precision p can range from 1 to 38.2 Gigabytes  CLOB/BLOB ± 4GB .

. .)] AS subquery. ‡ Define columns with column names and default values.Create Table Using Subquery ‡ Create a table and insert rows by combining the CREATE TABLE statement and AS subquery option. ‡ Match the number of specified columns to the number of subquery columns.. CREATE TABLE table [column(. column.

Create Table Using Subquery SQL> CREATE TABLE dept30 2 AS 3 SELECT empno. Table created.-------EMPNO NOT NULL ENAME ANNSAL HIREDATE Type ----NUMBER(4) VARCHAR2(10) NUMBER DATE . SQL> DESCRIBE dept30 Name Null? ---------------------------. sal*12 ANNSAL. ename. hiredate 4 FROM employee 5 WHERE deptno = 30.

..). .).. ALTER TABLE table DROP column column_name. ALTER TABLE table MODIFY (column data type [DEFAULT expr] [..ALTER TABLE Statement ‡ Add a new column ‡ Modify an existing column ‡ Drop an existing column. column data type]. ‡ Define a default value for the new column ALTER TABLE table ADD (column data type [DEFAULT expr] [. column data type].

..-------BLAKE 34200 MARTIN 15000 ALLEN 19200 TURNER 18000 New column HIREDATE 01-MAY-81 28-SEP-81 20-FEB-81 08-SEP-81 JOB ³«add a new column into DEPT30 table«´ DEPT30 EMPNO -----7698 7654 7499 7844 ..Adding a Column DEPT30 EMPNO -----7698 7654 7499 7844 ..-------BLAKE 34200 MARTIN 15000 ALLEN 19200 TURNER 18000 HIREDATE 01-MAY-81 28-SEP-81 20-FEB-81 08-SEP-81 JOB . ENAME ANNSAL ---------. ENAME ANNSAL ---------.

SQL> ALTER TABLE dept30 2 ADD (job VARCHAR2(9)).---------. EMPNO ENAME ANNSAL HIREDATE JOB --------..---7698 BLAKE 34200 01-MAY-81 7654 MARTIN 15000 28-SEP-81 7499 ALLEN 19200 20-FEB-81 7844 TURNER 18000 08-SEP-81 . 6 rows selected. .Adding a Column ‡ You use the ADD clause to add columns. Table altered.. ‡ The new column becomes the last column.--------.--------.

. ALTER TABLE dept30 MODIFY (ename VARCHAR2(15)). ‡ A change to the default value affects only subsequent insertions to the table. Table altered. and default value. size.Modifying a Column ‡ You can change a column's data type.

Set Column Unused SYNTAX: ALTER TABLE table_name SET UNUSED COLUMN column_name .

Table altered. ALTER TABLE dept30 DROP COLUMN ename. Table altered. Table altered. . ‡ You can ignore the column by set unused column SQL>ALTER TABLE dept30 set unused column ename. SQL> ALTER TABLE dept30 drop unused columns.Dropping a Column ‡ You can remove a column and its contents entirely from the table.

‡ You cannot roll back this statement.Dropping a Table ‡ All data and structure in the table is deleted. . Table dropped. ‡ Any pending transactions are committed. ‡ All indexes are dropped. SQL> DROP TABLE dept30.

sequence. Table renamed. view. ‡ You must be the owner of the object.Rename an Object ‡ To change the name of a table. . or synonym. SQL> RENAME dept TO department. you execute the RENAME statement.

Comment created. ALL_COL_COMMENTS USER_COL_COMMENTS ALL_TAB_COMMENTS USER_TAB_COMMENTS . SQL> COMMENT ON TABLE employee 2 IS 'Employee Information'. ‡ Comments can be viewed through the data dictionary views.Adding Comments to a Table ‡ You can add comments to a table or column by using the COMMENT statement.

Constraints .

FOREIGN KEY . .NOT NULL .CHECK ‡Query the USER_CONSTRAINTS table to view all constraint definitions and names.UNIQUE key .Objectives ‡Create the following types of constraints: .PRIMARY KEY .

FOREIGN KEY .PRIMARY KEY .CHECK .NOT NULL .What Are Constraints? ‡ Constraints enforce rules at the table level. ‡ The following constraint types are valid in Oracle: .Constraints prevent the deletion of a table if there are dependencies.UNIQUE Key .

Constraint Guidelines ‡ Name a constraint or the Oracle Server will generate a name by using the SYS_Cn format.At the same time as the table is created . . ‡ Create a constraint: . ‡ View a constraint in the data dictionary.After the table has been created ‡ Define a constraint at the column or table level.

CONSTRAINT emp_empno_pk PRIMARY KEY (EMPNO)).Defining Constraints CREATE TABLE [schema. ename VARCHAR2(10). « deptno NUMBER(7.]table (column data type [DEFAULT expr] [column_constraint].2) NOT NULL. CREATE TABLE employee( empno NUMBER(4). . « [table_constraint]).

).Defining Constraints ‡ Column constraint level column [CONSTRAINT constraint_name] constraint_type... [CONSTRAINT constraint_name] constraint_type (column. .. . ‡ Table constraint level column...

.. COMM DEPTNO 10 30 10 20 NOT NULL constraint (no row may contain a null value for this column) Absence of NOT NULL constraint (any row can contain null for this column) NOT NULL constraint ...The NOT NULL Constraint Ensures that null values are not permitted for the column EMP EMPNO ENAME 7839 7698 7782 7566 . KING BLAKE CLARK JONES JOB PRESIDENT MANAGER MANAGER MANAGER .

The NOT NULL Constraint Defined at the column level SQL> CREATE TABLE 2 empno 3 ename 4 job 5 mgr 6 hiredate 7 sal 8 comm 9 deptno employee( NUMBER(4). . NUMBER(7.2). VARCHAR2(9).2) NOT NULL). NUMBER(4). NUMBER(7. NUMBER(7.2). VARCHAR2(10) NOT NULL. DATE.

The UNIQUE Key Constraint UNIQUE key constraint DEPARTMENT DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON Insert into 50 SALES 60 DETROIT BOSTON Not allowed (DNAMESALES already exists) Allowed .

VARCHAR2(14). dept_dname_uk UNIQUE(dname)). VARCHAR2(13). .The UNIQUE Key Constraint Defined at either the table level or the column level SQL> CREATE TABLE 2 deptno 3 dname 4 loc 5 CONSTRAINT department( NUMBER(2).

PRIMARY KEY Constraint DEPARTMENT PRIMARY KEY DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON Insert into 20 MARKETING FINANCE DALLAS NEW YORK Not allowed (DEPTNO20 already exists) Not allowed (DEPTNO is null) .

PRIMARY KEY Constraint Defined at either the table level or the column level SQL> CREATE TABLE 2 deptno 3 dname 4 loc 5 CONSTRAINT 6 CONSTRAINT department( NUMBER(2). VARCHAR2(14). VARCHAR2(13). . dept_dname_uk UNIQUE (dname). dept_deptno_pk PRIMARY KEY(deptno)).

.... 200 200 9 DNAME ---------ACCOUNTING RESEARCH LOC -------NEW YORK DALLAS EMPLOYEE EMPNO ENAME 7839 KING 7698 BLAKE .... COMM DEPTNO 10 30 Not allowed (DEPTNO9 does not exist in the DEPT table) Allowed FOREIGN KEY ... . .FOREIGN KEY Constraint DEPARTMENT PRIMARY KEY DEPTNO -----10 20 . JOB PRESIDENT MANAGER Insert into 7571 FORD 7571 FORD MANAGER MANAGER ..

10 CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno) 11 REFERENCES dept (deptno)). 4 job VARCHAR2(9). 7 sal NUMBER(7. 8 comm NUMBER(7.2) NOT NULL.2).2). 9 deptno NUMBER(7. . 6 hiredate DATE. 3 ename VARCHAR2(10) NOT NULL.FOREIGN KEY Constraint Defined at either the table level or the column level SQL> CREATE TABLE employee( 2 empno NUMBER(4). 5 mgr NUMBER(4).

FOREIGN KEY Constraint Keywords : ‡ FOREIGN KEY ‡ Defines the column in the child table at the table constraint level ‡ REFERENCES ‡ Identifies the table and column in the parent table ‡ ON DELETE CASCADE ‡ Allows deletion in the parent table and deletion of the dependent rows in the child table .

and USERENV functions . .. and ROWNUM .Queries that refer to other values in other rows .Calls to SYSDATE.. UID.The CHECK Constraint ‡ Defines a condition that each row must satisfy ‡ Expressions that are not allowed: .... USER. NEXTVAL. deptno NUMBER(2). CONSTRAINT emp_deptno_ck CHECK (DEPTNO BETWEEN 10 AND 99).References to pseudo columns CURRVAL..

‡ Add or drop. a constraint ‡ Enable or disable constraints ‡ Add a NOT NULL constraint by using the MODIFY clause .Adding a Constraint ALTER TABLE table ADD [CONSTRAINT constraint] type (column). but not modify.

SQL> ALTER TABLE employee 2 ADD CONSTRAINT emp_mgr_fk 3 FOREIGN KEY(mgr) REFERENCES emp(empno).Adding a Constraint Add a FOREIGN KEY constraint to the EMP table indicating that a manager must already exist as a valid employee in the EMP table. Table altered. .

‡ Remove the PRIMARY KEY constraint on the DEPT table and drop the associated FOREIGN KEY constraint on the EMP. EMP emp_mgr_fk.DEPTNO column. SQL> ALTER TABLE DEPT 2 DROP PRIMARY KEY CASCADE.Dropping a Constraint ‡ Remove the emp_mgr_fk constraint from the EMP table. . SQL> ALTER TABLE 2 DROP CONSTRAINT Table altered. Table altered.

.Disabling Constraints ‡ Execute the DISABLE clause of the ALTER TABLE statement to deactivate an integrity constraint. SQL> ALTER TABLE 2 DISABLE CONSTRAINT Table altered. ‡ Apply the CASCADE option to disable dependent integrity constraints. EMP emp_empno_pk CASCADE.

EMP emp_empno_pk. . ‡ ‡ A UNIQUE or PRIMARY KEY index is automatically created if you enable a UNIQUE key or PRIMARY KEY constraint.Enabling Constraints ‡ Activate an integrity constraint currently disabled in the table definition by using the ENABLE clause. SQL> ALTER TABLE 2 ENABLE CONSTRAINT Table altered.

constraint_type.. search_condition FROM user_constraints WHERE table_name = 'EMPLOYEE'. SQL> 2 3 4 SELECT constraint_name. .. C C C P SEARCH_CONDITION ------------------------EMPNO IS NOT NULL DEPTNO IS NOT NULL CONSTRAINT_NAME -----------------------SYS_C00674 SYS_C00675 EMP_EMPNO_PK .Viewing Constraints Query the USER_CONSTRAINTS table to view all constraint definitions and names.

Columns with Constraints View the columns associated with the constraint names in the USER_CONS_COLUMNS view SQL> SELECT 2 FROM 3 WHERE constraint_name. COLUMN_NAME ---------------------DEPTNO EMPNO MGR EMPNO DEPTNO CONSTRAINT_NAME ------------------------EMP_DEPTNO_FK EMP_EMPNO_PK EMP_MGR_FK SYS_C00674 SYS_C00675 . column_name user_cons_columns table_name = 'EMPLOYEE'.

NOT NULL .CHECK ‡ Query the USER_CONSTRAINTS table to view all constraint definitions and names. .PRIMARY KEY .Summary ‡ Create the following types of constraints: .UNIQUE key .FOREIGN KEY .

Views .

and delete data through a view ‡ Drop a view .Objectives ‡ Describe a view ‡ Create a view ‡ Retrieve data through a view ‡ Alter the definition of a view ‡ Insert. update.

Database Objects Object Table Description Basic unit of storage. composed of rows and columns Logically represents subsets of data from one or more tables Generates primary key values Improves the performance of some queries Alternative name for an object View Sequence Index Synonym .

Why Use Views? ‡ To restrict database access ‡ To make complex queries easy ‡ To allow data independence ‡ To present different views of the same data .

)] ASThe subquery can contain complex SELECT ‡ subquery [WITH READ ONLY] syntax. .. CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[..Creating a View ‡ You embed a subquery within the CREATE VIEW statement. ‡ The subquery cannot contain an ORDER BY clause. alias].

Creating a View ‡ Create a view. empvu10 empno. ‡ Describe the structure of the view by using the SQL*Plus DESCRIBE command. SQL> 2 3 4 View CREATE VIEW AS SELECT FROM WHERE created. job employee deptno = 10. EMPVU10. SQL> DESCRIBE empvu10 . ename. that contains details of employees in department 10.

ename NAME.Creating a View ‡ Create a view by using column aliases in the subquery. sal SALARY employee deptno = 30. ‡ Select the columns from this view by the given alias names. SQL> 2 3 4 5 View CREATE VIEW AS SELECT FROM WHERE created. salvu30 empno EMPLOYEE_NUMBER. .

Retrieving Data from a View SQL> 2 SELECT * FROM salvu30.--------BLAKE 2850 MARTIN 1250 ALLEN 1600 TURNER 1500 JAMES 950 WARD 1250 EMPLOYEE_NUMBER --------------7698 7654 7499 7844 7900 7521 6 rows selected. . NAME SALARY ---------.

ename. 7839 7782 7934 KING PRESIDENT CLARK MANAGER MILLER CLERK EMP . USER_VIEWS EMPVU10 SELECT FROM WHERE empno.Querying a View SQL*Plus SELECT * FROM empvu10. job employee deptno = 10.

Modifying a View ‡ Modify the EMPVU10 view by using CREATE OR REPLACE VIEW clause. employee_name. job_title) AS SELECT empno. ename. created. ‡ Column aliases in the CREATE VIEW clause are listed in the same order as the columns in the subquery. Add an alias for each column name. job FROM employee WHERE deptno = 10. . SQL> 2 3 4 5 View CREATE OR REPLACE VIEW empvu10 (employee_number.

MAX(e.dname.sal) employee e.deptno d. minsal.Creating a Complex View Create a complex view that contains group functions to display values from two tables. dept_sum_vu (name. SQL> 2 3 4 5 6 7 View CREATE VIEW AS SELECT FROM WHERE GROUP BY created. MIN(e. AVG(e.sal).sal). department d e. maxsal.deptno = d. avgsal) d. .dname.

The DISTINCT keyword . ‡ You cannot remove a row if the view contains the following: .A GROUP BY clause .Group functions .DML Operations on a View Rules for Performing DML Operations on a View ‡ You can perform DML operations on simple views.

DML Operations on a View Rules for Performing DML Operations on a View ‡ You cannot modify data in a view if it contains: .Any of the conditions previously mentioned .The view contains any of the conditions mentioned above or previously mentioned .Columns defined by expressions .There are NOT NULL columns in the base tables that are not selected by the view .The ROWNUM pseudo column ‡ You cannot add data if: .

Denying DML Operations You can ensure that no DML operations occur by adding the WITH READ ONLY option to your view definition. . SQL> 2 3 4 5 6 View CREATE OR REPLACE VIEW empvu10 (employee_number. job_title) AS SELECT empno. job FROM employee WHERE deptno = 10 WITH READ ONLY. ename. ‡ Any attempt to perform a DML on any row in the view will result in Oracle Server error ORA01752. employee_name. created.

. DROP VIEW view. SQL> DROP VIEW empvu10.Removing a View Remove a view without losing data because a view is based on underlying tables in the database. View dropped.

Summary ‡ A view is derived from data in other tables or other views.Restricts database access .Simplifies queries .Provides data independence . ‡ A view provides the following advantages: .Allows multiple views of the same data .Can be dropped without removing the underlying data .

Synonyms. Indexes and Sequences .

Objectives ‡ Describe some database objects and their uses ‡ Create. and use sequences ‡ Create and maintain indexes ‡ Create private and public synonyms . maintain.

Database Objects Object Table Description Basic unit of storage. composed of rows and columns Logically represents subsets of data from one or more tables Generates primary key values Improves the performance of some queries Alternative name for an object View Sequence Index Synonym .

What Is a Sequence? ‡ Automatically generates unique numbers ‡ Is a sharable object ‡ Is typically used to create a primary key value ‡ Replaces application code ‡ Speeds up the efficiency of accessing sequence values when cached in memory .

.Creating a Sequence Define a sequence to generate sequential numbers 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 for the primary key of the DEPARTMENT table. . SQL> CREATE SEQUENCE dept_deptno 2 INCREMENT BY 1 3 START WITH 91 4 MAXVALUE 100 5 created. ‡ Do not use the CYCLE option.

last_number user_sequences. max_value. increment_by. min_value. SQL> SELECT 2 3 FROM sequence_name. .Confirming Sequences ‡ Verify your sequence values in the USER_SEQUENCES data dictionary table. ‡ The LAST_NUMBER column displays the next available sequence number.

Pseudo columns ‡ NEXTVAL returns the next available sequence value. ‡ ROWID uniquely identify the rows in your table. ‡ LEVEL ² a special column you can reference only in a hierarchical query . ‡ CURRVAL obtains the current sequence value.

Using a Sequence ‡ Insert a new department named ´MARKETINGµ in San Diego. dname. 'MARKETING'. SQL> INSERT INTO 2 VALUES 3 1 row created. 'SAN DIEGO'). ‡ View the current value for the DEPT_DEPTNO sequence.NEXTVAL. departmnent(deptno.CURRVAL dual. . SQL> SELECT 2 FROM dept_deptno. loc) (dept_deptno.

‡ Gaps in sequence values can occur when: . .The system crashes .A rollback occurs .Using a Sequence ‡ Caching sequence values in memory allows faster access to those values. by querying the USER_SEQUENCES table. if it was created with NOCACHE.A sequence is used in another table ‡ View the next available sequence.

SQL> ALTER SEQUENCE dept_deptno 2 INCREMENT BY 1 3 MAXVALUE 999999 4 NOCACHE 5 NOCYCLE. minimum value. . maximum value.Modifying a Sequence Change the increment value. cycle option. Sequence altered. or cache option.

Removing a Sequence ‡ Remove a sequence from the data dictionary by using the DROP SEQUENCE statement. Sequence dropped. . ‡ Once removed. SQL> DROP SEQUENCE dept_deptno. the sequence can no longer be referenced.

What Is an Index? ‡ Schema object ‡ Used by the Oracle Server to speed up the retrieval of rows by using a pointer ‡ Reduces disk I/O by using rapid path access method to locate the data quickly ‡ Independent of the table it indexes ‡ Automatically used and maintained by the Oracle Server .

A unique index is created automatically when you define a PRIMARY KEY or UNIQUE key constraint in a table definition. ‡ Manually . .Users can create nonunique indexes on columns to speed up access time to the rows.How Are Indexes Created? ‡ Automatically .

..Creating an Index ‡ Create an index on one or more columns CREATE INDEX index ON table (column[.). column]. ‡ Improve the speed of query access on the ENAME column in the EMP table SQL> CREATE INDEX 2 ON Index created. emp_ename_idx employee(ename)..

column_name.ix. ic.index_name = ix.index_name ic. ic. user_ind_columns ic ic.table_name = 'EMP'. the table name. ‡ The USER_IND_COLUMNS view contains the index name. and the column name.index_name. SQL> 2 3 4 5 SELECT FROM WHERE AND ic. .column_position col_pos.uniqueness user_indexes ix.Confirming Indexes ‡ The USER_INDEXES data dictionary view contains the name of the index and its uniqueness.

. SQL> DROP INDEX index. Index dropped. SQL> DROP INDEX emp_ename_idx. ‡ Remove the EMP_ENAME_IDX index from the data dictionary. ‡ To drop an index.Removing an Index ‡ Remove an index from the data dictionary. you must be the owner of the index or have the DROP ANY INDEX privilege.

view. user-defined object type. You can refer to synonyms in the following DML statements: SELECT. DELETE. which is an alternative name for a table. NOAUDIT. and COMMENT. package. However. Such privileges must be granted to a user before the user can use the synonym. REVOKE. Synonyms provide both data independence and location transparency. procedure. You can refer to synonyms in the following DDL statements: AUDIT. INSERT. Synonyms permit applications to function without modification regardless of which user owns the table or view and regardless of which database holds the table or view. UPDATE. GRANT. sequence. synonyms are not a substitute for privileges on database objects. or another synonym.Synonyms Purpose Use the CREATE SYNONYM statement to create a synonym. materialized view. Java class schema object. stored function. and LOCK TABLE. . EXPLAIN PLAN.

Synonyms

Prerequisites To create a private synonym in your own schema, you must have CREATE SYNONYM system privilege. To create a private synonym in another user¶s schema, you must have CREATE ANY SYNONYM system privilege. To create a PUBLIC synonym, you must have CREATE PUBLIC SYNONYM system privilege.

Synonyms 

Simplify access to objects by creating a synonym (another name for an object).

‡ Refer to a table owned by another user. ‡ Shorten lengthy object names.

CREATE [PUBLIC] SYNONYM synonym FOR object;

Create & Remove Synonyms
‡ Create a shortened name / SYNONYM for the DEPT_SUM_VU view.

SQL> CREATE SYNONYM d_sum 2 FOR dept_sum_vu; Synonym Created.

‡ Drop a synonym.
SQL> DROP SYNONYM d_sum; Synonym dropped.

DCL Statements

Objectives

‡ Create users ‡ Create roles to ease setup and maintenance of the security model ‡ GRANT and REVOKE object privileges

Controlling User Access

Database administrator

Username and password privileges
Users

Privileges ‡ Database security .Data security ‡ System privileges: Gain access to the database ‡ Object privileges: Manipulate the content of the database objects ‡ Schema: Collection of objects.System security . and sequences . such as tables. views.

Remove tables . . ‡ The DBA has high-level system privileges.Create new users .Backup tables .System Privileges ‡ More than 80 privileges are available.Remove users .

Creating Users The DBA creates users by using the CREATE USER statement. SQL> CREATE USER scott 2 IDENTIFIED BY tiger. . User created. CREATE USER IDENTIFIED BY user password.

] TO user [. ‡ An application developer may have the following system privileges: ± CREATE SESSION ± CREATE TABLE ± CREATE SEQUENCE ± CREATE VIEW ± CREATE PROCEDURE .. user. GRANT privilege [.. the DBA can grant specific system privileges to a user. privilege..]..User System Privileges ‡ Once a user is created.

create view 2 TO scott.Granting System Privileges The DBA can grant a user specific system privileges. . Grant succeeded. create sequence. SQL> GRANT create table.

What Is a Role? Users Manager Privileges Allocating privileges without a role Allocating privileges with a role .

Grant succeeded.Creating Roles SQL> CREATE ROLE manager. SQL> GRANT create table. SQL> GRANT manager to BLAKE. . CLARK. Role created. Grant succeeded. create view 2 to manager.

User altered. . ‡ Users can change their password by using the ALTER USER statement. SQL> ALTER USER scott 2 IDENTIFIED BY lion.Changing Your Password ‡ When the user account is created. a password is initialized.

Object Privileges Object Privilege ALTER DELETE EXECUTE INDEX INSERT REFERENCES SELECT UPDATE Ö Ö Ö Ö Ö Ö Ö Ö Ö Table Ö Ö Ö Ö View Sequence Ö Procedure .

Object Privileges ‡ Object privileges vary from object to object. . ‡ An owner has all the privileges on the object. GRANT ON TO [WITH GRANT object_priv [(columns)] object {user|role|PUBLIC} OPTION]. ‡ An owner can give specific privileges on that owner·s object.

Granting Object Privileges ‡ Grant query privileges on the EMP table. manager. ‡ Grant privileges to update specific columns to users and roles. SQL> GRANT select 2 ON employee 3 TO sue. SQL> GRANT update (dname. Grant succeeded. . loc) 2 ON department 3 TO scott. rich. Grant succeeded.

SQL> GRANT select. Grant succeeded. Grant succeeded. ‡ Allow all users on the system to query data from Alice·s DEPARTMENT table.GRANT Keywords WITH GRANT OPTION & PUBLIC Keywords ‡ Give a user authority to pass along the privileges. SQL> GRANT select 2 ON alice. . insert 2 ON department 3 TO scott 4 WITH GRANT OPTION.department 3 TO PUBLIC.

Confirming Privileges Granted Data Dictionary Table ROLE_SYS_PRIVS ROLE_TAB_PRIVS USER_ROLE_PRIVS USER_TAB_PRIVS_MADE USER_TAB_PRIVS_RECD USER_COL_PRIVS_MADE USER_COL_PRIVS_RECD Description System privileges granted to roles Table privileges granted to roles Roles accessible by the user Object privileges granted on the user's objects Object privileges granted to the user Object privileges granted on the columns of the user's objects Object privileges granted to the user on specific columns .

.. user.. REVOKE {privilege [.]|ALL} ON object FROM {user[. ‡ Privileges granted to others through the WITH GRANT OPTION will also be revoked.. privilege.]|role|PUBLIC} [CASCADE CONSTRAINTS]. .Revoke Object Privileges ‡ You use the REVOKE statement to revoke privileges granted to other users.

Revoke succeeded. insert 2 ON department 3 FROM scott.Revoking Object Privileges As user Alice. SQL> REVOKE select. revoke the SELECT and INSERT privileges given to user Scott on the DEPARTMENT table. .

Summary CREATE USER GRANT Allows the DBA to create a user Allows the user to give other users privileges to access the user's objects CREATE ROLE ALTER USER password REVOKE Allows the DBA to create a collection of privileges Allows users to change their Removes privileges on an object from users .

The Oracle Architecture .

The Memory Architecture .Objectives  Oracle Architecture  Oracle Database  The Study Phases Objectives .The Disk Architecture .The Back Ground Processes  The Logical Architecture  The Physical Architecture  How Oracle Works .

Understanding Oracle Database  Overview of oracle Database Architecture  Memory Structure  Process Structure  Storage Structure  New Features .

200.100 KByte DBW0 CKPT LGWR Data File Raw Device ARCH Archive Log Mode(50M) .000 KByte 2.Overview of Oracle Architecture PMON SMON RECO D000 S000 P000 * Total SGA Size : 1700 Mbyte * Fixed Size : 70 Kbyte * Variavle Size : 490 MByte SGA Shared SQL Area Database Buffer Cashe Redo Log Buffer TL-812 4.000 KByte 1.000.

Oracle Architecture .

Oracle Database Oracle Database Physical Logical Tablespaces DB Files Non DB Files Segments DataFile RedologFile PWD File INIT File Extents Control File Archived Log File Data Blocks .

Memory Architecture 2. Background Processes . Disk Architecture 3.The ³3´ Base 1.

Memory / Disk Architecture Disk Background processes Disk Architecture SGA .

Disk Architecture DATA FILES LOG FILES CONTROL FILES .

. ‡ One or more Data files may compose of a Tablespace.Data Files ‡ A Particular Data File is associated with only one Database and one Tablespace. ‡ They Dynamically Extend when the database runs out of space.

.Redo Log File ‡ Record all changes made to the Data. ‡ Instance Recovery ‡ Multiplexing Log Files for Security.

Control File The constituents shall be : ‡ Name of Database ‡ Names and Location of Physical Files ‡ Timestamp of the database. ‡ Recovery information .

Memory Architecture Memory Architecture Program Global area System Global Area INSTANCE = SGA + Background Process .

Oracle Instance Oracle Instance = Shared pool SGA + Background Processes Instance Memory structures Redo log buffer cache SGA Library cache Data Dictionary cache Database buffer cache PMON SMON DBWR LGWR CKPT Others Background structures .

Shared Global Area The Shared Global Area gets initialized during the startup and it is released during the shutdown. SHARED POOL LIBRARY CACHE DICTONARY CACHE DB BUFFER LOG BUFFER .

‡Minimize the disk IO and Improve Performance. . ‡Redo log Buffer Cache ‡Stores the log of modifications made to the database.Database and Log Buffers ‡Database Buffer Cache ‡The Latest used blocks by the Database.

Shared Pool = Library Cache + Dictionary Cache .Shared Pool ‡ Stores information about most recently executed SQL and PL/SQL statements. ‡ Stores most recently used data definitions.

Program Global Area ‡ Memory allocated when a session is stared and deallocated when the session terminated. . ‡ Used by only one session ( Unique to each session). ‡ The Server Process Control Information is available here.

.DBWR : Writes the modified blocks from the database buffer cache to the data files. It Cleans up Temp segments that are not in use and coalesce Free Extents.SMON : Dedicated to perform instance recovery. . .LGWR : Writes redo log entries to the redo log files .Dnnn : Dispatcher processes are present in a Shared server configuration.Background Processes .PMON : Performs recovery when a client/user process fails. .

.Background Processes .RECO : Used in a distributed environment when the transactions are pending due to some network failures. . The copied files are called offline/archived redo log files. .ARCH : Copies the online Redolog files when there is a log switch.CKPT : Responsible for instructing the DBWR to update the datafiles when ever a CKPT occurs and also update control file with most recent CKPT information.

Logical Structure TABLE SPACE SEGMENTS EXTENTS BLOCKS .

Data Files and Tablespaces .

Enlarging Tablespace ‡By adding a Data File .

Enlarging Tablespace ‡By Dynamically Sizing Data Files .

Enlarging Database ‡By adding a Tablespace .

How Oracle Works .

‡ The Server Process receives the Request and is checked in the shared pool. ‡ The Server detects the connection and a Dedicated server process gets created. . ‡ At PGA : A Private SQL Area is created.How Oracle Works ‡ User process from the Workstation.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->