Académique Documents
Professionnel Documents
Culture Documents
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
4.
3. 2.
Keyboard
Monitor Printer Mouse
Fields
1000
650o 4500 650
File
1.
Record
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)
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)
EMPNO
ENAME
JOB
DEPTNO
DNAME
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
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
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)
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
An Environment Oracle Proprietary Keywords can be abbreviated Commands do not allow manipulation of values in the database
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;
deptno, loc
FROM dept;
DEPTNO LOC
dept
Data Base
Dept
Deptno Dname Loc
Invoking Oracle
Sqlplus Scott/tiger@ntserver
FROM dept;
DEPTNO DNAME LOC
------------------------------------------------------10 20 30 40 ACCOUNTING RESEARCH SALES OPERATIONS NEW YORK DALLAS CHICAGO BOSTON
Arithmetic Expressions
Operator Description
Add
* /
-------------------------------------------------------------------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
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
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
Duplicate Rows
SELECT deptno FROM emp; DEPTNO --------------10 30 10 20 10
30
dept;
NULL? TYPE
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
7698
7782 7566 ..
BLAKE
CLARK JONES
MANAGER
MANAGER MANAGER
30
10 20
..
DEPTNO 10 10 10
ENAME
JOB
DEPTNO
Comparison Operators
Operator = > >= < <= <> Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to
ENAME
SAL
COMM
Operator
BETWEEN AND /NOT BETWEEN AND IN (list)/NOT IN (list) LIKE/NOT LIKE IS NULL/IS NOT NULL
SELECT ename, sal FROM emp WHERE sal BETWEEN 1000 AND 1500;
ENAME SAL ---------------------------------MARTAIN 1250 TURNER 1500 WARD 1250 ADAMS 1100 MILLER 1300
JAMES
WARD 1250
950
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
EMPNO ENAME JOB SAL ----------------------------------------------------------7876 ADAMS CLERK 1100 7934 MILLER CLERK 1300
EMPNO ENAME JOB SAL ---------------------------------------------------------------7839 KING PRESIDENT 5000 7698 BLAKE MANAGER 2850 7782 CLARK MANAGER 2450 7566 JONES MANAGER 2975 7654 MARTIN SALESMAN 1250
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
ENAME JOB DEPTNO HIREDATE ----------------------------------------------------------------------SMITH CLERK 20 17-DEC-80 ALLEN SALESMAN 30 20-FEB-81 ..
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
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
Arg-N
Arithmetic
ABS(Number) ROUND(Number [,Precision]) TRUNC(Number [,Precision]) MOD(Dividend,Division)
Examples:
SELECT ABS(-125) FROM DUAL; 125
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
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)
LENGTH('MILLENNIUM') -------------------10
SQL> select upper('millennium')from dual; UPPER('MIL ---------MILLENNIUM
SUBSTR -----LENNIU
SQL> SELECT INSTR('MILLENNIUM','L')FROM DUAL; INSTR('MILLENNIUM','L') ----------------------3
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
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
| date
TO_CHAR(date,fmt)
The format Model :
Must
be Enclosed in single quotation marks. Can Include any valid date format element
YYYY
YEAR
MM 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
Date Format
Date Format
HH24:MI:SS AM
15:45:32 PM
Add Character Strings by Enclosing them in Double Quotation Marks. DD of MONTH 12 of OCTOBER
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
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_NUMBER(char[, fmt])
SELECT TO_NUMBER(8,900, 9,999)*10 FROM DUAL;
Miscellaneous Functions
GREATEST(value,.)
LEAST(value,.)
NVL(value,expression)
DECODE
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
NOTE: You can use AVG and SUM for Numeric Data Only
NOTE: You can use MIN and MAX for any DATATYPE
COUNT(*) --------------6
COUNT(COMM) ---------------------4
AVG(COMM) ------------------550 NOTE: All group functions except COUNT(*) ignore Null values in the Column
AVG(NVL(COMM,0)) ----------------------------157.14286
2916.6667
2175
1566.6667
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
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
DEPTNO JOB
COUNT(*)
20 MANAGER
20 30 CLERK
1
5 1
30 MANAGER
30 SALESMAN 30
1
4 6 14
USING CUBE
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
WHERE
AVG(sal) > 2000 * ERROR at line 3: ORA-00934: group function is not allowed here
3000
2850
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];
MAX(AVG(SAL)) ----------------------2916.6667
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
Jones
Sub Query
SELECT sal FROM emp WHERE ename = JONES;
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.
Sub Query
SELECT deptno FROM emp WHERE ename = MILLER;
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
NOTE: List the names of the employee drawing the Highest salary
YORK );
2.
3.
In Usage
IN :- Equal to any member in the list
List the names of the Employee drawing the highest salary in department wise
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
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
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.
ename, job, sal emp sal < ANY ( SELECT sal FROM emp WHERE job=CLERK ) AND job <> CLERK;
ANY Usage
< ANY
> ANY = ANY
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
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 );
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 );
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
FROM emp,dept
WHERE emp.deptno = dept.deptno;
NOTE: Equijoins are called simple or inner joins
FROM
emp e,salgrade s WHERE e.sal between s.losal and s.hisal
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 (+)
SELECT e.empno, e.ename, d.deptno, d.loc FROM emp e, dept d WHERE e.deptno (+) = d.deptno;
TRANSACTION
A Collection of Statements that is either Completely Executed or Not Executed at All.
Commit Point
TRANSACTION
INSERT
UPDATE
UPDATE
DELETE
ROLLBACK
Insert ... Update Update
Commit Point TRANSACTION
Rollback;
Commit Point
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
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
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
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
U2
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
Michael
Michael
REVOKE Command
REVOKE {Privileges | All} ON Object FROM {Users | Public}
Michael
View
Sequence
Index Synonym
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.
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 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))