P. 1
SQL

SQL

|Views: 513|Likes:
Published by manishgtk

More info:

Categories:Types, Research
Published by: manishgtk on Jul 12, 2010
Copyright:Attribution Non-commercial

Availability:

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

06/19/2013

pdf

text

original

Sections

SQL Statements

‡SELECT ‡INSERT ‡UPDATE ‡DELETE ‡CREATE ‡ALTER ‡DROP ‡RENAME ‡TRUNCATE ‡COMMIT ‡ROLLBACK ‡SAVEPOINT
Data Retrieval Data manipulation language (DML)

Data definition language (DDL)

Transaction Control Language (TCL)

Data Retrieval SELECT

SELECT STATEMENT
Syntax : SELECT [ DISTINCT ] ( [ table ] . * | expr [alias ], ... ] FROM table [ alias ] , ... [ WHERE [ join condition ] ... ] [ AND [ row condition ] ... ] [ OR [ another row condition ] ] [ GROUP BY [ expr | column ]] [ HAVING [ group condition ]] [ ORDER BY [ expr | column ] [ ASC |DESC ] ] ;

Consider two tables: ‡ stud_name, containing the id and names of all students ‡ stud_reg, having the registration details for the courses that the students opt for. Consider this query: Select the most recent registration data of students. All the students must be listed even if they do not have any registration details.

Approach 1:
SELECT n.id ID, n.name Name, r1.seq Sequence, r1.sponsor Sponsor, r1.fee Fee, r1.regdate "REG DATE" FROM stud_name n, stud_reg r1 WHERE r1.stud_id(+) = n.id AND (r1.rowid IS NULL OR r1.seq = (SELECT MAX(r2.seq) FROM stud_reg r2 WHERE r2.stud_id = n.id)) ORDER BY 1;

Approach 2:
SELECT n.id ID, n.name Name, TO_NUMBER('') Sequence, '' Sponsor, TO_NUMBER('') Fee, '' "REG DATE" FROM stud_name n WHERE NOT EXISTS (SELECT 'x' FROM stud_reg r WHERE r.stud_id = n.id) UNION

SELECT n.id ID, n.name Name, r1.seq Sequence, r1.sponsor Sponsor, r1.fee Fee, TO_CHAR(r1.regdate) "REG DATE" FROM stud_name n, stud_reg r1 WHERE r1.stud_id = n.id AND r1.seq = (SELECT MAX(r2.seq) FROM stud_reg r2 WHERE r2.stud_id = n.id);

(Approach 2 contd.)

SELECT STATEMENT
Syntax : SELECT [ DISTINCT ] ( [ table ] . * | expr [alias ], ... ] FROM table [ alias ] , ... [ WHERE [ join condition ] ... ] [ AND [ row condition ] ... ] [ OR [ another row condition ] ] [ GROUP BY [ expr | column ]] [ HAVING [ group condition ]] [ ORDER BY [ expr | column ] [ ASC |DESC ] ] ;

Capabilities of SQL SELECT Statements
Restriction Projection

Table 1

Product / Join

Table 1

Table 1

Table 2

EMP

Limiting Rows Using a Restriction
JOB PRESIDENT MANAGER MANAGER MANAGER ... DEPTNO 10 30 10 20 KING BLAKE CLARK JONES

EMPNO ENAME 7839 7698 7782 7566 ...

³Retrieve all employees in department 10.´

EMP
EMPNO ENAME JOB ... DEPTNO 10 10 10

7839 KING PRESIDENT 7782 CLARK MANAGER 7934 MILLER CLERK

Creating a Projection on a Table DEPT
DEPTNO DNAME 10 20 30 40 ACCOUNTING RESEARCH SALES OPERATIONS LOC NEW YORK DALLAS CHICAGO BOSTON

³«Retrieve DEPTNO and LOC columns from the DEPT table´

DEPT
DEPTNO LOC 10 20 30 40 NEW YORK DALLAS CHICAGO BOSTON

only two columns are displayed

Cartesian Product
±A Cartesian product is formed when:
‡ A join condition is omitted ‡ A join condition is invalid ‡ All rows in the first table are joined to all rows in the second table

±To avoid a Cartesian product, always include a valid join condition in a WHERE clause.

Generating a 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 ...

³Cartesian product: 14*4=56 rows´

ENAME DNAME --------------KING ACCOUNTING BLAKE ACCOUNTING ... KING RESEARCH BLAKE RESEARCH ... 56 rows selected.

What Is a Join?
Use a join to query data from more than one table:
SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column1 = table2.column2;

±Write the join condition in the WHERE clause. ±Prefix the column name with the table name when the same column name appears in more than one table.

SELECT STATEMENT
Syntax : SELECT [ DISTINCT ] ( [ table ] . * | expr [alias ], ... ] FROM table [ alias ] , ... [ WHERE [ join condition ] ... ] [ AND [ row condition ] ... ] [ OR [ another row condition ] ] [ GROUP BY [ expr | column ]] [ HAVING [ group condition ]] [ ORDER BY [ expr | column ] [ ASC |DESC ] ] ;

Obtaining Data from Multiple Tables
EMP DEPT
EMPNO -----7839 7698 ... 7934 ENAME ----KING BLAKE ... DEPTNO ... -----... 10 ... 30 10 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.

Using the WHERE Clause
±Character strings and date values are enclosed in single quotation marks. ±Character values are case sensitive and date values are format sensitive.
SQL> SELECT ename, job, deptno 2 FROM emp 3 WHERE job = 'CLERK'; ENAME ---------JAMES SMITH ADAMS MILLER JOB DEPTNO --------- --------CLERK 30 CLERK 20 CLERK 20 CLERK 10

Types of Joins
Equijoin

Nonequijoin

Selfjoin

What is an Equijoin?
EMP
EMPNO ENAME DEPTNO ------ ------- ------... 7782 CLARK 10

DEPT
DEPTNO DNAME LOC ------- ---------- -------... 10 ACCOUNTING NEW YORK ...

Links rows that satisfy a specified condition

WHERE emp.deptno=dept.deptno

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

Foreign key

Primary key

Retrieving Records with an Equijoin
SQL> SELECT 2 3 FROM 4 WHERE emp.empno, emp.ename, emp.deptno, dept.deptno, dept.loc emp, dept emp.deptno=dept.deptno;

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.

Qualifying Ambiguous Column Names
±Use table prefixes to qualify column names that are in multiple tables. ±Use table prefixes to improve performance.

Defining a Column Alias
‡A column alias:
±Renames a column heading ±Is useful with calculations ±Immediately follows a column name; optional AS keyword may fall between a column name and an alias ±Requires double quotation marks if it contains spaces, special characters, or is case sensitive

Using Column Aliases
SQL> SELECT ename AS name, sal salary 2 FROM emp; NAME SALARY ------------- --------...

SQL> SELECT ename "Name", 2 sal * 12 "Annual Salary" 3 FROM emp; Name Annual Salary ------------- ------------...

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

« can be written as ...
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;

Using Table Aliases
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; EMPNO --------7839 7698 7782 7566 7654 7499 ... ENAME DEPTNO DEPTNO LOC ---------- --------- --------- ----------KING 10 10 NEW YORK BLAKE 30 30 CHICAGO CLARK 10 10 NEW YORK JONES 20 20 DALLAS MARTIN 30 30 CHICAGO ALLEN 30 30 CHICAGO

14 rows selected.

