Sie sind auf Seite 1von 187

Data V.

S Information
Data is nothing but all facts that are observed or measured by humans. When this data is systematized and processed we get Information Or A group of facts presented as an input to any system is termed as data. This group of facts has to be organized at which it becomes information which can be stored and retrieved as and when required

Fundamental Unit of Data


Character

4.
3. 2.

Keyboard
Monitor Printer Mouse
Fields

1000
650o 4500 650
File

1.
Record

Data Base Hierarchy


File-1

Database
File-N

Record-1

Record-N

Field-1

Field-N

Character-1

Character-N

Data Model
A data model specifies how data is stored and retrieved.
Hierarchical Model 2. Network Model 3. Relational Model
1.

Relational Model
Dr. E.F Codd Proposed/Designed the Relational Model For Database Systems in 1970 2. Data is represented in a tabular format 3. Data is stored in the form of rows & columns Table Name: Dept Column/Attribute
1.

Deptno Name Location ------------------------------------------------------10 Accounting 2nd Floor 20 Sales 1st Floor 30 Production 4th Floor
Row/Tuple

Table/Relation

Do You Know ?
The terms relation, tuple and attribute have been derived from the field of mathematics and are alias to most people. The equivalent terms used by different sets of people are Relational Model Relation Tuple Attribute Programmer File Record Field User Table Row Column

WHAT IS AN DBMS?
Every individual and company has data, which is to be stored and manipulated. Manipulating includes adding as new data, deleting unwanted data, and changing the existing data. So to store and manipulate data efficiently, we need a set of programs called as database management system.(DBMS)

What is a Database Management System ?


Is a collection of programs that is used to manipulates(add,delete and update) a Data Base.

Or
A Data Base Management System allows the user to store, retrieve and manipulate the data or information. Definition: An Efficient System that Organizes, Manages and manipulates the Data Base is called DATABASE MANAGEMENTY SYSTEM

WHAT IS AN RDBMS

A DBMS bases on relational mode is called RDBMS. It means a set of programs that manipulates data by storing data in the form of table values as an relational database management system(RDBMS)

Definition Of Relational Database


A Relational Database is a collection of relations or TwoDimensional Tables
Database

EMPNO

ENAME

JOB

DEPTNO

DNAME

-------------------------------------------------------------7839 7840 KING JONES PRESIDENT MANAGER

-------------------------------------10 20 ACCOUNTS SALES

WHAT IS ORACLE
A DBMS must be able to reliably manage a large amount of data in a multi-user environment. A database system should also provide secure and fail recovery. Oracle is the name of a database management system developed by ORACLE CORPORATION. ORACLE is an RDBMS as it stores and manage data using relational model.

Why Oracle ?

Old Data Base Management System It supports 100s of Different Platforms It is a very Complex System which maintains 100% accuracy and maintains a very big big data bases. It is very user friendly Software and its Cost is low It is one of the most Popular Solution Provider for all Commercial Applications

STANDARD QUERY LANGUAGE

All most all relational database system use SQL for data manipulation and retrieval. SQL is the standard language for relational database system. SQL commands are divided into following categories depending upon what they do

Structured Query Language(SQL)


Was Developed By IBM Standard Language for Relational Databases Non-Procedural Language.

SQL Statements
SELECT INSERT UPDATE DELETE CREATE ALTER DROP RENAME TRUNCATE COMMIT ROLLBACK SAVEPOINT GRANT REVOKE (DRL)Data retrieval Language DML(data manipulation language) DDL(data definition language)

Transaction Control language(TCL) DCL(data controlling language)

SQL Commands
Can be Given on Multiple Lines Must be Terminated with a Semicolon(;) SQL Statements are not Case Sensitive Are stored in SQL Buffer

SQL *Plus Commands


Must be given in a Single Line Can be Abbreviated Need not be Terminated with Semicolon(;) Are not stored in SQL Buffer

SQL Statements Versus SQL*Plus Commands


SQL
A Language ANSI Standard Keyword cannot be abbreviated Statements manipulate data and table definitions in the database

SQL*Plus
An Environment Oracle Proprietary Keywords can be abbreviated Commands do not allow manipulation of values in the database

Capabilities of SQL Statements SELECTION


Selecting a Few Rows from a set of Rows In a Table
Row-1 Row-2 Row-3 Row-4 Row-5 Row-6

PROJECTION
Selecting a Few Columns From a Set of Available Columns in a Table
Col-1 Col-2 Col-3 Col-4 Col-5 Col-6

SELECT Statement
SELECT [DISTINCT] (*,column [alias],) From table;

Selecting Specific Columns


SELECT

deptno, loc

FROM dept;
DEPTNO LOC

--------------------------------------10 40 NEW YORK BOSTON

Communicating with a RDBMS Using SQL


Statements Send to the DataBase

SQL> SELECT loc


FROM

dept

Data Base

LOC -------------------NEW YORK DALLAS CHICAGO BOSTON

Dept
Deptno Dname Loc

--------------------------------------------------10 20 ACCOUNTING RESEARCH NEW YORK DALLAS

Invoking Oracle

Logging In to SQL *Plus From Windows Environment

From Command Line


Sqlplus [username[/password [@database]]]

Sqlplus Scott/tiger@ntserver

Selecting All Columns


SELECT *

