Professional Documents
Culture Documents
Being Presented By
PM Karthick
Corporate Trainer Executive
Structured Query Language (SQL) is the set of statements with which all programs and users access data in an Oracle database.
as individual units.
It provides automatic navigation to the data. It uses statements that are complex and
logical level.
Introduction to ORACLE
Objectives
What is RDBMS ? Advantages of SQL and PLSQL RDBMS Vs ORDBMS Uses and benefits of PL/SQL
Database
Data Models
Server
Tables on disk
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.
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
Relational DB Properties
A relational database
- SQL Statements to be used for manipulating the database. - No Physical Pointers to access and store relations between Tables. - Set of Operators for Functionality
Dept
Location ------------Dallas New York Santa Clara
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.
SIMPLIFY To SOLVE. Objects and Interactions They replicate real time environment.
Characteristics of OOPS
Platform Independency
USER 3
USER 1
USER 2
USER 4
OS
SQL Statements
SELECT
Data retrieval
SQL Statements
Objectives
SQL SELECT statements A basic SELECT statement SQL statements and SQL*Plus commands
SELECT FROM
Select Clause determines what columns The From Clause determines which table.
SQL is not Case Sensitive. Keywords cannot be split or abbreviated. SQL Statements can be split across lines. Clauses are placed in different lines, to promote readability.
SQL> SELECT * 2 FROM departments; DEPTNO --------10 20 30 40 DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS LOC ------------NEW YORK DALLAS CHICAGO BOSTON
SQL> SELECT deptno, loc 2 FROM departments; DEPTNO --------10 20 30 40 LOC ------------NEW YORK DALLAS CHICAGO BOSTON
Default Column Headings Default justification - Date and Character Data is Left Justified - Numeric Data is Right Justified Display Headings in UPPER CASE. Character / Date Columns headings will be Truncated. Numerical Columns headings are not truncated. Column name can be replaced by the Alias name
Arithmetic Expressions
Basic Arithmetic operators
Operator + * /
SQL> SELECT ename, sal, sal+300 2 FROM employees; ENAME SAL SAL+300 ---------- --------- --------KING 5000 5300 BLAKE 2850 3150 CLARK 2450 2750 JONES 2975 3275 MARTIN 1250 1550 ALLEN 1600 1900 ... 14 rows selected.
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.
ENAME JOB COMM ---------- --------- --------KING PRESIDENT BLAKE MANAGER ... TURNER SALESMAN 0 ... 14 rows selected.
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.
The Heading name is replaced for the current SELECT Statement. AS Keyword [ Optional ] between the column name and the actual alias name Double Quotation Marks.
Concatenates the Columns of any data type. A Resultant column will be a Single column.
Employees ------------------KINGPRESIDENT BLAKEMANAGER CLARKMANAGER JONESMANAGER MARTINSALESMAN ALLENSALESMAN ... 14 rows selected.
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
Summary
SELECT FROM
Objectives
Using WHERE Clause Specify the Selection of rows retrieved by the WHERE Clause.
SELECT FROM [WHERE [DISTINCT] {*, column [alias], ...} table condition(s)];
Character / Dates are Represented by the Single Quotation Marks. Default date format is 'DD-MON-YY'
Comparison Operators
Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to
ENAME SAL ---------- --------MARTIN 1250 TURNER 1500 WARD 1250 ADAMS 1100 MILLER 1300
Lower limit
Higher limit
Using IN Operator
IN Operator to check with a List of Values.
ENAME SAL MGR ---------- --------- --------FORD 3000 7566 SMITH 800 7902 SCOTT 3000 7566 ADAMS 1100 7788
Like Keyword Does Wildcard Searches in Valid String Values.. % ---------- zero or many characters _ ----------- one character
SQL> SELECT 2 FROM 3 WHERE ename emp ename LIKE 'S%';
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
EMPNO ENAME JOB SAL --------- ---------- --------- --------7839 7698 7782 7566 7654 KING BLAKE CLARK JONES MARTIN PRESIDENT MANAGER MANAGER MANAGER SALESMAN 5000 2850 2450 2975 1250
SQL> SELECT ename, job 2 FROM emp 3 WHERE job NOT IN ('CLERK','MANAGER','ANALYST');
Rules of Precedence
Order Evaluated 1 2 3 4
ORDER BY Clause
EMPNO ENAME 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.
Sorting by Multiple Columns The order of ORDER BY list is the order of sort.
SQL> SELECT ename, deptno, sal 2 FROM emp 3 ORDER BY deptno, sal DESC; ENAME DEPTNO SAL ---------- --------- --------KING 10 5000 CLARK 10 2450 MILLER 10 1300 FORD 20 3000 ... 14 rows selected.
Summary
[DISTINCT] {*, column [alias], ...} table condition(s)] {column, expr, alias} [ASC|DESC]];
SQL Functions
Objectives
Get an awareness of the Various SQL Functions available. Types of Functions in the SELECT Statement. Conversion functions
Functions
MultipleMultiple-row functions
SingleSingle-row functions
Single-Row Functions
Single-Row Functions
Number
Conversion
Date
Character Functions
Character functions
SQL> SELECT empno, ename, deptno 2 FROM emp 3 WHERE ename = 'blake'; no rows selected SQL> SELECT 2 FROM 3 WHERE empno, ename, deptno emp LOWER(ename) = 'blake';
Character Functions
Result
******5000
SQL> SELECT ename, CONCAT (ename, job), LENGTH(ename), 2 INSTR(ename, 'A') 3 FROM emp 4 WHERE SUBSTR(job,1,5) = 'SALES';
ENAME ---------MARTIN ALLEN TURNER WARD CONCAT(ENAME,JOB) LENGTH(ENAME) INSTR(ENAME,'A') ------------------- ------------- ---------------MARTINSALESMAN 6 2 ALLENSALESMAN 5 1 TURNERSALESMAN 6 0 WARDSALESMAN 4 2
Number Functions
- ROUND:Rounds value to specified decimal
- ROUND(45.926, 2) 45.93 45.92
- TRUNC:
- TRUNC(45.926, 2)
- CEIL (num): It returns the smallest integer greater than the given number. CEIL (123.456) 124
Working with Dates Stores date with Century. Default date format is DD-MON-YY. SYSDATE is a Function which returns the System date and time. DUAL is a dummy table used to view SYSDATE.
Add/Subtract a Number to the Date. Add/Subtract hours to a date by dividing the number of hours by 24.
Conversion Functions
Conversion Functions
TO_NUMBER
TO_DATE
NUMBER
CHARACTER
DATE
TO_CHAR
TO_CHAR
TO_CHAR(date, 'fmt')
Date Format
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
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.
HH24:MI:SS AM
15:45:32 PM
Add character strings by enclosing them in double quotation marks. Number suffixes spell out numbers.
DD "of" MONTH
12 of OCTOBER
ddspth
fourteenth
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
50-99
NVL lets you replace a null with a string in the results of a query. - If expr1 is null, then NVL returns expr2. If expr1 is not null, then NVL returns expr1. - The arguments expr1 and expr2 can have any data type. If their data types are different, then Oracle converts expr2 to the data type of expr1 before comparing them. - The data type of the return value is always the same as the data type of expr1, unless expr1 is character data, in which case the return values data type is VARCHAR2 and is in the character set of expr1.
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
DEPT
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON
MILLER ...
EMPNO DEPTNO LOC ----- ------- -------7839 10 NEW YORK 7698 30 CHICAGO 7782 10 NEW YORK 7566 20 DALLAS 7654 30 CHICAGO 7499 30 CHICAGO ... 14 rows selected.
What Is a Join?
A JOIN Basically involves more than one Table to interact with.
Where clause specifies the JOIN Condition. Ambiguous Column names are identified by the Table name.
Cartesian Product
A Cartesian product is formed when: A Join Condition is completely omitted All rows in the first table are joined to all rows in the second table
Cartesian Product
EMP (14 rows)
EMPNO -----7839 7698 ... 7934 ENAME ----KING BLAKE ... DEPTNO ... -----... 10 ... 30 10
DEPT (4 rows)
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON
MILLER ...
ENAME DNAME --------------KING ACCOUNTING BLAKE ACCOUNTING ... KING RESEARCH BLAKE RESEARCH ... 56 rows selected.
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.
What Is an Equijoin?
EMP
EMPNO ENAME DEPTNO ------ ------- ------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 ... 14 rows selected.
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. LOC -------NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO DALLAS DALLAS
EMPNO ENAME DEPTNO DEPTNO LOC ----- ------ ------ ------ --------7839 KING 10 10 NEW YORK 7698 BLAKE 30 30 CHICAGO 7782 CLARK 10 10 NEW YORK 7566 JONES 20 20 DALLAS ... 14 rows selected.
SQL> SELECT e.empno, e.ename, e.deptno, 2 d.deptno, d.loc 3 FROM emp e, dept d 4 WHERE e.deptno=d.deptno;
ORD
CUSTID ORDID ------- ------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.
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 ------ ------- -----7839 KING 5000 7698 BLAKE 2850 7782 CLARK 2450 7566 JONES 2975 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 ... 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
Retrieving Rows:Non-Equijoin
SQL> 2 3 4
ENAME SAL GRADE ---------- --------- --------JAMES 950 1 SMITH 800 1 ADAMS 1100 1 ... 14 rows selected.
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, Oracle combines and returns rows of the table that satisfy the join condition.
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
WORKER.ENAME||'WORKSFOR'||MANAG ------------------------------BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE ... 13 rows selected.
Outer Joins
An outer join extends the result of a simple join. 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. To write a query that performs an outer join of tables A and B and returns all rows from A (a left outer join), use the LEFT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator (+) to all columns of B in the join condition in the WHERE clause. For all rows in A that have no matching rows in B, Oracle returns null for any select list expressions containing columns of B. n To write a query that performs an outer join of tables A and B and returns all rows from B (a right outer join), use the RIGHT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator (+) to all columns of A in the join condition in the WHERE clause. For all rows in B that have no matching rows in A, Oracle returns null for any select list expressions containing columns of A. n To write a query that performs an outer join and returns all rows from A and B, extended with nulls if they do not satisfy the join condition (a full outer join), use the FULL [OUTER] JOIN syntax in the FROM clause. Oracle Corporation recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions, 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.Joins
Outer Joins
EMP
ENAME ----KING BLAKE CLARK JONES ... DEPTNO -----10 30 10 20
DEPT
DEPTNO -----10 30 10 20 ... 40 DNAME ---------ACCOUNTING SALES ACCOUNTING RESEARCH OPERATIONS
Outer Joins To see also the rows that do not usually meet the join condition. Outer join operator is the plus sign (+).
SELECT table.column, table.column FROM table1, table2 WHERE table1.column(+) = table2.column; SELECT table.column, table.column FROM table1, table2 WHERE table1.column = table2.column(+);
ENAME DEPTNO DNAME ---------- --------- ------------KING 10 ACCOUNTING CLARK 10 ACCOUNTING ... 40 OPERATIONS 15 rows selected.
Summary
Types of Joins
Equijoins Non- Equijoins Outer Joins Self Joins
Objectives
EMP
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
MAX(SAL) --------5000
AVG(COMM) --------550
AVG(NVL(COMM,0)) ---------------157.14286
2916.6667
average DEPTNO AVG(SAL) salary ------- --------in EMP 2175 10 2916.6667 table 20 2175 for each department 30 1566.6667
1566.6667
Modularize rows in a table into smaller groups by using the GROUP BY clause.
--------- ---------
sum salaries in the EMP table for each job, grouped by department
SQL> SELECT deptno, job, sum(sal) 2 FROM emp 3 GROUP BY deptno, job;
DEPTNO JOB SUM(SAL) --------- --------- --------10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 ANALYST 6000 20 CLERK 1900 ... 9 rows selected.
Illegal Queries
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) * ERROR at line 1: ORA-00937: not a single-group group function
Illegal Queries
SQL> 2 3 4
WHERE AVG(sal) > 2000 * ERROR at line 3: ORA-00934: group function is not allowed here
DEPTNO 10 20
3000
--------- ---------
2850
SQL> 2 3 4
SQL> 2 3 4 5 6
job, SUM(sal) PAYROLL emp job NOT LIKE 'SALES%' job SUM(sal)>5000 SUM(sal);
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];
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
Main Query
Subqueries
SELECT FROM WHERE select_list table expr operator (SELECT FROM
select_list table);
The subquery (inner query) executes once before the main query. The result of the subquery is used by the main query (outer query).
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
Guidelines for Subqueries Enclose subqueries in parentheses. Place subqueries on the right side of the comparison operator. Do not add an ORDER BY clause to a subquery. Use single-row operators with single-row subqueries. Use multiple-row operators with multiplerow subqueries.
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
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
Single-Row Subqueries
SQL> 2 3 4 5 6 7 8 9 10
AND
ename, job employee job = (SELECT FROM WHERE sal > (SELECT FROM WHERE
CLERK
800
MIN(sal) employee);
SQL> 2 3 4 5 6 7
800
What Is Wrong ?
SQL> SELECT empno, ename 2 FROM employee 3 WHERE sal = 4 (SELECT 5 FROM 6 GROUP BY
ERROR: ORA-01427: single-row subquery returns more than one row no rows selected
SQL> SELECT ename, job 2 FROM employee 3 WHERE job = 4 (SELECT job 5 FROM employee 6 WHERE ename='SMYTHE');
no rows selected
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
SQL> 2 3 4 5 6 7
AND
empno, ename, job 1300 1100 employee 800 sal < ANY 950 (SELECT sal FROM employee WHERE job = 'CLERK') job <> 'CLERK'; JOB --------SALESMAN SALESMAN
empno, ename, job 2175 employee 2916.6667 sal > ALL (SELECT FROM GROUP BY JOB --------PRESIDENT MANAGER ANALYST ANALYST
1566.6667
Multiple-Column Subqueries
Main query
MANAGER 10
Subquery
SALESMAN MANAGER CLERK 30 10 20
to
Multiple-Column Subqueries
Display the name, dept. no, salary, and commission of any employee whose salary and commission matches both the commission and salary of any employee in department 30.
ename, deptno, sal, comm employee (sal, NVL(comm,-1)) IN (SELECT sal, NVL(comm,-1) FROM employee WHERE deptno = 30);
SQL> 2 3 4 5 6
SELECT FROM
WHERE AND
a.ename, a.sal, a.deptno, b.salavg employee a, (SELECT deptno, avg(sal) salavg FROM employee GROUP BY deptno) b a.deptno = b.deptno a.sal > b.salavg;
ENAME SAL DEPTNO SALAVG ---------- --------- --------- ---------KING 5000 10 2916.6667 JONES 2975 20 2175 SCOTT 3000 20 2175 ... 6 rows selected.
SQL> 2 3 4 5 6 7 8 9 10
WITH summary AS (SELECT dname,sum(sal) as dept_total FROM emp a , dept b WHERE a.deptno = b.deptno GROUP BY dname); SELECT dname,dept_total FROM summary WHERE dept_total > (SELECT sum(dept_total)*1/3 FROM summary) ORDER BY dept_total desc; DEPT_TOTAL ---------10875
DNAME --------------RESEARCH
Non-Correlated
SELECT dept.name FROM dept WHERE dept.id NOT IN ( SELECT dept_id FROM emp WHERE dept_id IS NOT NULL)
Correlated
SELECT dept.dname FROM dept WHERE EXISTS (SELECT deptno FROM emp WHERE emp.deptno = deptno) /
Correlated Subqueries
Query to diplay name of highest salary taker. SELECT EMPNO, ENAME FROM EMP A WHERE 1 > ( SELECT COUNT(*) FROM EMP B WHERE A.SAL < B.SAL)
Summary
Single row subqueries A multiple- ROW subquery returns more than one column. A multiple-column subquery can also be used in the FROM clause of a SELECT statement.
DML Statements
Objectives
Insert rows into a table Update rows in a table Delete rows from a table Controlling the Transactions
A transaction consists of a collection of DML statements that form a logical unit of work.
INSERT Statement
Insert a new row containing values for each column. List values in the default order of the columns in the table. Optionally list the columns in the INSERT clause. Enclose character and date values within SQL> INSERT INTO department single quotation marks. (deptno, dname, loc) 2 VALUES (50, 'DEVELOPMENT', 'DETROIT');
1 row created.
Insert Rows with Null Values Implicit method: Omit the column from the column list.
SQL> INSERT INTO 2 VALUES 1 row created. department (deptno, dname ) (60, 'MIS');
employee (empno, ename, job, mgr, hiredate, sal, comm, deptno) (7196, USER, 'SALESMAN', 7782, SYSDATE, 2000, NULL, 10);
Enter value for department_id: 80 Enter value for department_name: EDUCATION Enter value for location: ATLANTA 1 row created.
Insert all the employees details who are managers into bonus and tax for further manipulation INSERT ALL
- INTO BONUS (EMPNO,ANNUAL_SAL) - VALUES(EMPNO,SAL*12) - INTO TAX(EMPNO, GROSS_INCOME) - VALUES(EMPNO,(SAL+NVL(COMM,0))*12) - SELECT EMPNO,SAL,COMM FROM EMP - WHERE JOB=MANAGER
INSERT ALL WHEN JOB=CLERK then INTO BONUS(EMPNO,ANN_SAL) VALUES(EMPNO, SAL*12) WHEN JOB=SALESMAN then INTO BONUS(EMPNO,ANN_SAL) VALUES(EMPNO, (SAL+NVL(COMM,0))*12) SELECT EMPNO,job,SAL,COMM FROM EMP
Copying from Another Table Write your INSERT statement with a subquery.
SQL> INSERT INTO managers(id, name, salary, hiredate) 2 SELECT empno, ename, sal, hiredate 3 FROM employee 4 WHERE job = 'MANAGER'; 3 rows created.
Do not use the VALUES clause. Match the number of columns in the INSERT clause to those in the subquery.
UPDATE Statement
All rows in the table are modified if you omit the WHERE clause.
Updating Rows:
UPDATE emp * ERROR at line 1: ORA-02291: integrity constraint (USR.EMP_DEPTNO_FK) violated - parent key not found
DELETE Statement
You can remove existing rows from a table by using the DELETE statement.
table condition];
Deleting Rows from a Table Specific row or rows are deleted when you specify the WHERE clause.
SQL> DELETE FROM 2 WHERE 1 row deleted. department dname = 'DEVELOPMENT';
All rows in the table are deleted if you omit the WHERE clause.
SQL> DELETE FROM 4 rows deleted. department;
Deleting Rows:
DELETE FROM dept * ERROR at line 1: ORA-02292: integrity constraint (USR.EMP_DEPTNO_FK) violated - child record found
Summary
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
Objectives
Describe the main database objects Create tables Describe the data types that can be used when specifying column definition Alter table definitions Drop, rename, and truncate tables
Database Objects
Object Table
View
Generates primary key values Improves the performance of some queries Gives alternative names to objects
Naming Conventions
Must begin with a letter Can be 130 characters long Must contain only AZ, az, 09, _, $, and # Must not duplicate the name of another object owned by the same user Must not be an Oracle Server reserved word
You specify: - Table name - Column name, column data type, and column size
Tables belonging to other users are not in the users schema. You should use the owners name as a prefix to the table.
The DEFAULT Option Specify a default value for a column during an insert.
hiredate DATE DEFAULT SYSDATE,
Legal values are literal value, expression, or SQL function. Illegal values are another columns name or pseudo column. The default data type must match the column data type.
Creating Tables
Create the table.
SQL> CREATE TABLE department 2 (deptno NUMBER(2), 3 dname VARCHAR2(14), 4 loc VARCHAR2(13)); Table created.
Data types
Data type VARCHAR2(size) CHAR(size) NUMBER(p,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
MAXIMUM SIZE
CHAR- 4000 bytes NUMBER- The precision p can range from 1 to 38.The scales can range from -84 to 127. DATE- from January 1, 4712 BC to December 31, 9999 AD. LONG- 2 Gigabytes CLOB/BLOB 4GB
Create a table and insert rows by combining the CREATE TABLE statement and AS subquery option.
CREATE TABLE table [column(, column...)] AS subquery;
Match the number of specified columns to the number of subquery columns. Define columns with column names and default values.
SQL> CREATE TABLE dept30 2 AS 3 SELECT empno, ename, sal*12 ANNSAL, hiredate 4 FROM employee 5 WHERE deptno = 30; Table created. SQL> DESCRIBE dept30 Name Null? ---------------------------- -------EMPNO NOT NULL ENAME ANNSAL HIREDATE Type ----NUMBER(4) VARCHAR2(10) NUMBER DATE
ALTER TABLE Statement Add a new column Modify an existing column Drop an existing column, Define a default value for the new column
ALTER TABLE table ADD (column data type [DEFAULT expr] [, column data type]...); ALTER TABLE table MODIFY (column data type [DEFAULT expr] [, column data type]...); ALTER TABLE table DROP column column_name;
Adding a Column
DEPT30
EMPNO -----7698 7654 7499 7844 ... ENAME ANNSAL ---------- -------BLAKE 34200 MARTIN 15000 ALLEN 19200 TURNER 18000
New column
HIREDATE 01-MAY-81 28-SEP-81 20-FEB-81 08-SEP-81 JOB
DEPT30
EMPNO -----7698 7654 7499 7844 ... ENAME ANNSAL ---------- -------BLAKE 34200 MARTIN 15000 ALLEN 19200 TURNER 18000 HIREDATE 01-MAY-81 28-SEP-81 20-FEB-81 08-SEP-81 JOB
Modifying a Column You can change a column's data type, size, and default value.
ALTER TABLE dept30 MODIFY (ename VARCHAR2(15)); Table altered.
A change to the default value affects only subsequent insertions to the table.
Dropping a Column You can remove a column and its contents entirely from the table.
ALTER TABLE dept30 DROP COLUMN ename; Table altered.
Dropping a Table
All data and structure in the table is deleted. Any pending transactions are committed. All indexes are dropped. You cannot roll back this statement.
SQL> DROP TABLE dept30; Table dropped.
Rename an Object
To change the name of a table, view, sequence, or synonym, you execute the RENAME statement.
SQL> RENAME dept TO department; Table renamed.
Adding Comments to a Table You can add comments to a table or column by using the COMMENT statement.
SQL> COMMENT ON TABLE employee 2 IS 'Employee Information'; Comment created.
Constraints
Objectives
Create the following types of constraints: - NOT NULL - UNIQUE key - PRIMARY KEY - FOREIGN KEY - CHECK Query the USER_CONSTRAINTS table to view all constraint definitions and names.
What Are Constraints? Constraints enforce rules at the table level.Constraints prevent the deletion of a table if there are dependencies. The following constraint types are valid in Oracle: - NOT NULL - UNIQUE Key - PRIMARY KEY - FOREIGN KEY - CHECK
Constraint Guidelines
Name a constraint or the Oracle Server will generate a name by using the SYS_Cn format. Create a constraint: - At the same time as the table is created - After the table has been created Define a constraint at the column or table level. View a constraint in the data dictionary.
Defining Constraints
CREATE TABLE [schema.]table (column data type [DEFAULT expr] [column_constraint], [table_constraint]);
CREATE TABLE employee( empno NUMBER(4), ename VARCHAR2(10), deptno NUMBER(7,2) NOT NULL, CONSTRAINT emp_empno_pk PRIMARY KEY (EMPNO));
Defining Constraints
EMP
EMPNO ENAME 7839 7698 7782 7566 ... KING BLAKE CLARK JONES JOB PRESIDENT MANAGER MANAGER MANAGER ... 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)
DEPARTMENT
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON
department( NUMBER(2), VARCHAR2(14), VARCHAR2(13), dept_dname_uk UNIQUE (dname), dept_deptno_pk PRIMARY KEY(deptno));
EMPLOYEE
EMPNO ENAME 7839 KING 7698 BLAKE ... ... COMM DEPTNO 10 30 Not allowed (DEPTNO9 does not exist in the DEPT table) Allowed FOREIGN KEY
SQL> CREATE TABLE employee( 2 empno NUMBER(4), 3 ename VARCHAR2(10) NOT NULL, 4 job VARCHAR2(9), 5 mgr NUMBER(4), 6 hiredate DATE, 7 sal NUMBER(7,2), 8 comm NUMBER(7,2), 9 deptno NUMBER(7,2) NOT NULL, 10 CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno) 11 REFERENCES dept (deptno));
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
The CHECK Constraint Defines a condition that each row must satisfy Expressions that are not allowed: - References to pseudo columns CURRVAL, NEXTVAL, and ROWNUM - Calls to SYSDATE, UID, USER, and USERENV functions - Queries that refer to other values in other rows
..., deptno NUMBER(2), CONSTRAINT emp_deptno_ck CHECK (DEPTNO BETWEEN 10 AND 99),...
Adding a Constraint
Add or drop, but not modify, a constraint Enable or disable constraints Add a NOT NULL constraint by using the MODIFY clause
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.
SQL> ALTER TABLE employee 2 ADD CONSTRAINT emp_mgr_fk 3 FOREIGN KEY(mgr) REFERENCES emp(empno); Table altered.
Dropping a Constraint Remove the emp_mgr_fk constraint from the EMP table.
SQL> ALTER TABLE 2 DROP CONSTRAINT Table altered. EMP emp_mgr_fk;
Remove the PRIMARY KEY constraint on the DEPT table and drop the associated FOREIGN KEY constraint on the EMP.DEPTNO column.
SQL> ALTER TABLE DEPT 2 DROP PRIMARY KEY CASCADE; Table altered.
Disabling Constraints Execute the DISABLE clause of the ALTER TABLE statement to deactivate an integrity constraint. Apply the CASCADE option to disable dependent integrity constraints.
SQL> ALTER TABLE 2 DISABLE CONSTRAINT Table altered. EMP emp_empno_pk CASCADE;
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. EMP emp_empno_pk;
A UNIQUE or PRIMARY KEY index is automatically created if you enable a UNIQUE key or PRIMARY KEY constraint.
Viewing Constraints
Query the USER_CONSTRAINTS table to view all constraint definitions and names.
SQL> 2 3 4
SELECT constraint_name, constraint_type, search_condition FROM user_constraints WHERE table_name = 'EMPLOYEE'; C C C P SEARCH_CONDITION ------------------------EMPNO IS NOT NULL DEPTNO IS NOT NULL
constraint_name, column_name user_cons_columns table_name = 'EMPLOYEE'; COLUMN_NAME ---------------------DEPTNO EMPNO MGR EMPNO DEPTNO
Summary Create the following types of constraints: - NOT NULL - UNIQUE key - PRIMARY KEY - FOREIGN KEY - CHECK Query the USER_CONSTRAINTS table to view all constraint definitions and names.
Views
Objectives Describe a view Create a view Retrieve data through a view Alter the definition of a view Insert, update, and delete data through a view Drop a view
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
To restrict database access To make complex queries easy To allow data independence To present different views of the same data
Creating a View
You embed a subquery within the CREATE VIEW statement.
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)] ASThe subquery can contain complex SELECT subquery [WITH READ ONLY] syntax.
Creating a View Create a view, EMPVU10, that contains details of employees in department 10.
SQL> 2 3 4 View CREATE VIEW AS SELECT FROM WHERE created. empvu10 empno, ename, job employee deptno = 10;
Describe the structure of the view by using the SQL*Plus DESCRIBE command.
SQL> DESCRIBE empvu10
Select the columns from this view by the given alias names.
SQL> 2
SELECT * FROM salvu30; NAME SALARY ---------- --------BLAKE 2850 MARTIN 1250 ALLEN 1600 TURNER 1500 JAMES 950 WARD 1250
6 rows selected.
Querying a View
SQL*Plus
SELECT * FROM empvu10;
USER_VIEWS
EMPVU10
SELECT FROM WHERE empno, ename, job employee deptno = 10;
EMP
Modifying a View Modify the EMPVU10 view by using CREATE OR REPLACE VIEW clause. Add an alias for each column name.
SQL> 2 3 4 5 View CREATE OR REPLACE VIEW empvu10 (employee_number, employee_name, job_title) AS SELECT empno, ename, job FROM employee WHERE deptno = 10; created.
Column aliases in the CREATE VIEW clause are listed in the same order as the columns in the subquery.
SQL> 2 3 4 5 6 7 View
dept_sum_vu (name, minsal, maxsal, avgsal) d.dname, MIN(e.sal), MAX(e.sal), AVG(e.sal) employee e, department d e.deptno = d.deptno d.dname;
SQL> 2 3 4 5 6 View
CREATE OR REPLACE VIEW empvu10 (employee_number, employee_name, job_title) AS SELECT empno, ename, job FROM employee WHERE deptno = 10 WITH READ ONLY; created.
Any attempt to perform a DML on any row in the view will result in Oracle Server error ORA01752.
Removing a View
Remove a view without losing data because a view is based on underlying tables in the database.
Summary A view is derived from data in other tables or other views. A view provides the following advantages: - Restricts database access - Simplifies queries - Provides data independence - Allows multiple views of the same data - Can be dropped without removing the underlying data
Objectives
Describe some database objects and their uses Create, maintain, and use sequences Create and maintain indexes Create private and public synonyms
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
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. Do not use the CYCLE option.
SQL> CREATE SEQUENCE dept_deptno 2 INCREMENT BY 1 3 START WITH 91 4 MAXVALUE 100 5 created.
Confirming Sequences
Pseudo columns NEXTVAL returns the next available sequence value. CURRVAL obtains the current sequence value. ROWID uniquely identify the rows in your table. LEVEL a special column you can reference only in a hierarchical query
Using a Sequence Caching sequence values in memory allows faster access to those values. Gaps in sequence values can occur when:
- A rollback occurs - The system crashes - A sequence is used in another table
View the next available sequence, if it was created with NOCACHE, by querying the USER_SEQUENCES table.
Modifying a Sequence
Change the increment value, maximum value, minimum value, cycle option, or cache option.
SQL> ALTER SEQUENCE dept_deptno 2 INCREMENT BY 1 3 MAXVALUE 999999 4 NOCACHE 5 NOCYCLE; Sequence altered.
Removing a Sequence
Remove a sequence from the data dictionary by using the DROP SEQUENCE statement. Once removed, the sequence can no longer be referenced.
SQL> DROP SEQUENCE dept_deptno; Sequence dropped.
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
Automatically
- 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.
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);
Confirming Indexes The USER_INDEXES data dictionary view contains the name of the index and its uniqueness. The USER_IND_COLUMNS view contains the index name, the table name, and the column name.
SQL> 2 3 4 5 SELECT FROM WHERE AND ic.index_name, ic.column_name, ic.column_position col_pos,ix.uniqueness user_indexes ix, user_ind_columns ic ic.index_name = ix.index_name ic.table_name = 'EMP';
To drop an index, you must be the owner of the index or have the DROP ANY INDEX privilege.
Synonyms
Purpose Use the CREATE SYNONYM statement to create a synonym, which is an alternative name for a table, view, sequence, procedure, stored function, package, materialized view, Java class schema object, user-defined object type, or another synonym. Synonyms provide both data independence and location transparency. Synonyms permit applications to function without modification regardless of which user owns the table or view and regardless of which database holds the table or view. However, synonyms are not a substitute for privileges on database objects. Such privileges must be granted to a user before the user can use the synonym. You can refer to synonyms in the following DML statements: SELECT, INSERT, UPDATE, DELETE, EXPLAIN PLAN, and LOCK TABLE. You can refer to synonyms in the following DDL statements: AUDIT, NOAUDIT, GRANT, REVOKE, and COMMENT.
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 users schema, you must have CREATE ANY SYNONYM system privilege. To create a PUBLIC synonym, you must have CREATE PUBLIC SYNONYM system privilege.
Synonyms
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
Database administrator
Privileges
Database security - System security - Data security System privileges: Gain access to the database Object privileges: Manipulate the content of the database objects Schema: Collection of objects, such as tables, views, and sequences
System Privileges
More than 80 privileges are available. The DBA has high-level system privileges. - Create new users - Remove users - Remove tables - Backup tables
Creating Users
The DBA creates users by using the CREATE USER statement. CREATE USER IDENTIFIED BY user password;
An application developer may have the following system privileges: CREATE SESSION CREATE TABLE CREATE SEQUENCE CREATE VIEW CREATE PROCEDURE
SQL> GRANT create table, create sequence, create view 2 TO scott; Grant succeeded.
What Is a Role?
Users
Manager
Creating Roles
When the user account is created, a password is initialized. Users can change their password by using the ALTER USER statement.
SQL> ALTER USER scott 2 IDENTIFIED BY lion; User altered.
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. An owner can give specific privileges on that owners object.
GRANT ON TO [WITH GRANT object_priv [(columns)] object {user|role|PUBLIC} OPTION];
GRANT Keywords
Allow all users on the system to query data from Alices DEPARTMENT table.
SQL> GRANT select 2 ON alice.department 3 TO PUBLIC; Grant succeeded.
Revoke Object Privileges You use the REVOKE statement to revoke privileges granted to other users. Privileges granted to others through the WITH GRANT OPTION will also be revoked.
As user Alice, revoke the SELECT and INSERT privileges given to user Scott on the DEPARTMENT table.
Summary
Allows the DBA to create a user Allows the user to give other users privileges to access the user's objects
Allows the DBA to create a collection of privileges Allows users to change their Removes privileges on an object from users
Objectives
Oracle
Architecture Oracle Database The Study Phases Objectives - The Memory Architecture - The Disk Architecture - The Back Ground Processes The Logical Architecture The Physical Architecture How Oracle Works
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
TL-812
4,000,000 KByte 1,200,000 KByte 2,100 KByte
DBW0
CKPT
LGWR
ARCH
Archive Log Mode(50M)
Oracle Architecture
Oracle Database
Oracle Database
Physical
Logical
Tablespaces DB Files Non DB Files Segments DataFile RedologFile PWD File INIT File
Extents
Control File
Data Blocks
The 3 Base
1. Memory Architecture
2. Disk Architecture
3. Background Processes
Disk
Background processes Disk Architecture
SGA
Disk Architecture
DATA FILES
LOG FILES
CONTROL FILES
Data Files
They Dynamically Extend when the database runs out of space. One or more Data files may compose of a Tablespace.
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
INSTANCE
SGA
Library cache Data Dictionary cache
PMON
SMON
DBWR
LGWR
CKPT
Others
Background structures
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
Database Buffer Cache The Latest used blocks by the Database. Minimize the disk IO and Improve Performance. Redo log Buffer Cache Stores the log of modifications made to the database.
Shared Pool
Shared Pool
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.
Background Processes - DBWR : Writes the modified blocks from the database buffer cache to the data files. - LGWR : Writes redo log entries to the redo log files
- SMON : Dedicated to perform instance recovery, It Cleans up Temp segments that are not in use and coalesce Free Extents. - PMON : Performs recovery when a client/user process fails. - Dnnn : Dispatcher processes are present in a Shared server configuration.
Background Processes - 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. - ARCH : Copies the online Redolog files when there is a log switch. The copied files are called offline/archived redo log files. - RECO : Used in a distributed environment when the transactions are pending due to some network failures.
Enlarging Tablespace
Enlarging Tablespace
Enlarging Database
By adding a Tablespace
How Oracle Works User process from the Workstation. The Server detects the connection and a Dedicated server process gets created. The Server Process receives the Request and is checked in the shared pool. At PGA : A Private SQL Area is created.