Nonequijoins
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 Records with Nonequijoins
SQL> 2 3 4 SELECT FROM WHERE BETWEEN e.ename, e.sal, s.grade emp e, salgrade s e.sal s.losal AND s.hisal;

ENAME SAL GRADE ---------- --------- --------JAMES 950 1 SMITH 800 1 ADAMS 1100 1 ... 14 rows selected.

EMP

Joining More Than Two Tables DEPT
DEPTNO DNAME --------- ---------10 ACCOUNTING 20 RESEARCH 30 SALES 40 OPERATIONS

ENAME SAL DEPTNO ---------- --------- --------JAMES 950 30 SMITH 800 20 ADAMS 1100 20 MARTIN 1250 30 WARD 1250 30 MILLER 1300 10 « 14 rows selected.

SALGRADE

LOSAL HISAL GRADE --------- --------- --------700 1200 1 WHERE emp.sal BETWEEN 1201 1400 2 salgrade.losal AND 1401 2000 3 2001 3000 4 salgrade.hisal 3001 9999 5 AND emp.deptno = dept.deptno

Using Multiple Joins
SQL> 2 3 4 SELECT FROM WHERE AND e.ename, e.deptno, d.dname, e.sal, s.grade emp e, dept d, salgrade s e.deptno=d.deptno e.sal BETWEEN s.losal and s.hisal; DNAME SAL GRADE -------------- --------- --------SALES 950 1 RESEARCH 800 1 RESEARCH 1100 1 SALES 1250 2 SALES 1250 2 ACCOUNTING 1300 2 SALES 1600 3

ENAME DEPTNO ---------- --------JAMES 30 SMITH 20 ADAMS 20 MARTIN 30 WARD 30 MILLER 10 ALLEN 30 ... 14 rows selected.

Selfjoins
EMP (WORKER)
EMPNO ----7839 7698 7782 7566 7654 7499 ENAME -----KING BLAKE CLARK JONES MARTIN ALLEN MGR ---7839 7839 7839 7698 7698

EMP (MANAGER)
EMPNO ENAME ----- -------7839 7839 7839 7698 7698 KING KING KING BLAKE BLAKE

³MGR in the WORKER table is equal to EMPNO in the MANAGER table.´

Joining a Table to Itself
SQL> 2 3 4 SELECT AS FROM WHERE worker.ename||' works for '||manager.ename WHO_WORKS_FOR_WHOM emp worker, emp manager worker.mgr = manager.empno;

WHO_WORKS_FOR_WHOM ------------------------------BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE ... 13 rows selected.

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

No employee in the OPERATIONS department

Outer Joins
±You use an outer join to see rows that do not usually meet the join condition. ±The 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(+);

Using Outer Joins
SQL> SELECT 2 FROM 3 WHERE e.ename, d.deptno, d.dname emp e, dept d e.deptno(+) = d.deptno;

ENAME DEPTNO DNAME ---------- --------- ------------MARTIN 30 SALES ALLEN 30 SALES TURNER 30 SALES JAMES 30 SALES WARD 30 SALES 40 OPERATIONS 15 rows selected.

Additional Search Conditions Using the AND Operator
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 ... 14 rows selected.

DEPT
DEPTNO DNAME ------ --------10 ACCOUNTING 30 SALES 10 ACCOUNTING 20 RESEARCH 30 SALES 30 SALES 30 SALES 30 SALES ... 14 rows selected. LOC -------NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO CHICAGO CHICAGO

WHERE emp.deptno=dept.deptno AND emp.ename= KING

Using Additional Search Conditions with a Join
SQL> 2 3 4 SELECT FROM WHERE AND emp.empno, emp.ename, emp.deptno, dept.loc emp, dept; emp.deptno = dept.deptno INITCAP(emp.ename) = 'King';

EMPNO ENAME DEPTNO LOC --------- ---------- --------- ------------7839 KING 10 NEW YORK

Using Additional Search Conditions with a Join
SQL> 2 3 4 SELECT FROM WHERE AND emp.ename, emp.job, dept.deptno, dept.dname emp, dept emp.deptno=dept.deptno emp.job IN ('MANAGER','PRESIDENT');

ENAME ---------KING BLAKE CLARK JONES

JOB DEPTNO DNAME --------- --------- -------------PRESIDENT 10 ACCOUNTING MANAGER 30 SALES MANAGER 10 ACCOUNTING MANAGER 20 RESEARCH

SELECT STATEMENT
Syntax : SELECT [ DISTINCT ] ( [ table ] . * | expr [alias ], ... ] FROM table [ alias ] , ... [ WHERE [ join condition ] ... ] [ AND [ row condition ] ... ] [ OR [ another row condition ] ] [ GROUP BY [ expr | column ]] [ HAVING [ group condition ]] [ ORDER BY [ expr | column ] [ ASC |DESC ] ] ;

Using the GROUP BY Clause
±Any column or expression in the SELECT list which is not an aggregate function must be in the GROUP BY clause.
SQL> 2 3 4 SELECT deptno, COUNT(*) emps FROM emp GROUP BY deptno HAVING COUNT(*) > 3;

DEPTNO EMPS ---------- ---------20 5 30 6

SQL Functions
Input arg 1 arg 2 Function Function performs action Result value Output

arg n

Two Types of SQL Functions
Functions

SingleSingle-row functions

MultipleMultiple-row functions

Single-Row Functions
±Manipulate data items ±Accept arguments and return one value ±Act on each row returned ±Return one result per row ±May modify the datatype ±Can be nested
function_name (column|expression, [arg1, arg2,...])

Single-Row Functions
Character

General

SingleSingle-row functions

Number

Conversion

Date

What Are Group Functions?
‡Group functions operate on sets of rows to give one result per group.
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

³maximum salary in the EMP table´

MAX(SAL) --------5000

Creating Groups of Data
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

2916.6667

³average DEPTNO AVG(SAL) salary ------- --------in EMP 2175 10 2916.6667 table 20 2175 for each department´ 30 1566.6667
1566.6667

Creating Groups of Data: GROUP BY Clause
SELECT FROM [WHERE [GROUP BY [ORDER BY column, group_function(column) table condition] group_by_expression] column];

‡Divide rows in a table into smaller groups by using the GROUP BY clause.

Types of Group Functions
±AVG ±COUNT ±MAX ±MIN ±STDDEV ±SUM ±VARIANCE

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

Using AVG and SUM Functions
‡You can use AVG and SUM for numeric data.
SQL> SELECT 2 3 FROM 4 WHERE AVG(sal), MAX(sal), MIN(sal), SUM(sal) emp job LIKE 'SALES%';

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

Using MIN and MAX Functions
‡You can use MIN and MAX for any datatype.
SQL> SELECT 2 FROM MIN(hiredate), MAX(hiredate) emp;

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

Using the GROUP BY Clause
‡All columns in the SELECT list that are not in group functions must be in the GROUP BY clause.
SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 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.
SQL> SELECT AVG(sal) 2 FROM emp 3 GROUP BY deptno;

AVG(SAL) --------2916.6667 2175 1566.6667

EMP
DEPTNO JOB

Grouping by More Than One Column
SAL 2450 5000 1300 800 1100 3000 3000 2975 1600 2850 1250 950 1500 1250 10 MANAGER 10 PRESIDENT 10 CLERK 20 CLERK 20 CLERK 20 ANALYST 20 ANALYST 20 MANAGER 30 SALESMAN 30 MANAGER 30 SALESMAN 30 CLERK 30 SALESMAN 30 SALESMAN DEPTNO -------10 10 10 20 20 20 30 30 30 JOB CLERK MANAGER PRESIDENT ANALYST CLERK MANAGER CLERK MANAGER SALESMAN SUM(SAL) 1300 2450 5000 6000 1900 2975 950 2850 5600 --------- ---------

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