FROM dept;
DEPTNO DNAME LOC

------------------------------------------------------10 20 30 40 ACCOUNTING RESEARCH SALES OPERATIONS NEW YORK DALLAS CHICAGO BOSTON

Arithmetic Expressions
Operator Description
Add

* /

Subtract Multiply Divide

Using Arithmetic Operators


SELECT ename, sal, sal+500 FROM emp; ENAME SAL SAL+500

-------------------------------------------------------------------KING BLAKE CLARK JONES 5000 2850 2450 2975 5500 3350 2950 3475

Operator Precedence

* / + Multiplication and Division take priority over addition and subtraction Operators of the same priority are evaluated from left to right Parentheses are used to force the Precedence Order.

Operator Precedence
SELECT ename, sal, 12* sal+200 FROM emp; ENAME SAL 12*SAL+200

-------------------------------------------------------------------KING BLAKE CLARK JONES 5000 2850 2450 2975 60200 34400 29600 35900

Using Parentheses
SELECT ename, sal, 12* (sal+200) FROM emp; ENAME SAL 12*(SAL+200)

-------------------------------------------------------------------KING BLAKE CLARK JONES 5000 2850 2450 2975 62400 36600 31800 38100

Defining a Null Value


A Null is a value that is unavailable, unassigned, unknown, or inapplicable
A null is not the same as zero or a blank(space)
SELECT ename, job,sal, comm FROM emp; ENAME JOB SAL COMM

---------------------------------------------------------------------------KING BLAKE . TURNER PRESIDENT MANAGER SALESMAN 5000 2850 . 1500 0

Null Values in Arithmetic Expressions


Arithmetic expressions containing a null value evaluate to null
SELECT ename, 12*sal+comm FROM emp; ENAME JOB SAL+COMM

---------------------------------------------------------------KING BLAKE . TURNER PRESIDENT MANAGER SALESMAN 1500

Defining a Column Alias


Renames

a column heading Is useful with calculations AS is a Keyword is used Between Column name and Alias Double quotation marks Requires if it contains spaces or special characters or is case sensitive

Using Column Aliases


SELECT ename as name, sal salary FROM emp; NAME SALARY

--------------------------------------KING JONES 50000 2850

SELECT ename name, sal*12 ANNUAL SALARY

FROM emp;
NAME ANNUAL SALARY

Concatenation Operator
Concatenates Columns or Character Strings to Other Columns Is Represented by two Vertical bars(||) Creates a resultant Column that is a Character Expression

Using the Concatenation Operator


SELECT ename || job as Employees FROM emp; EMPLOYEES -------------------------------KINGPRESIDENT BLAKEMANAGER CKARJNABAGER JONESMANAGER TURNERSALESMAN

Using Literal Character Strings


SELECT ename || : is a || job as Employee Details FROM emp; EMPLOYEE DETAILS -------------------------------KING: is a PRESIDENT BLAKE: is a MANAGER CLARK: is a MANAGER JONES: is a MANAGER MARTIN: is a SALESMAN

Duplicate Rows
SELECT deptno FROM emp; DEPTNO --------------10 30 10 20 10

Eliminating Duplicate Rows


SELECT DISTINCT deptno FROM emp; DEPTNO --------------10 20

30

Displaying Table Structure


DESCRIBE
NAME

dept;
NULL? TYPE

-----------------------------------------------------------------DEPTNO DNAME LOC NOT NULL NUMBER(2) VARCHAR2(14) VARCHAR2(13)

Null ? Indicates whether a column must contain data; NOT NULL indicates that a column must contain data.
Type Displays the data type for a column

Limiting Rows Using a Selection


EMPNO 7839 ENAME KING JOB PRESIDENT .. DEPTNO 10

7698
7782 7566 ..

BLAKE
CLARK JONES

MANAGER
MANAGER MANAGER

30
10 20

Retrieve all Employees in Department 10

EMPNO 7839 7782 7934

ENAME KING CLARK MILLER

JOB PRESIDEN T MANAGER CLERK

..

DEPTNO 10 10 10

Limiting Rows Selected


Restrict the Rows Returned by using the WHERE Clause.

SELECT [DISTINCT] {*|column [alias],.} FROM table [WHERE condition(s)];

Using the WHERE Clause


SELECT ename, job, deptno FROM emp WHERE job=CLERK;

ENAME

JOB

DEPTNO

---------------------------------------------------------JAMES CLERK 30 SMITH CLERK 20 ADAMS CLERK 20 MILLER CLERK 10

Character Strings and Dates


Character Strings and Date values are Enclosed in Single Quotation Marks Character Values are Case Sensitive and Date Values are format Sensitive The Default Date Format is DD-MON-YY

SELECT ename, job, deptno FROM emp WHERE ename = JAMES;

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

Using the Comparison Operators


SELECT ename, sal, comm FROM emp WHERE sal<=comm;

ENAME

SAL

COMM

---------------------------------------------------------MARTIN 1250 1400

Operator

Other Comparison Operators


Meaning Between two values

BETWEEN AND /NOT BETWEEN AND IN (list)/NOT IN (list) LIKE/NOT LIKE IS NULL/IS NOT NULL

Matches any of a list of values Matches a character pattern Is a null value

Using the BETWEEN Operator


Use the BETWEEN operator to Display Rows based on a range of values