³sum salaries in the EMP table for each job, grouped by department´

Using the GROUP BY Clause on Multiple Columns
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 Using Group Functions
‡Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause. SQL> SELECT deptno, COUNT(ename)
2 FROM emp; SELECT deptno, COUNT(ename) * ERROR at line 1: ORA-00937: not a single-group group function

Illegal Queries Using Group Functions
±You cannot use the WHERE clause to restrict groups. ±You use the HAVING clause to restrict groups.
SQL> 2 3 4 SELECT FROM WHERE GROUP BY deptno, AVG(sal) emp AVG(sal) > 2000 deptno;

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

Excluding Group Results
EMP
DEPTNO 10 10 10 20 20 20 20 20 30 30 30 30 30 30 SAL 2450 5000 1300 800 1100 3000 3000 2975 1600 2850 1250 950 1500 1250 --------- ---------

5000 ³maximum salary per department greater than $2900´

DEPTNO 10 20

MAX(SAL) 5000 3000

3000

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

2850

Excluding Group Results: HAVING Clause
‡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
SQL> 2 3 4 SELECT FROM GROUP BY HAVING deptno, max(sal) emp deptno max(sal)>2900;

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

Using the HAVING Clause
SQL> 2 3 4 5 6 SELECT FROM WHERE GROUP BY HAVING ORDER BY job, SUM(sal) PAYROLL emp job NOT LIKE 'SALES%' job SUM(sal)>5000 SUM(sal);

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

Nesting Group Functions
‡Display the maximum average salary.
SQL> SELECT max(avg(sal)) 2 FROM emp 3 GROUP BY deptno;

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

SELECT STATEMENT
Syntax : SELECT [ DISTINCT ] ( [ table ] . * | expr [alias ], ... ] FROM table [ alias ] , ... [ WHERE [ join condition ] ... ] [ AND [ row condition ] ... ] [ OR [ another row condition ] ] [ GROUP BY [ expr | column ]] [ HAVING [ group condition ]] [ ORDER BY [ expr | column ] [ ASC |DESC ] ] ;

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.
SQL> SELECT ename, job, deptno, hiredate 2 FROM emp 3 ORDER BY hiredate; ENAME JOB DEPTNO HIREDATE ---------- --------- --------- --------SMITH CLERK 20 17-DEC-80 ALLEN SALESMAN 30 20-FEB-81 ... 14 rows selected.

Sorting in Descending Order
SQL> SELECT ename, job, deptno, hiredate 2 FROM emp 3 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 MARTIN SALESMAN 30 28-SEP-81 ... 14 rows selected.

Sorting by Column Alias
SQL> SELECT empno, ename, sal * 12 annsal 2 FROM emp 3 ORDER BY annsal; 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 the columns in the ORDER BY clause is the order of the 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.

‡ You can sort by a column that is not in the SELECT clause.

SELECT STATEMENT
Syntax : SELECT [ DISTINCT ] ( [ table ] . * | expr [alias ], ... ] FROM table [ alias ] , ... [ WHERE [ join condition ] ... ] [ AND [ row condition ] ... ] [ OR [ another row condition ] ] [ GROUP BY [ expr | column ]] [ HAVING [ group condition ]] [ ORDER BY [ expr | column ] [ ASC |DESC ] ] ;

Combining queries
‡ Subqueries ‡ Set operators

SUBQUERIES
Single Row SubQuery Multirow Subquery Nested Subqueries Correlated Subqueries

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 to Solve a Problem
‡³Who has a salary greater than Jones¶s?´
Main Query

?

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

?

³What is Jones¶s salary?´

Using a Subquery
SQL> SELECT ename 2 FROM emp 2975 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE empno=7566);

ENAME ---------KING FORD SCOTT

Guidelines for Using 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 returns Subquery

CLERK

‡ Multiple-row subquery
Main query Subquery returns

CLERK MANAGER

‡ Multiple-column subquery
Main query Subquery returns

CLERK 7900 MANAGER 7698

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

Executing Single-Row Subqueries
SQL> 2 3 4 5 6 7 8 9 10 SELECT FROM WHERE ename, job emp job = (SELECT FROM WHERE sal > (SELECT FROM WHERE
CLERK

job emp empno = 7369)
1100

AND

sal emp empno = 7876);

ENAME JOB ---------- --------MILLER CLERK

Using Group Functions in a Subquery
SQL> SELECT 2 FROM 3 WHERE 4 5 ename, job, sal emp sal = (SELECT FROM
800

MIN(sal) emp);

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

HAVING Clause with Subqueries
±The Oracle Server executes subqueries first. ±The Oracle Server returns results into the main query¶s HAVING clause.
SQL> 2 3 4 5 6 7 SELECT FROM GROUP BY HAVING deptno, MIN(sal) emp deptno MIN(sal) > (SELECT FROM WHERE

800

MIN(sal) emp deptno = 20);

What Is Wrong with This Statement?
SQL> SELECT empno, ename 2 FROM emp 3 WHERE sal = 4 (SELECT 5 FROM 6 GROUP BY MIN(sal) emp deptno);

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

Will This Statement Work?
SQL> SELECT ename, 2 FROM emp 3 WHERE job = 4 5 6 job

(SELECT job FROM emp 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

Using ANY Operator in Multiple-Row Subqueries
SQL> 2 3 4 5 6 7 SELECT FROM WHERE empno, ename, job 1300 1100 emp 800 sal < ANY 950 (SELECT sal FROM emp WHERE job = 'CLERK') job <> 'CLERK'; JOB --------SALESMAN SALESMAN

AND

EMPNO --------7654 7521

ENAME ---------MARTIN WARD

Using ALL Operator in Multiple-Row Subqueries
SQL> SELECT 2 FROM 3 WHERE 4 5 6 EMPNO --------7839 7566 7902 7788 empno, ename, job 2175 emp 2916.6667 sal > ALL (SELECT FROM GROUP BY JOB --------PRESIDENT MANAGER ANALYST ANALYST
1566.6667

avg(sal) emp deptno);

ENAME ---------KING JONES FORD SCOTT

Summary
‡Subqueries are useful when a query is based on unknown values.
SELECT FROM WHERE select_list table expr operator (SELECT select_list FROM table);

Multiple-Column Subqueries
Main query
MANAGER 10

Subquery
SALESMAN MANAGER CLERK 30 10 20

Main query compares
MANAGER 10

to

Values from a multiple-row and multiplemultiplemultiple-column subquery
SALESMAN 30 MANAGER 10 CLERK 20

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

Column Comparisons
Pairwise
SAL 1600 1250 1250 2850 1500 950 COMM 300 500 1400 0

Nonpairwise
SAL 1600 1250 1250 2850 1500 950 COMM 300 500 1400 0

‡Display the name, department number, salary, and commission of any employee whose salary and commission matches the commission and salary of any employee in department 30.
SQL> 2 3 4 5 6 7 8 9 SELECT FROM WHERE ename, deptno, sal, comm emp sal IN (SELECT sal FROM emp WHERE deptno = 30) NVL(comm,-1) IN (SELECT NVL(comm,-1) FROM emp WHERE deptno = 30);

Nonpairwise Comparison Subquery

AND

Modifying the EMP Table
±Assume that salary and commission for Clark are modified. ‡ Salary is changed to $1500 and commission to $300.
ENAME SAL COMM ---------- --------- --------... CLARK 1500 300 ... ALLEN 1600 300 TURNER 1500 0 ... 14 rows selected.

Pairwise Subquery
SQL> SELECT 2 FROM 3 WHERE 4 5 6 ename, deptno, sal, comm emp (sal, NVL(comm,-1)) IN (SELECT sal, NVL(comm,-1) FROM emp WHERE deptno = 30);

ENAME DEPTNO SAL COMM ---------- --------- --------- --------JAMES 30 950 WARD 30 1250 500 MARTIN 30 1250 1400 TURNER 30 1500 0 ALLEN 30 1600 300 BLAKE 30 2850 6 rows selected.

Nonpairwise Subquery
SQL> 2 3 4 5 6 7 8 9 SELECT FROM WHERE ename,deptno, sal, comm emp sal IN (SELECT sal FROM emp WHERE deptno = 30) NVL(comm,-1) IN (SELECT NVL(comm,-1) FROM emp WHERE deptno = 30);

AND

ENAME DEPTNO SAL COMM ---------- --------- --------- --------JAMES 30 950 BLAKE 30 2850 TURNER 30 1500 0 CLARK 10 1500 300 ... 7 rows selected.

Summary
±A multiple-column subquery returns more than one column. ±Column comparisons in a multiple- column comparisons can be pairwise or nonpairwise. ±A multiple-column subquery can also be used in the FROM clause of a SELECT statement.

Using a Correlated Subquery to Solve a Problem
‡³Which employees earn more than the average salary for each department?´
Main Query

?

³Which employees earn more than the average salary for their individual department?´
Correlated Subquery

?

³What is the average salary for the employee¶s department?´

Using Correlated Subqueries
‡Find all employees who make more than the average salary in their department.
SQL> SELECT empno, sal, deptno Each time the outer query is processed, the 2 FROM emp outer inner query is 3 WHERE sal > (SELECT AVG(sal) evaluated. 4 FROM emp inner 5 WHERE outer.deptno = inner.deptno); EMPNO SAL DEPTNO -------- --------- --------7839 5000 10 7698 2850 30 7566 2975 20 ... 6 rows selected.

Using the EXISTS Operator
±If a subquery row value is found:
‡ The search will not continue in the inner query ‡ The condition is flagged TRUE

±If a subquery row value is not found:
‡ The condition is flagged FALSE ‡ The search will continue in the inner query

Using the NOT EXISTS Operator
Find all departments that do not have any employees.
SQL> SELECT deptno, dname 2 FROM dept d 3 WHERE NOT EXISTS (SELECT '1' 4 FROM emp e 5 WHERE d.deptno = e.deptno); DEPTNO DNAME --------- -------------40 OPERATIONS

Summary
±Subqueries are useful when a query is based on unknown values. ±A nested subquery is executed once. ±A correlated subquery is executed once for each parent candidate row. ±Nested subqueries can be used for multicolumn comparison. ±The EXISTS operator is a Boolean operator, testing the presence of a value. ±Caution is necessary with NULL values and NOT IN.

Combining queries
‡ Subqueries ‡ Set operators

The Set Operators
A B

Intersect
A B A B

Union / Union All
A B

Minus

UNION
A B

Using the UNION Operator
‡Display the name, job title, and department of all employees.
SQL> 2 3 4 5 SELECT ename, job, deptno FROM emp UNION SELECT name, title, deptid FROM emp_history;

ENAME JOB DEPTNO ---------- --------- --------ADAMS CLERK 30 ALLEN SALESMAN 30 ALLEN SALESMAN 20 BALFORD CLERK 20 BLAKE MANAGER 30 ... 20 rows selected.

UNION ALL
A B

‡Display the names, employee numbers, and job titles of all employees.
SQL> 2 3 4 5 SELECT ename, empno, job FROM emp UNION ALL SELECT name, empid, title FROM emp_history; JOB --------PRESIDENT MANAGER MANAGER MANAGER SALESMAN

Using the UNION ALL Operator

ENAME EMPNO ---------- --------KING 7839 BLAKE 7698 CLARK 7782 CLARK 7782 MARTIN 7654 ... 23 rows selected.

INTERSECT
A B

Using the INTERSECT Operator
‡Display the distinct names, employee numbers, and job titles of employees found in both the EMP and EMP_HISTORY tables.
SQL> 2 3 4 5 SELECT ename, empno, job FROM emp INTERSECT SELECT name, empid, title FROM emp_history;

ENAME EMPNO JOB ---------- --------- --------ALLEN 7499 SALESMAN CLARK 7782 MANAGER SCOTT 7788 ANALYST

MINUS
A B

MINUS
Display the names, employee numbers, and job titles for all employees who have left the company.
SQL> 2 3 4 5 SELECT FROM MINUS SELECT FROM name, empid, title emp_history ename, empno, job emp; TITLE --------CLERK PAY CLERK ANALYST OPERATOR

NAME EMPID ---------- --------BALFORD 6235 BRIGGS 7225 JEWELL 7001 SPENCER 6087 ... 6 rows selected.

SET Operator Rules
±The expressions in the SELECT lists must match in number and datatype. ±Duplicate rows are automatically eliminated except in UNION ALL. ±Column names from the first query appear in the result. ±The output is sorted in ascending order by default except in UNION ALL. ±Parentheses can be used to alter the sequence of execution.

Matching the SELECT Statement
Display the department number, location, and hiredate for all employees.
SQL> 2 3 4 5 SELECT FROM UNION SELECT FROM deptno, TO_CHAR(null) location, hiredate emp deptno, loc, TO_DATE(null) dept;

Produce an English sentence using two UNION operators.
SQL> SQL> 2 3 4 5 6 7 8 9 COLUMN a_dummy NOPRINT SELECT 'to sing' "My dream", 3 a_dummy FROM dual UNION SELECT 'I''d like to teach', 1 FROM dual UNION SELECT 'the world', 2 FROM dual ORDER BY 2;

Controlling the Order of Rows

My dream ------------------------I'd like to teach the world to sing

Summary
±UNION returns all distinct rows. ±UNION ALL returns all rows including duplicates. ±INTERSECT returns all rows that both queries share. ±MINUS returns all distinct rows selected by the first query but not the second. ±ORDER BY can only appear at the very end of the statement.

SQL Statements
‡SELECT ‡INSERT ‡UPDATE ‡DELETE ‡CREATE ‡ALTER ‡DROP ‡RENAME ‡TRUNCATE ‡COMMIT ‡ROLLBACK ‡SAVEPOINT
Data Retrieval Data manipulation language (DML)

Data definition language (DDL)

Transaction Control Language (TCL)

Manipulating Data DML

Data Manipulation Language
±A DML statement is executed when you:
‡ Add new rows to a table (INSERT) ‡ Modify existing rows in a table (UPDATE) ‡ Remove existing rows from a table (DELETE)

±A transaction consists of a collection of DML statements that form a logical unit of work.

Adding a New Row to a Table
50 DEVELOPMENT DETROIT

New row DEPT
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON

³«insert a new row into DEPT table«´
DEPT
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON

50 DEVELOPMENT DETROIT

The INSERT Statement
±Add new rows to a table by using the INSERT statement.
INSERT INTO VALUES table [(column [, column...])] (value [, value...]);

±Only one row is inserted at a time with this syntax.

Inserting New Rows
±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.
SQL> INSERT INTO 2 VALUES 1 row created. dept (deptno, dname, loc) (50, 'DEVELOPMENT', 'DETROIT');

±Enclose character and date values within single quotation marks.

Inserting Rows with Null Values
±Implicit method: Omit the column from the column list.
SQL> INSERT INTO 2 VALUES 1 row created. dept (deptno, dname ) (60, 'MIS');

‡ Explicit method: Specify the NULL keyword.
SQL> INSERT INTO 2 VALUES 1 row created. dept (70, 'FINANCE', NULL);

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

Inserting Specific Date Values
±Add a new employee.
SQL> INSERT INTO 2 VALUES 3 4 1 row created. emp (2296,'AROMANO','SALESMAN',7782, TO_DATE('FEB 3,97', 'MON DD, YY'), 1300, NULL, 10);

‡ Verify your addition.
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ----- ------- -------- ---- --------- ---- ---- -----2296 AROMANO SALESMAN 7782 03-FEB-97 1300 10

Inserting Values by Using Substitution Variables
‡Create an interactive script by using SQL*Plus substitution parameters.
SQL> INSERT INTO 2 VALUES 3 dept (deptno, dname, loc) (&department_id, '&department_name', '&location');

Enter value for department_id: 80 Enter value for department_name: EDUCATION Enter value for location: ATLANTA 1 row created.

Creating a Script with Customized Prompts
±ACCEPT stores the value into a variable. ±PROMPT displays your customized text.
ACCEPT ACCEPT ACCEPT INSERT INTO VALUES department_id PROMPT 'Please enter the department number:' department_name PROMPT 'Please enter the department name:' location PROMPT 'Please enter the location:' dept (deptno, dname, loc) (&department_id, '&department_name', '&location');

Copying Rows 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 emp 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.

EMP

Changing Data in a Table
JOB PRESIDENT MANAGER MANAGER MANAGER ... DEPTNO 10 30 10 20 KING BLAKE CLARK JONES

EMPNO ENAME 7839 7698 7782 7566 ...

³«update a row in EMP table«´

EMP
EMPNO ENAME 7839 7698 7782 7566 ... KING BLAKE CLARK JONES JOB PRESIDENT MANAGER MANAGER MANAGER ... DEPTNO 10 30 20 10 20

The UPDATE Statement
±Modify existing rows with the UPDATE statement.
UPDATE SET [WHERE table column = value [, column = value] condition];

±Update more than one row at a time, if required.

Updating Rows in a Table
±Specific row or rows are modified when you specify the WHERE clause.
SQL> UPDATE emp 2 SET deptno = 20 3 WHERE empno = 7782; 1 row updated.

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

Updating with Multiple-Column Subquery
‡Update employee 7698¶s job and department to match that of employee 7499.
SQL> UPDATE emp 2 SET (job, deptno) = 3 (SELECT job, deptno 4 FROM emp 5 WHERE empno = 7499) 6 WHERE empno = 7698; 1 row updated.

Updating Rows Based on Another Table
‡Use subqueries in UPDATE statements to update rows in a table based on values from another table.
SQL> UPDATE employee 2 SET deptno = 3 4 5 WHERE job = 6 7 2 rows updated. (SELECT FROM WHERE (SELECT FROM WHERE deptno emp empno = 7788) job emp empno = 7788);

Removing a Row from a Table
DEPT
DEPTNO -----10 20 30 40 50 60 ... DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON DEVELOPMENT DETROIT MIS

³«delete a row from DEPT table«´
DEPT
DEPTNO -----10 20 30 40 60 ... DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS MIS LOC -------NEW YORK DALLAS CHICAGO BOSTON

The DELETE Statement
‡You can remove existing rows from a table by using the DELETE statement.
DELETE [FROM] [WHERE 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 Based on Another Table
‡Use subqueries in DELETE statements to remove rows from a table based on values from another table.
SQL> DELETE FROM 2 WHERE 3 4 5 6 rows deleted. employee deptno = (SELECT FROM WHERE deptno dept dname ='SALES');

Correlated UPDATE
UPDATE table1 alias1 SET column = (SELECT expression FROM table2 alias2 WHERE alias1.column = alias2.column);

‡Use a correlated subquery to update rows in one table based on rows from another table.

Correlated DELETE
DELETE FROM table1 alias1 WHERE column operator (SELECT expression FROM table2 alias2 WHERE alias1.column = alias2.column);

Use a correlated subquery to delete only those rows that also exist in another table.

Summary
‡ INSERT Statement ‡ UPDATE Statement ‡ DELETE Statement

SQL Statements
‡SELECT ‡INSERT ‡UPDATE ‡DELETE ‡CREATE ‡ALTER ‡DROP ‡RENAME ‡TRUNCATE ‡COMMIT ‡ROLLBACK ‡SAVEPOINT
Data Retrieval Data manipulation language (DML)

Data definition language (DDL)

Transaction Control Language (TCL)

Creating and Managing Tables DDL

‡ These statements are used to create, modify or remove

Oracle database structures, including tables. ‡ have an immediate effect on the database ,and record information in the Data dictionary.

DDL Statements in SQL : ‡ CREATE
‡ ‡ ‡ ‡ ALTER DROP RENAME TRUNCATE

Naming Conventions
Table and column names:
±Must begin with a letter ±Can be 1±30 characters long ±Must contain only A±Z, a±z, 0±9, _, $, and # ±Must not duplicate the name of another object owned by the same user ±Must not be Oracle Server reserved words

Datatypes
Datatype Description VARCHAR2(size) Variable-length character data CHAR(size) NUMBER(p,s) DATE LONG RAW and CLOB BLOB BFILE ROWID Fixed-length character data Variable-length numeric data Date and time values Variable-length character data up to 2 gigabytes Raw binary data LONG RAW Single-byte character data up to 4 gigabytes Binary data up to 4 gigabytes Binary data up to 4 gigabytes stored in an external file Hexadecimal string representing the unique address of a row in its table

The CREATE TABLE Statement
±You must have:
‡ The CREATE TABLE privilege ‡ A storage area
CREATE TABLE [schema.]table (column datatype [DEFAULT expr] [column_constraint], ... [table_constraint]);

±You specify the table name, column name, column datatype, column size, and the table and/or column constraint.

±Create the table.

Creating Tables

SQL> CREATE TABLE dept 2 (deptno NUMBER(2), 3 dname VARCHAR2(14), 4 loc VARCHAR2(13)); Table created.

‡ Confirm table creation.
SQL> DESCRIBE dept Name Null? --------------------------- -------DEPTNO NOT NULL DNAME LOC Type --------NUMBER(2) VARCHAR2(14) VARCHAR2(13)

The DEFAULT Option
‡You can specify a default value for a column during an insert:
... hiredate DATE DEFAULT SYSDATE, ...

‡ Legal values are a literal value, an expression, or a SQL function. ‡ Illegal values are another column¶s name or pseudocolumn. ‡ The default datatype must match the column datatype.

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 the Oracle Server:
‡ ‡ ‡ ‡ ‡ NOT NULL UNIQUE 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 datatype [DEFAULT expr] [column_constraint], ... [table_constraint]);

±Column-level constraint
column [CONSTRAINT constraint_name] constraint_type,

±Table-level constraint
column,... [CONSTRAINT constraint_name] constraint_type (column, ...),

The NOT NULL Constraint
‡The NOT NULL constraint ensures that null values are not permitted for the column.
EMP
EMPNO ENAME 7839 7698 7782 7566 ... KING BLAKE CLARK JONES JOB PRESIDENT MANAGER MANAGER MANAGER ... COMM DEPTNO 10 30 10 20

NOT NULL constraint (no row may contain a null value for this column)

Absence of NOT NULL constraint (any row can contain null for this column)

NOT NULL constraint

The UNIQUE Key Constraint
UNIQUE key constraint

DEPT
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON

Insert into 50 SALES 60 DETROIT BOSTON

Not allowed (DNAME SALES already exists) Allowed

The UNIQUE Key Constraint
‡You can define the UNIQUE key constraint at either the table level or the column level.
SQL> CREATE TABLE dept( 2 deptno NUMBER(2), 3 dname VARCHAR2(14), 4 loc VARCHAR2(13), 5 CONSTRAINT dept_dname_uk UNIQUE(dname));

The PRIMARY KEY Constraint PRIMARY key
DEPT
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON

Insert into 20 MARKETING FINANCE DALLAS NEW YORK

Not allowed (DEPTNO 20 already exists) Not allowed (DEPTNO is null)

The FOREIGN KEY Constraint
DEPT
PRIMARY key DEPTNO -----10 20 ... DNAME ---------ACCOUNTING RESEARCH LOC -------NEW YORK DALLAS

EMP
EMPNO ENAME 7839 KING 7698 BLAKE ... JOB PRESIDENT MANAGER Insert into 7571 FORD 7571 FORD MANAGER MANAGER ... ... 200 200 9 ... COMM DEPTNO 10 30 Not allowed (DEPTNO 9 does not exist in the DEPT table) Allowed FOREIGN key

The FOREIGN KEY Constraint
‡You can define the FOREIGN KEY constraint at either the table level or the column level.
SQL> CREATE TABLE emp( 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));