SELECT ename, sal FROM emp WHERE sal BETWEEN 1000 AND 1500;
ENAME SAL ---------------------------------MARTAIN 1250 TURNER 1500 WARD 1250 ADAMS 1100 MILLER 1300

Using the IN Operator


Use the IN Operator to test for values in a list SELECT deptno, ename, sal FROM emp WHERE deptno in(10,20);
EMPNO ENAME JOB DEPTNO ------------------------------------------------------------------7839 KING PRESIDENT 10 7782 CLARK MANAGER 10 7566 JONES MANAGER 20 7734 MILLER CLERK 10 7788 SCOTT ANALYST 20

Using the LIKE Operator


Use the LIKE Operator to perform wildcard searches of valid search string values Search conditions can contain either literal characters or numbers % Denotes Zero or many Characters _ Denotes One Character

Using the LIKE Operator


SELECT ename, sal pattern-matching characters. You can combine FROM emp WHERE ename LIKE _A%;
ENAME SALARY ------------------------------MARTIN 1250

JAMES
WARD 1250

950

Using the IS NULL Operator


SELECT ename, mgr FROM emp WHERE mgr IS NULL;

ENAME MGR -------------------------KING

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

OR

NOT

Using the AND Operator


AND requires both conditions to be TRUE
SELECT empno, ename, job, sal FROM emp WHERE sal >=1100 AND job=CLERK;

EMPNO ENAME JOB SAL ----------------------------------------------------------7876 ADAMS CLERK 1100 7934 MILLER CLERK 1300

Using the OR Operator


OR requires either Condition to be TRUE
SELECT empno, ename, job, sal FROM emp WHERE sal >=1100 OR job=CLERK;

EMPNO ENAME JOB SAL ---------------------------------------------------------------7839 KING PRESIDENT 5000 7698 BLAKE MANAGER 2850 7782 CLARK MANAGER 2450 7566 JONES MANAGER 2975 7654 MARTIN SALESMAN 1250

Using the NOT Operator


SELECT ename, job emp WHERE job NOT IN (CLERK,MANAGER,ANALYST);
ENAME JOB --------------------------------------KING PRESIDENT MARTIN SALESMAN ALLEN SALESMAN TURNER SALESMAN WARD SALESMAN

FROM

Rules of Precedence
Order Evaluated 1 2 3 4 Operator All Comparison Operators NOT AND OR

Rules of Precedence
SELECT ename, job, sal FROM emp WHERE job=SALESMAN OR job=PRESIDENT AND sal>1500
ENAME JOB SAL ---------------------------------------------KING PRESIDENT 5000 MARTIN SALESMAN 1250 ALLEN SALESMAN 1600 TURNER SALESMAN 1500 WARD SALESMAN 1250

Rules of Precedence
Use Parentheses to Force Priority
SELECT ename, job, sal FROM emp WHERE (job=SALESMAN OR job=PRESIDENT) AND sal>1500
ENAME JOB SAL ---------------------------------------------KING PRESIDENT 5000 ALLEN SALESMAN 1600

ORDER BY Clause
Sort

Rows with the ORDER BY Clause ASC: Ascending Order, Default DESC: Descending Order The ORDER BY Clause Comes last in the SELECT Statement

Using ORDER BY Clause


SELECT ename, job, deptno, hiredate FROM emp ORDER BY hiredate;

ENAME JOB DEPTNO HIREDATE ----------------------------------------------------------------------SMITH CLERK 20 17-DEC-80 ALLEN SALESMAN 30 20-FEB-81 ..

Sorting in Descending Order


SELECT ename, job, deptno, hiredate FROM emp ORDER BY hiredate DESC;
ENAME JOB DEPTNO HIREDATE ----------------------------------------------------------------------ADAMS CLERK 20 12-JAN-83 SCOTT ANALYST 20 09-DEC-82 MILLER CLERK 10 23-JAN-82 JAMES CLERK 30 03-DEC-81 FORD ANALYST 20 03-DEC-81 KING PRESIDENT 10 17-NOV-81

Sorting By Column Alias


SELECT empno, ename, sal*12 annsal FROM emp ORDER BY annsal
EMPNO ENAME ANNAL --------------------------------------------------------7369 SMITH 9600 7900 JAMES 11400 7876 ADAMS 13200 7654 MARTIN 15000 7521 WARD 15000 7934 MILLER 18000

Sorting by Multiple Columns


SELECT empno, ename, sal*12 annsal FROM emp ORDER BY deptno, sal DESC;

ENAME DEPTNO SAL --------------------------------------------------------KING 10 5000 CLARK 10 2450 MILLER 10 1300 FORD 20 3000

Functions
The following are Different types of Functions available in Oracle

Arithmetic String Date and Time

Conversion
Group

Miscellaneous

SQL Functions
Functions are a very powerful feature of SQL and can be used to do the following

Performs Calculations on Data Modify individual Data Items Manipulate output for Groups of Rows Format Dates and Numbers for Display Convert Column datatypes

SQL Functions
Inpu t Output

FUNCTION
Arg-1 Arg-2 Arg-3

Function Performs an Action Result

Arg-N

Arithmetic
ABS(Number) ROUND(Number [,Precision]) TRUNC(Number [,Precision]) MOD(Dividend,Division)