‡You can define a condition that each row must satisfy. ‡The following expressions are not allowed:
±References to pseudocolumns CURRVAL, NEXTVAL, LEVEL, and ROWNUM ±Calls to SYSDATE, UID, USER, and USERENV functions ..., deptno NUMBER(2), ±Queries that emp_deptno_ck values in other refer to other CONSTRAINT CHECK (DEPTNO BETWEEN 10 AND 99),... rows

The CHECK Constraint

Example CREATE TABLE new_emp (empno NUMBER(4) CONSTRAINT pk_emp_empno PRIMARY KEY, ename VARCHAR2(10) CONSTRAINT chk_upp_ename CHECK(ENAME= UPPER(ENAME)), job VARCHAR2(9), mgr NUMBER(4) CONSTRAINT fk_emp_mgr REFERENCES new_emp(empno), hiredate DATE DEFAULT SYSDATE, sal NUMBER(7, 2) CONSTRAINT nn_sal NOT NULL, comm NUMBER(7, 2), deptno NUMBER(2) CONSTRAINT nn_deptno NOT NULL, CONSTRAINT fk_emp_deptno FOREIGN KEY(deptno) REFERENCES new_dept(deptno) ON DELETE CASCADE ) ;

Updating Rows: Integrity Constraint Error
SQL> UPDATE 2 SET 3 WHERE emp deptno = 55 deptno = 10;

UPDATE emp * ERROR at line 1: ORA-02291: integrity constraint (USR.EMP_DEPTNO_FK) violated - parent key not found

Deleting Rows: Integrity Constraint Error
SQL> DELETE FROM 2 WHERE dept deptno = 10;

DELETE FROM dept * ERROR at line 1: ORA-02292: integrity constraint (USR.EMP_DEPTNO_FK) violated - child record found

Querying the Data Dictionary
±Describe tables owned by the user.
SQL> SELECT 2 FROM * user_tables;

‡ View distinct object types owned by the user.
SQL> SELECT 2 FROM DISTINCT object_type user_objects;

‡ View tables, views, synonyms, and sequences owned by the user.
SQL> SELECT 2 FROM * user_catalog;

Viewing Constraints
‡Query the USER_CONSTRAINTS table to view all constraint definitions SQL> SELECT constraint_name, constraint_type, and names. 2 search_condition
3 4 FROM WHERE user_constraints table_name = 'EMP';

View the columns associated with the constraint names in the USER_CONS_COLUMNS view.
SQL> SQL> 2 2 3 3 SELECT SELECT FROM FROM WHERE WHERE constraint_name, column_name constraint_name, column_name user_cons_columns user_cons_columns table_name = 'EMP'; table_name = 'EMP';

Commonly used Data Dictionary Views
USER_OBJECTS USER_TABLES USER_CONSTRAINTS USER_CONS_COLUMNS USER_SOURCE USER_VIEWS USER_TRIGGERS USER_INDEXES

±Create a table and insert rows by combining the CREATE TABLE statement and AS subquery option.
CREATE TABLE table [column(, column...)] AS subquery;

Creating a Table by Using a Subquery

±Match the number of specified columns to the number of subquery columns. ±Define columns with column names and default values.

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

The ALTER TABLE Statement
‡Use the ALTER TABLE statement to:
±Add and modify columns ±Add or remove constraints ±Enable or disable constraints ±Define a default value for the new column
ALTER TABLE table ADD (column datatype [DEFAULT expr] [NOT NULL] [, column datatype]...); ALTER TABLE table MODIFY (column datatype [DEFAULT expr] [NOT NULL] [, column datatype]...);

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

³«add a new column into DEPT30 table«´

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
‡Modify a column definition by using the ALTER TABLE statement with the MODIFY clause.
±You can change a column¶s datatype, size, default value, and NOT NULL column constraint.
SQL> ALTER TABLE emp 2 MODIFY (job VARCHAR2(50)); Table altered.

±A change to the default value affects only subsequent insertions to the table.

Adding a Constraint
‡Add constraints to a table or column by using the ALTER TABLE statement with the ADD clause:
ALTER TABLE table ADD [CONSTRAINT constraint] type (column);

±You can add or drop but not modify the structure of a constraint. ±You can enable or disable constraints. ±You can 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 emp 2 ADD CONSTRAINT emp_mgr_fk 3 FOREIGN KEY(mgr) REFERENCES emp(empno); Table altered.

Dropping a Constraint
±Remove the manager constraint from the EMP table.
SQL> ALTER TABLE emp 2 DROP CONSTRAINT emp_mgr_fk; Table altered.

‡ 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 emp 2 DISABLE CONSTRAINT emp_empno_pk CASCADE; Table altered.

Enabling Constraints
±Activate an integrity constraint currently disabled in the table definition by using the ENABLE clause.
SQL> ALTER TABLE emp 2 ENABLE CONSTRAINT emp_empno_pk; Table altered.

±A UNIQUE or PRIMARY KEY index is automatically created if you enable a UNIQUE or PRIMARY KEY constraint.

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

View

Sequence Index Synonym

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

‡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}];

The CREATE SEQUENCE Statement

Creating a Sequence
±Create a sequence named DEPT_DEPTNO to be used for the primary key of the DEPT table. ±Do not use the CYCLE option.
SQL> CREATE SEQUENCE dept_deptno 2 INCREMENT BY 1 3 START WITH 91 4 MAXVALUE 100 5 NOCACHE 6 NOCYCLE; Sequence created.