Examples:
SELECT ABS(-125) FROM DUAL; 125

SELECT ROUND(2555.746,2) FROM DUAL;


2555.75 SELECT TRUNC(1583.768,2) FROM DUAL; 1583.76 SELECT MOD(10,4) FROM DUAL; 2

Date Arithmetic
Arithmetic Operations allowed on Dates are
Adding

a number to a date to add that many days Subtract a number from a date to subtract that many days

Examples:
SELECT SYSDATE FROM DUAL; 15-AUG-01 SELECT SYSDATE+10 FROM DUAL; 25-AUG-01

SELECT SYSDATE-10 FROM DUAL;


5-AUG-01

Date and Time Functions


Add_Months(date,number) Months_Between(date1,date2) Last_Day(date) Next_Day(date,week) Sysdate

Examples :
SELECT ADD_MONTHS(SYSDATE,2) FROM DUAL;
15-OCT-01 SELECT MONTHS_BETWEEN(SYSDATE,10-MAR-01) FROM DUAL; 5.33 SELECT LAST_DAY(SYSDATE) FROM DUAL; 31-AUG-01 SELECT NEXT_DAY(SYSDATE,FRIDAY) FROM DUAL;

String Functions

Length(string) Upper(string) Lower(string) Initcap(string) Substr(string,spos[,nochar]) Instr(string1,string2,[,spos[,nochar]) Ltrim(string) Rtrim(string) Lpad(string,length[,char]) Rpad(string,length[,char]) Replace(string,source,target) Translate(string,source,target)

SQL> select length('millennium')from dual;

LENGTH('MILLENNIUM') -------------------10
SQL> select upper('millennium')from dual; UPPER('MIL ---------MILLENNIUM

SQL> select lower('MILLENNIUM')FROM DUAL;


LOWER('MIL ---------millennium SQL> SELECT INITCAP('millennium')from dual; INITCAP('M ---------Millennium

SELECT SUBSTR('MILLENNIUM',4,6)FROM DUAL

SUBSTR -----LENNIU
SQL> SELECT INSTR('MILLENNIUM','L')FROM DUAL; INSTR('MILLENNIUM','L') ----------------------3

SELECT RPAD('MSS',10,'*')FROM DUAL


RPAD('MSS' ---------MSS******* SELECT LPAD('MSS',10,'*')FROM DUAL LPAD('MSS' ---------*******MSS

SELECT RTRIM('MILLENNIUM','IUM')FROM DUAL RTRIM(' ------MILLENN SELECT LTRIM('MILLENNIUM','MILL')FROM DUAL LTRIM( -----ENNIUM SELECT TRIM('M' FROM 'MILLENNIUM')FROM DUAL TRIM('M' -------ILLENNIU SELECT REPLACE('MILLENNIUM','ENN','ABC')FROM DUAL REPLACE('M ---------MILLABCIUM SELECT TRANSLATE('MILLENNIUM','MLN','ABC')FROM DUAL TRANSLATE( ---------AIBBECCIUA

Automatic Type Conversion


Oracle tries to Automatically Convert the given data to the Required Data Type

INSERT.VALUES(10-AUG-01,) Converts the given String to Date Type SELECT LENGTH(EMPNO) FROM EMP; Converts Empno, Which is a Number to String SELECT 10*2 FROM DUAL; Converts the given String to Number and Performs the Multiplication

Conversion Functions
TO_CHAR(number

[,format]) TO_DATE(char [,format]) TO_NUMBER(char [,format])

| date

TO_CHAR(date,fmt)
The format Model :
Must

be Enclosed in single quotation marks. Can Include any valid date format element

YYYY

Full Year in Numbers

YEAR
MM MONTH

Year Spelled out


Two-Digit value for Month Full Name of Month

DY
DAY

Three-Letter Abbreviation of the Day of the Week Full Name of the Day THREE LETTERS OF THE MONTH
TWO DIGITS OF THE YEAR NUMBER OF THE DAY IN A WEEK

MON
YY D

DD

TWO DIGITS OF THE DATE

Date Format

Date Format

Elements of Date Format Model


Time Elements format the time portion of the date

HH24:MI:SS AM

15:45:32 PM

Add Character Strings by Enclosing them in Double Quotation Marks. DD of MONTH 12 of OCTOBER

Number Suffixes Spell Out Numbers Ddspth fourteenthe

Element DDTH DDSP ddSPTH/ddTHSP

Description 4TH FOUR FOURTH

Using FM and AM/PM Keywords

Use these formats with the TO_CHAR function to display a number value as a character
9 0 $ L . , Represents a Number Represents a Number Places a Floating Dollar Sign Uses the Floating Local Currency Symbol Prints a Decimal Point Prints a Thousand Indicator

Using TO_CHAR Function With Numbers

Using TO_CHAR Function With Numbers

TO_DATE Function
Converts a character string to Date format using the TO_DATE Function

TO_DATE(char[, fmt])
SELECT ename, hiredate FROM emp WHERE hiredate= TO_DATE(February 22, 1981, Month dd, YYYY);

TO_NUMBER Function
THE FUNCTION REQUIRES IN 2 OCCASIONS. TO CONVERT FORMATTED NUMBER TO NUMBER

TO SORT CHAR DATA IN NUMERICE ORDER

TO_NUMBER(char[, fmt])
SELECT TO_NUMBER(8,900, 9,999)*10 FROM DUAL;

Miscellaneous Functions
GREATEST(value,.)
LEAST(value,.)

NVL(value,expression)
DECODE

(expression,cond1,value1, cond2,value2.else value)

Examples:
SELECT GREATEST(45,78,96,45)FROM DUAL; 96 SELECT LEAST(45,96,74,42)FROM DUAL; 42 SELECT ENAME,JOB,SAL,DECODE(JOB,'ANALYST',SAL*1.1, 'CLERK',SAL*1.9, 'MANAGER',SAL*1.5, SAL)REVISEDSAL FROM EMP;

What are GROUP Functions ? Group functions operate on sets of rows to give one result DEPTNO SAL group per
-------------------------------10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 2975 30 1600 30 950 MAX(SAL) -------------5000

Types of GROUP Functions


AVG COUNT MAX MIN SUM

Using AVG and SUM Functions


SELECT AVG(sal), MAX(sal), MIN(sal), SUM(sal) FROM emp WHERE job LIKE SALES%;

AVG(SAL) MAX(SAL) MIN(SAL) SUM(SAL) --------------------------------------------------------------------1400 1600 1250 5600

NOTE: You can use AVG and SUM for Numeric Data Only

Using MIN and Max Functions


SELECT MIN(hiredate), MAX(hiredate) FROM emp;

MIN(HIRED) MAX(HIRED) ------------------------------------------------------17-DEC-80 12-JAN-83

NOTE: You can use MIN and MAX for any DATATYPE

Using the COUNT Function


COUNT(*) returns the number of rows in a table
SELECT COUNT(*) FROM emp WHERE deptno = 30

COUNT(*) --------------6

COUNT Function Has two formats


COUNT(*) COUNT(expr)
NOTE 1: COUNT(*) returns number of rows in a table, including duplicate rows and rows containing null values in any of the columns. If WHERE clause is included in the SELECT statement, COUNT(*) returns the number of rows that satisfies the condition in the WHERE clause. NOTE 2: COUNT(expr) returns the number of nonnull rows in in the column identified by expr.

Using the COUNT Function


COUNT(expr) returns the number of nonnull rows
SELECT COUNT(comm) FROM emp WHERE deptno = 30;

COUNT(COMM) ---------------------4

GROUP Function and NULL Values


Group functions ignore Null values in the column
SELECT AVG(comm) FROM emp;

AVG(COMM) ------------------550 NOTE: All group functions except COUNT(*) ignore Null values in the Column

Using the NVL Function with GROUP Function


The NVL Function forces Group Functions to include Null values SELECT AVG(NVL(comm,0)) FROM emp;

AVG(NVL(COMM,0)) ----------------------------157.14286

Creating Groups of Data


DEPTNO SAL --------------------------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

2175

DEPTNO AVG(SAL) -------------------------------10 2916.6667 20 2175 30 1566.6667

1566.6667

Creating Groups of Data: GROUP BY Clause

Divide rows in a table into smaller groups by using the GROUP BY Clause
SELECT column, group_function(column) FROM table [WHERE condition] [GROUP BY group_by_expression] [ORDER BY column];

Using the GROUP BY Clause All columns in the SELECT list that are not in group functions must be in the GROUP BY Clause
SELECT deptno, AVG(sal) FROM emp GROUP BY deptno;
DEPTNO AVG(SAL) --------------------------------10 2916.6667 20 2175 30 1566.6667

Using the GROUP BY Clause


The GROUP BY Column does not have to be in the SELECT list SELECT AVG(sal)
FROM emp GROUP BY deptno;
AVG(SAL) ----------------2916.6667 2175 1566.6667

Grouping by More Than One Column


DEPTNO JOB SAL ------------------------------------------------10 MANAGER 2450 10 PRESIDENT 5000 10 CLERK 1300 20 CLERK 800 20 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

DEPTNO JOB SUM(SAL) ------------------------------------------------------10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 ANALYST 6000 20 CLERK 1900 20 MANAGER 2975 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600

NOTE: Groups within Groups

Clause on Multiple Columns


SELECT deptno, job, SUM(sal) FROM emp GROUP BY deptno, job;
DEPTNO JOB SUM(SAL) ------------------------------------------------------10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 ANALYST 6000 20 CLERK 1900 20 MANAGER 2975 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600

USING ROLLUP

select deptno,job,count(*) from emp group by rollup(deptno,job);

DEPTNO JOB

COUNT(*)

------ --------- --------10 CLERK 10 MANAGER 10 PRESIDENT 10 20 ANALYST 20 CLERK 1 1 1 3 2 2

20 MANAGER
20 30 CLERK

1
5 1

30 MANAGER
30 SALESMAN 30

1
4 6 14

USING CUBE

select deptno,job,count(*) from emp group by CUBE(deptno,job);

DEPTNO JOB

COUNT(*)

------- --------- ---------

10 CLERK
10 MANAGER 10 PRESIDENT 10 20 ANALYST 20 CLERK 20 MANAGER 20 30 CLERK 30 MANAGER 30 SALESMAN 30 ANALYST

1
1 1 3 2 2 1 5 1 1 4 6 2

CLERK
MANAGER PRESIDENT SALESMAN

4
3 1 4

14

Illegal Queries Using Group Functions Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY Clause
SELECT deptno, COUNT(ename) FROM emp;
SELECT deptno, COUNT(ename) * ERROR at line 1: ORA-00937: not a single-group group function

Illegal Queries Using Group Functions

You cant use the WHERE Clause to restrict Groups

You use the HAVING Clause to restrict Groups


SELECT deptno, AVG(sal) FROM emp WHERE AVG(sal) > 2000 GROUP BY deptno;

WHERE

AVG(sal) > 2000 * ERROR at line 3: ORA-00934: group function is not allowed here

Excluding Group Results


DEPTNO SAL --------------------------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
5000

3000

DEPTNO MAX(SAL) -------------------------------10 5000 20 3000

2850

Use the HAVING Clause to restrict Groups


Rows

are grouped The group Function is applied Groups matching the HAVING Clause are Displayed
SELECT FROM [WHERE [GROUP BY [HAVING [ORDER BY column, group_function table condition] group_by_expression] group_condition] column];

Using the HAVING Clause


SELECT deptno, max(sal) FROM emp GROUP BY deptno HAVING max(sal) > 2900

DEPTNO MAX(SAL) --------------------------------------------10 5000 20 3000

Using the HAVING Clause


SELECT job, SUM(sal) PAYROLL FROM emp WHERE job NOT LIKE SALES% GROUP BY deptno HAVING max(sal) > 2900

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

Nesting Group Functions Display the maximum average salary


SELECT MAX(AVG(sal)) FROM emp GROUP BY deptno;

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

Order of evaluation of the Clauses


WHERE Clause GROUP BY Clause HAVING Clause ORDER BY Clause

Nesting Functions
Single Row functions can be nested to any level Nested functions are evaluated from deepest level to the leastdeep level

F3(F2(F1(col,arg1),arg2),arg3)
Step1=Result1 Step2=Result2 Step3=Result3

Nesting Functions
SELECT ename, NVL(TO_CHAR(mgr),No Manager) FROM emp WHERE mgr IS NULL;
ENAME NVL(TO_CHAR(MGR),NO MANAGER) -----------------------------------------------------------------------KING No Manager

Sub-Query
2

Who has a salary Greater than Jones ?

Jones

Sub Query
SELECT sal FROM emp WHERE ename = JONES;

SELECT * FROM emp WHERE sal > 5500;

NOTE: Here we do not know the salary of Employee JONES. So, we have to determine the Salary of JONES and use the Salary to find out the Employees Whose Salary greater than his Salary.

Using a Sub Query to Solve a Problem


Main Query SELECT ename Sub-Query FROM emp WHERE sal > 3500 ( SELECT sal FROM emp WHERE ename=JONES ); NOTE 1: The Sub query (Inner Query) Executes once before the main Query. NOTE 2: The Result of the Sub Query is Used by the Main Query(Outer Query)

Sub Query
SELECT deptno FROM emp WHERE ename = MILLER;

SELECT * FROM emp WHERE deptno=10

NOTE: Here we do not know the department to which MILLER belongs. So, we have to determine the department of MILLER and use the department number to find out the other Employees of that department.

Nested Quires
The Result of one query is dynamically substituted in the condition of another SQL First evaluates inner query(or sub query) within the WHERE clause The return value of inner query is then substituted in the condition of the outerquery When using relational operators, ensure that the sub query returns a single row output

1. SELECT MAX(sal) FROM emp;


2. SELECT * FROM emp WHERE sal=5500;

SELECT * FROM emp WHERE sal

= 5500 ( SELECT MAX(sal) FROM emp );

NOTE: List the names of the employee drawing the Highest salary

1. SELECT deptno FROM dept WHERE loc = NEW YORK;


2. SELECT * FROM emp WHERE deptno=10;

SELECT * FROM emp WHERE deptno

= 10 ( SELECT deptno FROM dept WHERE loc = NEW

YORK );

Guidelines for Using Sub queries


Enclose sub queries in parentheses. Place sub queries on the right side of the comparison operator Use single-row operator with single-row sub queries Use multiple-row operators with multiple-row sub queries.

Types of Sub Queries


1. Single-Row Sub Query
Main Query
Sub Query Clerk

2.

Multiple-Row Sub Query


Main Query Sub Query Clerk Manage r

3.

Multiple-Column Sub Query


Main Query Sub Query Clerk 7900 Manager 7698

Single-Row Sub queries


Returns

only one Row Use Single-row comparison Operators


=, > ,>=, <, <=, < >

Multiple-Row Sub queries


Returns

Multiple Rows Use Multiple-row comparison Operators IN, ANY, ALL

In Usage
IN :- Equal to any member in the list

List the names of the Employee drawing the highest salary in department wise

SELECT FROM WHERE

ename, job, sal emp sal IN ( SELECT MAX(sal) FROM emp GROUP BY

deptno);

In Usage
List the names of the Employee who are working in NEW YORK and CHICAGO

SELECT FROM WHERE

ename, job, sal emp deptno IN ( SELECT deptno FROM DEPT WHERE loc IN(NEW YORK,CHICAGO));

In Usage
List the names of the Employee whose Jobtistle is similar to the Jobtitle of the Department 10 people

SELECT FROM WHERE

AND

ename, job, sal emp job IN ( SELECT job FROM emp WHERE deptno=10 ) deptno in(20,30);

ANY Usage
ANY: Compare value to each value returned by the sub query List all employees whose salary is less than any clerk and who are not clerks.

SELECT FROM WHERE

ename, job, sal emp sal < ANY ( SELECT sal FROM emp WHERE job=CLERK ) AND job <> CLERK;

ANY Usage
< ANY
> ANY = ANY

Means less than the maximum.


Means more than the minimum. Is equivalent to IN.

ANY Usage
SELECT FROM WHERE ename, job, sal emp sal > ANY ( SELECT sal FROM emp WHERE deptno=20

); List the employee names whose salary is greater than the lowest salary of an employee belonging to department number 20.

ANY Usage
SELECT FROM WHERE ename, job, sal emp sal > ANY ( SELECT sal FROM emp WHERE Job=MANAGER);

List the employee details of those employees whose salary is greater than any of the manager

ALL Usage
ALL :- Compare value to every value returned by the sub query SELECT FROM WHERE ename, job, sal emp sal > ALL ( SELECT AVG(sal) FROM emp GROUP BY deptno); Means more than the maximum Means less than the minimum

> ALL < ALL

Multiple Queries
SELECT ename,job 1 FROM emp WHERE job = Clerk ( SELECT job FROM emp WHERE empno=7369 ) 2 AND sal > 1100 ( SELECT sal FROM emp WHERE empno=7876 );

Using Group Functions In a Sub Query


SELECT FROM WHERE ename, job, sal emp sal = ( SELECT MIN(sal) FROM emp );

ENAME JOB SAL -----------------------------------------------------------------SMITH CLERK 800

Having Clause with Sub queries


The Oracle Server executes sub queries first

The Oracle Server returns results into the HAVING clause of the main query.
SELECT deptno, MIN(sal) FROM emp GROUP BY deptno HAVING MIN(sal) > ( SELECT MIN(sal) FROM emp );

What is Wrong with This Statement


SELECT FROM WHERE empno, ename emp sal = ( SELECT

MIN(sal) FROM emp GROUP BY deptno);


ERROR: ORA-01427 : single-row sub query returns more than one row no rows selected

Will This Statement Work ?


SELECT FROM WHERE ename, job emp job = ( SELECT job FROM emp WHERE ename=SMYTHE);

No rows Selected

SET Operators
SET Operators combine two or more queries into one result UNION : Rows of first query plus rows of second query, less duplicate rows INTERSECT : Common rows from all the queries MINUS : Rows unique to the first query

UNION

Multiple queries can be merged together and their results combined, using the UNION Clause

the output of two or more queries into a single set of rows and columns
The queries are all executed independently, but their output is merged Only the final query ends with a semicolon

UNION
SELECT job FROM emp
WHERE deptno = 20 UNION SELECT job FROM emp WHERE deptno = 30;
NOTE : Display the different Designations in Department 20 and 30.

INTERSECT
SELECT job FROM emp
WHERE deptno = 20 INTERSECT SELECT job FROM emp WHERE deptno = 30;
NOTE : List the jobs common to department 20 and 30

MINUS
SELECT job FROM emp WHERE deptno = 20 MINUS SELECT job FROM emp WHERE deptno = 10 MINUS SELECT job FROM emp WHERE deptno = 30;

JOIN
Use a join to query data from more than one table
EMPNO Exists in the EMP table DEPTNO Exists in the both the EMP and DEPT tables LOC Exists in the DEPT table

Types of Joins
Equi

Join Non-Equi Join Outer Join Self Join

Retrieving Records with Equi Joins


SELECT emp.empno, emp.ename,

emp.deptno, dept.deptno, dept.loc

FROM emp,dept
WHERE emp.deptno = dept.deptno;
NOTE: Equijoins are called simple or inner joins

Retrieving Records with NON-Equi Joins


SELECT e.ename,e.sal,s.grade

FROM
emp e,salgrade s WHERE e.sal between s.losal and s.hisal

Conditions Using the AND Operator


SELECT empno, ename, emp.deptno, loc FROM emp, dept WHERE emp.deptno = dept.deptno AND INITCAP(ename) = King;

Using Table Aliases


SELECT emp.empno, emp.ename, emp.deptno, dept.loc FROM emp, dept WHERE emp.deptno = dept.deptno;

SELECT e.empno, e.ename, e.deptno, d.loc FROM emp e, dept d WHERE e.deptno = d.deptno;

Outer Joins
You

use an outer join to also see rows that do not usually meet the join condition Outer join operator is the plus sing (+)

Using Outer Join

SELECT e.empno, e.ename, d.deptno, d.loc FROM emp e, dept d WHERE e.deptno (+) = d.deptno;

Self Join Joining a Table to Itself


SELECT worker.ename || Works for || manager.ename FROM emp worker, emp manager WHERE worker.mgr = manager.empno;
MGR in the WORKER table is equal to EMPNO in the MANAGER table

TRANSACTION
A Collection of Statements that is either Completely Executed or Not Executed at All.
Commit Point

Insert ... Update Update Commit;


TRANSACTION Commit Point

TRANSACTION

INSERT

UPDATE

UPDATE

DELETE

ROLLBACK
Insert ... Update Update
Commit Point TRANSACTION

Rollback;

Commit Point

Advantages of COMMIT and ROLLBACK Statements


Ensures Data Consistency

Preview Data Changes Before Making Changes Permanent

SAVEPOINT
Insert ...
Commit Point

Update
Savepoint S1 Update Rollback to S1 Delete Commit;
Commit will Commit Insert,Update and Delete Commands Update Command is ROLLED Back

Controlling Transactions
TRANSACTION

INSERT

UPDATE

UPDATE

DELETE
Savepoint B
ROLLBACK TO B

COMMIT Savepoint A

ROLLBACK TO A

ROLLBACK

Locking
Rows

that are being updated are locked to ensure only one user can modify a row at a time Locking is row level Locking is automatic, Oracle automatically locks and unlocks.

Products
1. 2. 3. Shirt 20 Jeans 10 Shoe 5

T1

T2

SELECT * FROM products


U1

SELECT * FROM products


U2

More than one User can access the Same data is called Data concurrency

Products
1. 2. 3. Shirt 20 Jeans 15 Shoe 5
T1 T2

ROLLBACK Segment

2.

Jeans 10

UPDATE products SET qty = qty + 5 WHERE pid = 2; U1

SELECT * FROM products U2

At T1 row is locked At T2, u2 gets Pre-Modified rows

Products
1. 2. 3. Shirt 20 Jeans 15 Shoe 5
T1 UPDATE products SET qty = qty + 5 WHERE pid = 2; U1 T2

ROLLBACK Segment

2.

Jeans 10

UPDATE products SET qty = qty + 5 WHERE pid = 2; U2

At T1 row is locked At T2, u2 waits until lock is released

Products
1. 2. 3. Shirt 20 Jeans 15 Shoe 5
T1 UPDATE products SET qty = qty + 5 WHERE pid = 2; COMMIT; U1 T2

ROLLBACK Segment

2.

Jeans 10

SELECT * FROM products

U2

At T1 Transaction is Committed At T2, u2 gets Post-Modified rows

Security in Oracle implemented in two different Levels


System

Level Security Object Level Security

Object Level Security Allows security implementation at object level


SELECT INSERT

DELETE
ALTER REFERENCESS

UPDATE
INDEX EXECUTE

DCL Commands
GRANT {Privileges | All } ON object TO {Users | Public} [with GRANT option];

Marshall

Data Base

Michael

Dept
Deptno Dname Loc

--------------------------------------------------10 20 ACCOUNTING RESEARCH NEW YORK DALLAS

Michael

GRANT SELECT ON dept TO Marshall


Marshall

SELECT * FROM Michael.dept;

Michael

GRANT SELECT ON dept TO Marshall WITH GRANT OPTION


Marshall

GRANT SELECT ON Michael.dept Dean


Dean

SELECT * FROM Marshall.dept

REVOKE Command
REVOKE {Privileges | All} ON Object FROM {Users | Public}
Michael

REVOKE SELECT ON dept FROM Marshall

Data Base 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 Gives alternative names to objects

View

Sequence
Index Synonym

Oracle 8 Table Structures


Tables

can be created at any time, even while users are using the database You do not need to specify the size of any table. The size is ultimately defined by the amount of space allocated to the database as a whole. It is important, however, to estimate how mush space a table will use over time. Table structure can be modified online

Naming Conventions
Table

names and column names must begin with a letter and can be 1-30 characters long Names must contain only the characters A-Z, a-z, 0-9, _(underscore),$, and # Names must not duplicate the name of another object owned by the same Oracle sever user Names must not be an Oracle reserved word.

The CREATE TABLE Statement


You Must Have
CREATE TABLE Privilege A Storage area You Specify Table name Column name, column data type, and column size

Referencing Another Users Tables


Tables

belonging to another users are not in the users schema You should use the owners name as a prefix to the table

Data Type

Data Types

Description
Variable-Length Character Data Fixed-Length Character Data NUMARICAL VALUES DATE V-L-C-D Up to 2 Gigabytes S-B-C-D Up to 4 Gigabytes Raw Binary Data
Binary Data up to 4 Gigabytes B-D-S in an external File

VARCHAR2(size) CHAR(size) NUMBER(p,s) DATE LONG CLOB RAW and LONG RAW
BLOB BFILE

SYNTAX

CREATING TABLE
TABLE <TABLE

CREATE

NAME> (COLUMN NAME COLUMN TYPE(COLUMN SIZE); TABLE RAJU (SNO NUMBER(2),SNAME VARCHAR2(10),JD DATE)

CREATE

INSERTING VALUES INTO A TABLE


INSERT INTO <TABLE NAME>VALUES(1,'SAI',1500);

INSERTING VALUES INTO A TABLE USING VARIABLES INSERT INTO RAJU VALUES(&SNO,'&SNAME','&JD')

TYPES OF CONSTRAINT 1)primary key--- does not allow duplicates 2)foreign key---- can refer with column in another table 3)not null---------does not allow null values 4)unique----------will allow the feild unique 5)check------------cheks the given conditions

syntax <constraint> <constraint name> < constraint type> ex: sno number(4) constraint sno_pk primary key

courses

-------------create table courses (ccode number(2) constraint cc_pk primary key, cname varchar2(10)constraint cn_un unique, duration number(4)constraint d_ck check(duration>=30))

Das könnte Ihnen auch gefallen