Confirming Sequences
±Verify your sequence values in the USER_SEQUENCES data dictionary table.
SQL> SELECT 2 3 FROM sequence_name, min_value, max_value, increment_by, last_number user_sequences;

±The LAST_NUMBER column displays the next available sequence number.

±NEXTVAL returns the next available sequence value. It returns a unique value every time it is referenced, even for different users. ±CURRVAL obtains the current sequence value. NEXTVAL must be issued for that sequence before CURRVAL contains a value.

NEXTVAL and CURRVAL Pseudocolumns

±NEXTVAL returns the next available sequence value. It returns a unique value every time it is referenced, even for different users. ±CURRVAL obtains the current sequence value. NEXTVAL must be issued for that sequence before CURRVAL contains a value.

NEXTVAL and CURRVAL Pseudocolumns

Using a Sequence
±Insert a new department named ³MARKETING´ in San Diego.
SQL> INSERT INTO 2 VALUES 3 1 row created. dept(deptno, dname, loc) (dept_deptno.NEXTVAL, 'MARKETING', 'SAN DIEGO');

±View the current value for the DEPT_DEPTNO sequence.
SQL> SELECT 2 FROM dept_deptno.CURRVAL dual;

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.

Guidelines for Modifying a Sequence
±You must be the owner or have the ALTER privilege for the sequence. ±Only future sequence numbers are affected. ±The sequence must be dropped and recreated to restart the sequence at a different number. ±Some validation is performed.

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.

Dropping a Table
‡The DROP TABLE statement:
±Deletes all data and the table structure ±Commits any pending transactions ±Drops all indexes
SQL> DROP TABLE dept30; Table dropped.

‡You cannot roll back this statement.

Changing the Name of an Object
±To change the name of a table, view, sequence, or synonym, execute the RENAME statement.
SQL> RENAME dept TO department; Table renamed.

±You must be the owner of the object.

Truncating a Table
±The TRUNCATE TABLE statement:
‡ Removes all rows from a table ‡ Releases the storage space used by that table
SQL> TRUNCATE TABLE department; Table truncated.

±You cannot roll back row removal when using TRUNCATE. ±Alternatively, you can remove rows by using the DELETE statement.

Adding Comments to a Table
±You can add comments to a table or column by using the COMMENT statement.
SQL> COMMENT ON TABLE emp 2 IS 'Employee Information'; Comment created.

±Comments can be viewed through the following data dictionary views:
‡ ‡ ‡ ‡ ALL_COL_COMMENTS USER_COL_COMMENTS ALL_TAB_COMMENTS USER_TAB_COMMENTS

Summary
±Types of constraints:
‡ ‡ ‡ ‡ ‡ NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK

±Use data dictionary views to retrieve table, column, and constraint information.

Summary
Create and maintain tables using the following statements:
Statement CREATE TABLE ALTER TABLE DROP TABLE RENAME TRUNCATE COMMENT Description Creates a table Modifies table structures Removes the rows and table structure Changes the name of a table, view, sequence, or synonym Removes all rows from a table and releases the storage space Adds comments to a table or view

SQL Statements
‡SELECT ‡INSERT ‡UPDATE ‡DELETE ‡CREATE ‡ALTER ‡DROP ‡RENAME ‡TRUNCATE ‡COMMIT ‡ROLLBACK ‡SAVEPOINT
Data Retrieval Data manipulation language (DML)

Data definition language (DDL)

Transaction Control Language (TCL)

Contolling Transactions TCL

Database Transactions
Database transactions can consist of:
±DML statements that make up one consistent change to the data
Example: UPDATE

±One DDL statement
Example: CREATE

±One DCL statement
Example: GRANT and REVOKE

Database Transactions
‡Begin when the first executable SQL statement is executed ‡End with one of the following events:
‡ COMMIT or ROLLBACK ‡ DDL or DCL statement executes (automatic commit) ‡ User exits ‡ System crashes

Advantages of COMMIT and ROLLBACK
±COMMIT and ROLLBACK ensure data consistency. ±Users can preview data changes before making changes permanent. ±Users can group logically related operations.

Controlling Transactions
Transaction
INSERT
COMMIT

UPDATE

INSERT

DELETE

Savepoint A

Savepoint B

ROLLBACK to Savepoint B

ROLLBACK to Savepoint A

ROLLBACK

Implicit Transaction Processing
±An automatic commit occurs under the following circumstances:
‡ A DDL statement is issued, such as CREATE ‡ A DCL statement is issued, such as GRANT ‡ A normal exit from SQL*Plus occurs without an explicitly issued COMMIT or ROLLBACK statement

±An automatic rollback occurs under an abnormal termination of SQL*Plus or a system failure.

State of the Data Before COMMIT or ROLLBACK
±The previous state of the data can be recovered. ±The current user can review the results of the DML operations by using the SELECT statement. ±Other users cannot view the results of the DML statements by the current user. ±The affected rows are locked; other users cannot change the data within the affected rows.

Committing Data
‡Change the department number of an employee (Clark) identified by a employee number.
±Make the changes.
SQL> UPDATE emp 2 SET deptno = 10 3 WHERE empno = 7782; 1 row updated.

‡ Commit the changes.
SQL> COMMIT; Commit complete.

State of the Data After ROLLBACK
Discard all pending changes by using the ROLLBACK statement. Following a ROLLBACK:
±Data changes are undone. ±The previous state of the data is restored. ±Locks on the affected rows are released.
SQL> DELETE FROM employee; 14 rows deleted. SQL> ROLLBACK; Rollback complete.

Rolling Back Changes to a Marker
±Create a marker within a current transaction by using the SAVEPOINT statement. ±Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement.
SQL> UPDATE... SQL> SAVEPOINT update_done; Savepoint created. SQL> INSERT... SQL> ROLLBACK TO update_done; Rollback complete.

Statement-Level Rollback
±If a single DML statement fails during execution, only that statement is rolled back. ±Oracle implements an implicit savepoint. ±All other changes are retained. ±The user should terminate transactions explicitly by executing a COMMIT or ROLLBACK statement.

Read Consistency
±Read consistency guarantees a consistent view of the data at all times. ±Changes made by one user do not conflict with changes made by another user. ±Read consistency ensures that on the same data:
‡ Readers do not wait for writers or other readers ‡ Writers do not wait for readers

Implementation of Read Consistency
UPDATE emp SET sal = 2000 WHERE ename = 'SCOTT';

Data blocks Rollback segments
Changed and unchanged data Before change ³old´ data

User A
SELECT * FROM emp;

Read consistent image

User B

Locking
The Oracle Server locks:
±Prevent destructive interaction between concurrent transactions ±Require no user action ±Automatically use the lowest level of restrictiveness ±Are held for the duration of the transaction ±Have two basic modes:
‡ Exclusive ‡ Share

Locking Modes
Lock Mode Exclusive lock Description Prevents a resource from being shared. The first transaction to lock a resource exclusively is the only transaction that can alter the resource until the exclusive lock is released. Share Allows the resource to be shared. Multiple users reading data can share the data, holding share locks to prevent concurrent access by a writer (who needs an exclusive lock). Several transactions can acquire share locks on the same resource.

Implicit Locking
User Action SELECT ... FROM table ... INSERT INTO table ... UPDATE table ... DELETE FROM table ... DDL Operation Row-Level Lock None X X X None Table-Level Lock None RX RX RX X

Explicit Locking
User Action SELECT FOR UPDATE LOCK TABLE IN option Row-Level lock X None Table-Level lock RS [NOWAIT] Depends on the MODE restrictiveness used

Override the default lock mechanism:
±For a consistent view of data when reading across multiple tables ±When a transaction may change data based on other data that must not change until the whole transaction is complete

±A transaction is a logical unit of work. ±Transaction control statements:
Statement COMMIT SAVEPOINT ROLLBACK Description Makes all pending changes permanent. Allows a rollback to the savepoint marker. Discards all pending data changes.

Summary

‡ The Oracle Server guarantees a readconsistent view. ‡ Locking is automatic. ‡ Locking can be implicit or explicit.

Power / Pitfalls & Tips

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. ± takes up one byte of internal µstorage¶ overhead ± any column or expression contains Null, the result will be Null.
SQL> SELECT ename, job, comm 2 FROM emp; ENAME JOB COMM ---------- --------- --------KING PRESIDENT BLAKE MANAGER ... TURNER SALESMAN 0 ... 14 rows selected.

Null Values in a Subquery
SQL> SELECT employee.ename 2 FROM emp employee 3 WHERE employee.empno NOT IN 4 (SELECT manager.mgr 5 FROM emp manager); no rows selected.

NVL Function
‡Converts null to an actual value
±Datatypes that can be used are date, character, and number. ±Datatypes must match
‡ NVL(comm,0) ‡ NVL(hiredate,'01-JAN-97') ‡ NVL(job,'No Job Yet')

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

‡Use the NVL function to convert a null value to an actual value.
SQL> SELECT ename NAME, 12 * sal + NVL(comm, 0) 2 FROM emp;

Null Values in Arithmetic Expressions

NAME 12*SAL+NVL(COMM,0) ---------- -----------------KING 60000 ... 14 rows selected.

Group Functions and Null Values
‡Group functions ignore null values in the column.
SQL> SELECT AVG(comm) 2 FROM emp;

AVG(COMM) --------550

Using the NVL Function with Group Functions
‡The NVL function forces group functions to include null values.
SQL> SELECT AVG(NVL(comm,0)) 2 FROM emp;

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

DECODE Function
‡Facilitates conditional inquiries by doing the work of a CASE or IF-THEN-ELSE statement
DECODE(col/expression, search1, result1 [, search2, result2,...,] [, default])

Using the DECODE Function
SQL> SELECT job, sal, 2 DECODE(job, 'ANALYST', SAL*1.1, 3 'CLERK', SAL*1.15, 4 'MANAGER', SAL*1.20, 5 SAL) 6 REVISED_SALARY 7 FROM emp; JOB SAL REVISED_SALARY --------- --------- -------------PRESIDENT 5000 5000 MANAGER 2850 3420 MANAGER 2450 2940 ... 14 rows selected.

Example 1 : SELECT ename , job , DECODE ( job, µCLERK¶, µWORKER¶ , µMANAGER¶, µSUPERVISOR¶ , µPRESIDENT¶, µBOSS¶ , µOTHERS¶) Decoded_Job FROM emp; Example 2 : UPDATE emp SET comm = DECODE(sign(sal - 1000), -1, sal*0.1 , DECODE(sign(sal - 2000), -1, sal*0.2 , DECODE(sign(sal - 3000), -1, sal*0.25, 0, sal*0.3, sal*0.4))) Example 3 : DELETE FROM emp WHERE sal < DECODE(SIGN(NVL(comm,0) - 1000), -1, 999, 0, 1000, 1, 1500);

Nesting Functions
±Single-row functions can be nested to any level. ±Nested functions are evaluated from deepest level to the least deep level. F3(F2(F1(col,arg1),arg2),arg3)
Step 1 = Result 1 Step 2 = Result 2 Step 3 = Result 3

Nesting Functions
SQL> SELECT 2 3 FROM 4 WHERE ename, NVL(TO_CHAR(mgr),'No Manager') emp mgr IS NULL;

ENAME NVL(TO_CHAR(MGR),'NOMANAGER') ---------- ----------------------------KING No Manager

Using the COUNT Function
‡COUNT(*) returns the number of rows in a table.
SQL> SELECT 2 FROM 3 WHERE COUNT(*) --------6 COUNT(*) emp deptno = 30;

Using the COUNT Function
‡COUNT(expr) returns the number of nonnull rows.
SQL> SELECT 2 FROM 3 WHERE COUNT(COMM) ----------4 COUNT(comm) emp deptno = 30;

Using Pseudocolumns
‡A pseudocolumn behaves like a table column, but is not stored in a table. ‡ROWID returns a row¶s address.
SQL> SELECT 2 FROM 3 WHERE ROWID, ename emp deptno = 20; ENAME ------------SMITH JONES

ROWID ------------------AAAAdNAAEAAAAEbAAD AAAAdNAAEAAAAEbAAJ ...

Using Pseudocolumns
ROWNUM returns a number indicating the order in which the row is selected.
SQL> SELECT empno, ename, job, mgr, hiredate 2 FROM emp 3 WHERE ROWNUM < 5;

This statement uses ROWNUM to limit the number of rows shown by the EMPNO JOB MGR HIREDATE query. ENAME
--------7839 7698 7782 7566 ---------KING BLAKE CLARK JONES --------- --------- --------PRESIDENT 17-NOV-81 MANAGER 7839 01-MAY-81 MANAGER 7839 09-JUN-81 MANAGER 7839 02-APR-81

Summary
± ± ± ± NVL DECODE COUNT PSEUDOCOLUMNS

SQL*Plus

What is SQL*Plus ?
- An Oracle Product with which SQL and certain other commands may be used - has its own command language for controlling the behaviour of the product, and for formatting the output from SQL queries.

SQL Statements Versus SQL*Plus Commands
SQL ‡ Is a language ‡ Is ANSI standard ‡ Keywords cannot be abbreviated ‡ Statements manipulate data and table definitions in the database
SQL statements SQL buffer

SQL*Plus ‡ Is an environment ‡ Is Oracle proprietary ‡ Keywords can be abbreviated ‡ Commands do not allow manipulation of values in the database
SQL*Plus commands SQL*Plus buffer

Overview of SQL*Plus
With SQL*Plus you can:
±Describe the table structure. ±Edit your SQL statement. ±Execute SQL from SQL*Plus. ±Save SQL statements to files and append SQL statements to files. ±Execute saved files. ±Load commands from file to buffer for editing. ±Format columns.

Displaying Table Structure
Use the SQL*Plus DESCRIBE command to display the structure of a table.
DESC[RIBE] tablename SQL> DESCRIBE dept Name Null? ----------------- -------DEPTNO NOT NULL DNAME LOC Type ---NUMBER(2) VARCHAR2(14) VARCHAR2(13)

SQL*Plus Editing Commands
±A[PPEND] text ±C[HANGE] / old / new ±C[HANGE] / text / ±CL[EAR] BUFF[ER] ±DEL ±DEL n ±DEL m n

SQL*Plus Editing Commands
±I[NPUT] ±I[NPUT] text ±L[IST] ±L[IST] n ±L[IST] m n ±R[UN] ±n ±n text ±0 text

SQL*Plus File Commands
±SAVE filename ±GET filename ±START filename ±@ filename ±EDIT filename ±SPOOL filename ±EXIT

Summary of SQL*Plus
‡ Displaying table structure ‡ Editing Commands ‡ File Commands

You're Reading a Free Preview

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