Download as PPT, PDF, TXT or read online from Scribd
Download as ppt, pdf, or txt
You are on page 1of 268
SQL Plus Introduction
Copyright Wipro Technologies
Training Manual 2 Communicating with a RDBMS Using SQL Database SQL> SELECT loc 2 FROM dept; SQL statement is entered Message is sent to the Client Query is sent to Database Location ------------- Dallas New York Santa Clara Dept 3 Types Of SQL Statements SELECT Data Retrieval INSERT DELETE UPDATE Data Manipulation Language (DML) CREATE ALTER DROP RENAME TRUNCATE Data Definition Language (DDL) COMMIT ROLLBACK SAVEPOINT Transaction Control Language (TCL) GRANT REVOKE Data Control Language (DCL) 4 Objectives Capabilities of SQL SELECT statements
Execute a basic SELECT statement
Differentiate between SQL statements and SQL*Plus commands 5 Basic SELECT Statement SELECT [DISTINCT] {*, column [alias],...} FROM table; SELECT identifies what columns
FROM identifies which table 6 Guidelines Writing SQL Statements SQL statements are not case sensitive. SQL statements can be on one or More lines. Keywords cannot be abbreviated or split across lines. Clauses are usually placed on separate lines. Tabs and indents are used to enhance readability. 7
SQL> SELECT * 2 FROM dept; Selecting All Columns DEPTNO DNAME LOC --------- -------------- ------------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON 8
Selecting Specific Columns DEPTNO LOC --------- ------------- 10 NEW YORK 20 DALLAS 30 CHICAGO 40 BOSTON SQL> SELECT deptno, loc 2 FROM dept; 9 Arithmetic Expressions Basic Arithmetic operators used in SQLs Operator + - * / Description Add Subtract Multiply Divide 10
Using Arithmetic Operators
SQL> SELECT ename, sal, sal+300 2 FROM emp; 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. 11 Operator Precedence Multiplication and division take priority over addition and subtraction. Operators of the same priority are evaluated from left to right. Override operator precedence using parentheses
* / + _ 12
Operator Precedence SQL> SELECT ename, sal, 12*sal+100 2 FROM emp; 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. 13
Using Parentheses SQL> SELECT ename, sal, 12*(sal+100) 2 FROM emp; ENAME SAL 12*(SAL+100) ---------- --------- ----------- KING 5000 61200 BLAKE 2850 35400 CLARK 2450 30600 JONES 2975 36900 MARTIN 1250 16200 ... 14 rows selected. 14
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. SQL> SELECT ename, job, comm 2 FROM emp; ENAME JOB COMM ---------- --------- --------- KING PRESIDENT BLAKE MANAGER ... TURNER SALESMAN 0 ... 14 rows selected. 15
Using the DISTINCT Clause Eliminate duplicate rows by using the DISTINCT keyword SQL> SELECT DISTINCT deptno 2 FROM emp; DEPTNO --------- 10 20 30
16 SQL and SQL*Plus Commands
SQL
A language ANSI standard Keyword cannot be abbreviated Statements manipulate data and table definitions in the database SQL statements are stored in buffer
SQL*Plus
An environment Oracle proprietary Keywords can be abbreviated Commands do not allow manipulation of values in the database SQL*PLUS statements are not stored in Buffer
17 SQL*Plus Commands A[PPEND] text C[HANGE] / old / new C[HANGE] / text / CL[EAR] BUFF[ER] DEL DEL n DEL m n 18 SQL*Plus Commands I[NPUT] I[NPUT] text L[IST] L[IST] n L[IST] m n R[UN] 19 SQL*Plus File Commands SAVE filename GET filename START filename @ filename EDIT filename SPOOL filename 20 Summary Use SQL*Plus as an environment to: Execute SQL statements Edit SQL statements SELECT [DISTINCT] {*,column[alias],...} FROM table; 21 Objectives
Limiting the rows retrieved Sorting the rows retrieved 22
Using the WHERE Clause Restrict the rows returned by using the WHERE clause. SELECT [DISTINCT] {*, column [alias], ...} FROM table [WHERE condition(s)]; The WHERE clause follows the FROM clause. 23
Using the WHERE Clause SQL> SELECT ename, job, deptno 2 FROM emp 3 WHERE job='CLERK'; ENAME JOB DEPTNO ---------- --------- --------- JAMES CLERK 30 SMITH CLERK 20 ADAMS CLERK 20 MILLER CLERK 10 24 Working with Character Strings and Dates Character strings and date values are enclosed in single quotation marks Character values are case-sensitive and date values are format-sensitive Default date format is 'DD-MON-YY' SQL> SELECT ename, job, deptno 2 FROM emp 3 WHERE ename = 'JAMES'; 25 Using the Comparison Operators Operator = > >= < <= <> Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to 26
Using the Comparison Operators SQL> SELECT ename, sal, comm 2 FROM emp 3 WHERE sal<=comm; ENAME SAL COMM ---------- --------- --------- MARTIN 1250 1400 27 Other Comparison Operators Operator BETWEEN ...AND... IN(list) LIKE IS NULL Meaning Between two values (inclusive)
Match any of a list of values Match a character pattern Is a null value 28
Using the BETWEEN Operator ENAME SAL ---------- --------- MARTIN 1250 TURNER 1500 WARD 1250 ADAMS 1100 MILLER 1300
SQL> SELECT ename, sal 2 FROM emp 3 WHERE sal BETWEEN 1000 AND 1500; Lower limit Higher limit Use the BETWEEN operator to display rows based on a range of values. 29
Using the IN Operator Use the IN operator to test for values in a list. SQL> SELECT empno, ename, sal, mgr 2 FROM emp 3 WHERE mgr IN (7902, 7566, 7788); EMPNO ENAME SAL MGR --------- ---------- --------- --------- 7902 FORD 3000 7566 7369 SMITH 800 7902 7788 SCOTT 3000 7566 7876 ADAMS 1100 7788 30
Using the LIKE Operator Use the LIKE operator to perform wildcard searches of valid search string values. % denotes zero or many characters _ denotes one character SQL> SELECT ename 2 FROM emp 3 WHERE ename LIKE 'S%'; 31
Using the LIKE Operator You can use the ESCAPE identifier to search for "%" or "_". SQL> SELECT ename 2 FROM emp 3 WHERE ename LIKE '_A%'; ENAME ---------- JAMES WARD 32
Using the IS NULL Operator Use the IS NULL operator to test for null values SQL> SELECT ename, mgr 2 FROM emp 3 WHERE mgr IS NULL; ENAME MGR ---------- --------- KING 33 Logical Operators Operator AND
OR
NOT 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 34
Using the AND Operator AND requires both conditions to be TRUE. SQL> SELECT empno, ename, job, sal 2 FROM emp 3 WHERE sal>=1100 4 AND job='CLERK'; EMPNO ENAME JOB SAL --------- ---------- --------- --------- 7876 ADAMS CLERK 1100 7934 MILLER CLERK 1300 35
Using the OR Operator OR requires either condition to be TRUE. SQL> SELECT empno, ename, job, sal 2 FROM emp 3 WHERE sal>=1100 4 OR job='CLERK'; EMPNO ENAME JOB SAL --------- ---------- --------- ---------
7839 KING PRESIDENT 5000 7698 BLAKE MANAGER 2850 7782 CLARK MANAGER 2450 7566 JONES MANAGER 2975 7654 MARTIN SALESMAN 1250 ... 14 rows selected. 36
Using the NOT Operator SQL> SELECT ename, job 2 FROM emp 3 WHERE job NOT IN ('CLERK','MANAGER','ANALYST'); ENAME JOB ---------- --------- KING PRESIDENT MARTIN SALESMAN ALLEN SALESMAN TURNER SALESMAN WARD SALESMAN 37 Rules of Precedence Override rules of precedence by using parentheses. Order Evaluated Operator 1 All comparison operators 2 NOT 3 AND 4 OR 38
Using the ORDER BY Clause Sort rows with the ORDER BY clause ASC: ascending order, default DESC: descending order
SQL> SELECT ename, job, deptno, hiredate 2 FROM emp 3 ORDER BY hiredate;
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. 40
Sorting the rows 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. 41
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. 42
Summary SELECT [DISTINCT] {*, column [alias], ...} FROM table [WHERE condition(s)] [ORDER BY {column, expr, alias} [ASC|DESC]]; Review Questions 44 Objectives Describe various types of functions available in SQL Use character, number, and date functions in SELECT statements Describe the use of conversion functions 45 Types of SQL Functions Functions Single-row functions Multiple-row functions 46 Single-Row Functions Act on each row returned Return one result per row Can be nested function_name (column|expression, [arg1, arg2,...]) 47 Single-Row Functions Conversion Character Number Date General Single-row functions 48 Using Character Functions Character functions LOWER UPPER INITCAP CONCAT SUBSTR LENGTH INSTR LPAD Case conversion functions Character manipulation functions 49 Function Result Using Case Conversion Functions Convert case for character strings LOWER('SQL Course') UPPER('SQL Course') INITCAP('SQLCourse') sql course SQL COURSE Sql Course 50 Using Case Conversion Functions Display the employee number, name, and department number for employee Blake. SQL> SELECT empno, ename, deptno 2 FROM emp 3 WHERE ename = 'blake'; no rows selected
EMPNO ENAME DEPTNO --------- ---------- --------- 7698 BLAKE 30 SQL> SELECT empno, ename, deptno 2 FROM emp 3 WHERE LOWER(ename) = 'blake'; 51 CONCAT('Good', 'String') SUBSTR('String',1,3) LENGTH('String') INSTR('String', 'r') LPAD(sal,10,'*') GoodString Str 6 3 ******5000 Function Result Character Manipulation Functions Manipulate character strings 52
Using the Character Manipulation Functions SQL> SELECT ename, CONCAT (ename, job), LENGTH(ename), 2 INSTR(ename, 'A') 3 FROM emp 4 WHERE SUBSTR(job,1,5) = 'SALES'; ENAME CONCAT(ENAME,JOB) LENGTH(ENAME) INSTR(ENAME,'A') ---------- ------------------- ------------- ---------------- MARTIN MARTINSALESMAN 6 2 ALLEN ALLENSALESMAN 5 1 TURNER TURNERSALESMAN 6 0 WARD WARDSALESMAN 4 2 53 Using the Number Functions ROUND: Rounds value to specified decimal ROUND(45.926, 2) 45.93 TRUNC: Truncates value to specified decimal TRUNC(45.926, 2) 45.92 MOD: Returns remainder of division MOD(1600, 300) 100 54 Working with Dates Oracle stores dates in an internal numeric format: Century, year, month, day, hours, minutes, seconds. The default date format is DD-MON-YY. SYSDATE is a function returning date and time. DUAL is a dummy table used to view SYSDATE. 55 Arithmetic with Dates Add or subtract a number to or from a date for a resultant date value. Subtract two dates to find the number of days between those dates. Add hours to a date by dividing the number of hours by 24. 56
Using Arithmetic Operators With Dates SQL> SELECT ename, (SYSDATE-hiredate)/7 WEEKS 2 FROM emp 3 WHERE deptno = 10; ENAME WEEKS ---------- --------- KING 830.93709 CLARK 853.93709 MILLER 821.36566 57 Working with Date Functions Number of months between two dates MONTHS_BETWEEN ADD_MONTHS NEXT_DAY LAST_DAY ROUND TRUNC Add calendar months to date Next day of the date specified Last day of the month Round date Truncate date FUNCTION DESCRIPTION 58 Using Date Functions ROUND('25-JUL-95','MONTH') 01-AUG-95 ROUND('25-JUL-95','YEAR') 01-JAN-96 TRUNC('25-JUL-95','MONTH') 01-JUL-95 TRUNC('25-JUL-95','YEAR') 01-JAN-95 59 Conversion Functions Implicit datatype conversion Explicit datatype conversion Datatype conversion 60 Implicit Datatype Conversion For assignments, Oracle can automatically convert VARCHAR2 or CHAR From To VARCHAR2 or CHAR NUMBER DATE NUMBER DATE VARCHAR2 VARCHAR2 61 Explicit Datatype Conversion NUMBER CHARACTER TO_CHAR TO_NUMBER DATE TO_CHAR TO_DATE 62 Using the TO_CHAR Function with Dates The format model: Must be enclosed in single quotation marks and is case sensitive Can include any valid date format element Has an fm element to remove padded blanks or suppress leading zeros Is separated from the date value by a comma TO_CHAR(date, 'fmt') 63 YYYY Date Format Model YEAR MM MONTH DY DAY Full year in numbers Year spelled out 2-digit value for month 3-letter abbreviation of the day of the week Full name of the day Full name of the month 64 Date Format Model Elements Time elements format the time portion of the date.
HH24:MI:SS AM 15:45:32 PM DD "of" MONTH 12 of OCTOBER ddspth fourteenth Add character strings by enclosing them in double quotation marks. Number suffixes spell out numbers. 65 Using the TO_CHAR Function with Numbers Use these formats with the TO_CHAR function to display a number value as a character. TO_CHAR(number, 'fmt') 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 66 TO_NUMBER and TO_DATE Functions Convert a character string to a number format using the TO_NUMBER function TO_NUMBER(char) Convert a character string to a date format using the TO_DATE function TO_DATE(char[, 'fmt']) 67 Windowing Technique using the RR Date Format Current Year 1995 1995 2001 2001 Specified Date 27-OCT-95 27-OCT-17 27-OCT-17 27-OCT-95 RR Format 1995 2017 2017 1995 YY Format 1995 1917 2017 2095 If two digits of the current year are 0-49 0-49 50-99 50-99 The return date is in the current century. The return date is in the century after the current one. The return date is in the century before the current one. The return date is in the current century. If the specified two-digit year is 68
SQL> SELECT ename, sal, comm, (sal*12)+NVL(comm,0) 2 FROM emp; Using the NVL Function 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. 69 Using the 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]) 70
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. 71 Nesting Functions Single-row functions can be nested to any level. They follow Function of Function rule F3(F2(F1(col,arg1),arg2),arg3) Step 1 = Result 1 Step 2 = Result 2 Step 3 = Result 3 72 Summary Perform calculations on data Modify individual data items Alter date formats for display Convert column data types Review Questions Review Questions Review Questions 76 Objectives Cartesian Products How to access data from more than one table using equality and non-equality joins View data that generally does not meet a join condition by using outer joins Join a table to itself 77
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. Getting Data from Multiple Tables EMP DEPT EMPNO ENAME ... DEPTNO ------ ----- ... ------ 7839 KING ... 10 7698 BLAKE ... 30 ... 7934 MILLER ... 10 DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON 78 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. 79 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 80 Cartesian Product ENAME DNAME ------ ---------- KING ACCOUNTING BLAKE ACCOUNTING ... KING RESEARCH BLAKE RESEARCH ... 56 rows selected. EMP (14 rows) DEPT (4 rows) EMPNO ENAME ... DEPTNO ------ ----- ... ------ 7839 KING ... 10 7698 BLAKE ... 30 ... 7934 MILLER ... 10 DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON Cartesian product: 14*4=56 rows 81 Types of Joins Equijoins Non- Equijoins Outer Joins Self Joins 82
What Is an Equijoin? EMP DEPT 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. DEPTNO DNAME LOC ------- ---------- -------- 10 ACCOUNTING NEW YORK 30 SALES CHICAGO 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 20 RESEARCH DALLAS 20 RESEARCH DALLAS ... 14 rows selected. 83
Retrieving Records with Equijoins SQL> SELECT emp.empno, emp.ename, emp.deptno, 2 dept.deptno, dept.loc 3 FROM emp, dept 4 WHERE 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. 84
Using 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; 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; 85 Joining More Than Two Tables NAME CUSTID ----------- ------ JOCKSPORTS 100 TKB SPORT SHOP 101 VOLLYRITE 102 JUST TENNIS 103 K+T SPORTS 105 SHAPE UP 106 WOMENS SPORTS 107 ... ... 9 rows selected. CUSTOMER CUSTID ORDID ------- ------- 101 610 102 611 104 612 106 601 102 602 106 604 106 605 ... 21 rows selected. ORD ORDID ITEMID ------ ------- 610 3 611 1 612 1 601 1 602 1 ... 64 rows selected. ITEM 86
Non-Equijoins EMP SALGRADE salary in the EMP table is between low salary and high salary in the SALGRADE table 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. GRADE LOSAL HISAL ----- ----- ------ 1 700 1200 2 1201 1400 3 1401 2000 4 2001 3000 5 3001 9999 87
Retrieving Records with Non-Equijoins ENAME SAL GRADE ---------- --------- --------- JAMES 950 1 SMITH 800 1 ADAMS 1100 1 ... 14 rows selected. SQL> SELECT e.ename, e.sal, s.grade 2 FROM emp e, salgrade s 3 WHERE e.sal 4 BETWEEN s.losal AND s.hisal; 88
Outer Joins EMP DEPT No employee in the OPERATIONS department ENAME DEPTNO ----- ------ KING 10 BLAKE 30 CLARK 10 JONES 20 ...
DEPTNO DNAME ------ ---------- 10 ACCOUNTING 30 SALES 10 ACCOUNTING 20 RESEARCH ... 40 OPERATIONS 89 Outer Joins You use an outer join to also see rows that do not usually meet the join condition. Outer join operator is the plus 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(+); 90
Using Outer Joins SQL> SELECT e.ename, d.deptno, d.dname 2 FROM emp e, dept d 3 WHERE e.deptno(+) = d.deptno 4 ORDER BY e.deptno; ENAME DEPTNO DNAME ---------- --------- ------------- KING 10 ACCOUNTING CLARK 10 ACCOUNTING ... 40 OPERATIONS 15 rows selected. 91
Self Joins EMP (WORKER) EMP (MANAGER) "MGR in the WORKER table is equal to EMPNO in the MANAGER table" EMPNO ENAME MGR ----- ------ ---- 7839 KING 7698 BLAKE 7839 7782 CLARK 7839 7566 JONES 7839 7654 MARTIN 7698 7499 ALLEN 7698 EMPNO ENAME ----- --------
7839 KING 7839 KING 7839 KING 7698 BLAKE 7698 BLAKE 92
Joining a Table to Itself WORKER.ENAME||'WORKSFOR'||MANAG ------------------------------- BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE ... 13 rows selected. SQL> SELECT worker.ename||' works for '||manager.ename 2 FROM emp worker, emp manager 3 WHERE worker.mgr = manager.empno; 93 Summary SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column1 = table2.column2; Types of Joins
Equijoins Non- Equijoins Outer Joins Self Joins 97 Objectives Various group functions Group data using the GROUP BY clause Include or exclude grouped rows by using the HAVING clause 98
What Are Group Functions? Group functions operate on sets of rows to give one result per group. EMP maximum salary in the EMP table 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 99 Common Group Functions AVG COUNT MAX MIN STDDEV SUM VARIANCE 100 Using Group Functions
SELECT column, group_function(column) FROM table [WHERE condition] [ORDER BY column]; 101
Using the COUNT Function COUNT(*) --------- 6 SQL> SELECT COUNT(*) 2 FROM emp 3 WHERE deptno = 30; COUNT(*) returns the number of rows in a table. 102
Using the COUNT Function COUNT(expr) returns the number of nonnull rows. SQL> SELECT COUNT(comm) 2 FROM emp 3 WHERE deptno = 30; COUNT(COMM) ----------- 4 103
Group Functions and Null Values Group functions ignore null values in the column. SQL> SELECT AVG(comm) 2 FROM emp; AVG(COMM) --------- 550 104
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 105
Creating Groups of Data EMP average salary in EMP table for each department 2916.6667 2175 1566.6667 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
DEPTNO AVG(SAL) ------- --------- 10 2916.6667 20 2175 30 1566.6667 106 Using the GROUP BY Clause
SELECT column, group_function(column) FROM table [WHERE condition] [GROUP BY group_by_expression] [ORDER BY column]; Divide rows in a table into smaller groups by using the GROUP BY clause. 107
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 108
Grouping by More Than One Column
EMP sum salaries in the EMP table for each job, grouped by department DEPTNO JOB SAL --------- --------- --------- 10 MANAGER 2450 10 PRESIDENT 5000 10 CLERK 1300 20 CLERK 800 20 CLERK 1100 20 ANALYST 3000 20 ANALYST 3000 20 MANAGER 2975 30 SALESMAN 1600 30 MANAGER 2850 30 SALESMAN 1250 30 CLERK 950 30 SALESMAN 1500 30 SALESMAN 1250 JOB SUM(SAL) --------- --------- CLERK 1300 MANAGER 2450 PRESIDENT 5000 ANALYST 6000 CLERK 1900 MANAGER 2975 CLERK 950 MANAGER 2850 SALESMAN 5600 DEPTNO -------- 10 10 10 20 20 20 30 30 30 109
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. 110 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 111 Illegal Queries Using Group Functions You cannot use the WHERE clause to restrict groups.Use the HAVING clause to restrict groups. SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 WHERE AVG(sal) > 2000 4 GROUP BY deptno; WHERE AVG(sal) > 2000 * ERROR at line 3: ORA-00934: group function is not allowed here 112
Segregating Group Results maximum salary per department greater than $2900 EMP 5000 3000 2850 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 DEPTNO MAX(SAL) --------- --------- 10 5000 20 3000 113
Using the HAVING Clause Use the HAVING clause to restrict groups Only the Groups matching the HAVING clause are displayed. SELECT column, group_function FROM table [WHERE condition] [GROUP BY group_by_expression] [HAVING group_condition] [ORDER BY column]; 114
Using the HAVING Clause SQL> SELECT deptno, max(sal) 2 FROM emp 3 GROUP BY deptno 4 HAVING max(sal)>2900; DEPTNO MAX(SAL) --------- --------- 10 5000 20 3000 115 Using the HAVING Clause
SQL> SELECT job, SUM(sal) PAYROLL 2 FROM emp 3 WHERE job NOT LIKE 'SALES%' 4 GROUP BY job 5 HAVING SUM(sal)>5000 6 ORDER BY SUM(sal);
Nesting Group Functions SQL> SELECT max(avg(sal)) 2 FROM emp 3 GROUP BY deptno; MAX(AVG(SAL)) ------------- 2916.6667 Display the maximum average salary. 117
Summary SELECT column, group_function (column) FROM table [WHERE condition] [GROUP BY group_by_expression] [HAVING group_condition] [ORDER BY column]; Order of evaluation of the clauses: WHERE clause GROUP BY clause HAVING clause Review Questions Review Questions 120 Objectives Describe the types of problems that subqueries can solve Define subqueries List the types of subqueries Write single-row , multiple-row and multiple column subqueries 121 Using a Subquery to Solve a Problem Who has a salary greater than Joness? Which employees have a salary greater than Joness salary? Main Query ? What is Joness salary? ? Subquery 122
Subqueries The subquery (inner query) executes once before the main query. The result of the subquery is used by the main query (outer query). SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table); 123 2975 SQL> SELECT ename 2 FROM emp 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE empno=7566);
Using a Subquery ENAME ---------- KING FORD SCOTT 124 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 multiple-row subqueries. 125 Types of Subqueries Single-row subquery Main query Subquery
returns CLERK Multiple-row subquery CLERK MANAGER Main query Subquery
returns Multiple-column subquery CLERK 7900 MANAGER 7698 Main query Subquery
returns 126 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 127
Executing Single-Row Subqueries CLERK 1100 ENAME JOB ---------- --------- MILLER CLERK SQL> SELECT ename, job 2 FROM emp 3 WHERE job = 4 (SELECT job 5 FROM emp 6 WHERE empno = 7369) 7 AND sal > 8 (SELECT sal 9 FROM emp 10 WHERE empno = 7876); 128
Using Group Functions in a Subquery 800 ENAME JOB SAL ---------- --------- --------- SMITH CLERK 800 SQL> SELECT ename, job, sal 2 FROM emp 3 WHERE sal = 4 (SELECT MIN(sal) 5 FROM emp); 129
HAVING Clause with Subqueries The Oracle Server executes subqueries first. 800 SQL> SELECT deptno, MIN(sal) 2 FROM emp 3 GROUP BY deptno 4 HAVING MIN(sal) > 5 (SELECT MIN(sal) 6 FROM emp 7 WHERE deptno = 20); 130
What Is Wrong with This Statement? ERROR: ORA-01427: single-row subquery returns more than one row
no rows selected SQL> SELECT empno, ename 2 FROM emp 3 WHERE sal = 4 (SELECT MIN(sal) 5 FROM emp 6 GROUP BY deptno); 131
Will This Statement Work? no rows selected SQL> SELECT ename, job 2 FROM emp 3 WHERE job = 4 (SELECT job 5 FROM emp 6 WHERE ename='SMYTHE'); 132 Multiple-Row Subqueries Return more than one row Use multiple-row comparison operators Operator IN ANY
ALL 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 133
Using ANY Operator in Multiple-Row Subqueries 950 800 1100 1300 EMPNO ENAME JOB --------- ---------- --------- 7654 MARTIN SALESMAN 7521 WARD SALESMAN SQL> SELECT empno, ename, job 2 FROM emp 3 WHERE sal < ANY 4 (SELECT sal 5 FROM emp 6 WHERE job = 'CLERK') 7 AND job <> 'CLERK'; 134
Using ALL Operator in Multiple-Row Subqueries 2916.6667 2175 1566.6667 EMPNO ENAME JOB --------- ---------- --------- 7839 KING PRESIDENT 7566 JONES MANAGER 7902 FORD ANALYST 7788 SCOTT ANALYST SQL> SELECT empno, ename, job 2 FROM emp 3 WHERE sal > ALL 4 (SELECT avg(sal) 5 FROM emp 6 GROUP BY deptno); 135 Multiple-Column Subqueries Main query MANAGER 10 Subquery SALESMAN 30 MANAGER 10 CLERK 20
Main query compares MANAGER 10 Values from a multiple-row and multiple-column subquery SALESMAN 30 MANAGER 10 CLERK 20
to 136
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 ename, deptno, sal, comm 2 FROM emp 3 WHERE (sal, NVL(comm,-1)) IN 4 (SELECT sal, NVL(comm,-1) 5 FROM emp 6 WHERE deptno = 30); 137
Using a Subquery in the FROM Clause ENAME SAL DEPTNO SALAVG ---------- --------- --------- ---------- KING 5000 10 2916.6667 JONES 2975 20 2175 SCOTT 3000 20 2175 ... 6 rows selected. SQL> SELECT a.ename, a.sal, a.deptno, b.salavg 2 FROM emp a, (SELECT deptno, avg(sal) salavg 3 FROM emp 4 GROUP BY deptno) b 5 WHERE a.deptno = b.deptno 6 AND a.sal > b.salavg; 138 Summary Single row subqueries
A multiple-column subquery returns more than one column.
A multiple-column subquery can also be used in the FROM clause of a SELECT statement. Review Questions Review Questions Review Questions 142 Objectives Insert rows into a table Update rows in a table Delete rows from a table Controlling the Transactions 143 Data Manipulation Language A DML statement is executed when you: Add new rows to a table Modify existing rows in a table Remove existing rows from a table A transaction consists of a collection of DML statements that form a logical unit of work. 144 The INSERT Statement Add new rows to a table by using the INSERT statement. INSERT INTO table [(column [, column...])] VALUES (value [, value...]); 145 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.
Enclose character and date values within single quotation marks. SQL> INSERT INTO dept (deptno, dname, loc) 2 VALUES (50, 'DEVELOPMENT', 'DETROIT'); 1 row created. 146
Inserting Rows with Null Values Implicit method: Omit the column from the column list. SQL> INSERT INTO dept (deptno, dname ) 2 VALUES (60, 'MIS'); 1 row created. Explicit method: Specify the NULL keyword. SQL> INSERT INTO dept 2 VALUES (70, 'FINANCE', NULL); 1 row created. 147
Inserting Special Values The SYSDATE and USER function records the current date and time. SQL> INSERT INTO emp (empno, ename, job, 2 mgr, hiredate, sal, comm, 3 deptno) 4 VALUES (7196, USER, 'SALESMAN', 5 7782, SYSDATE, 2000, NULL, 6 10); 1 row created. 148
Inserting Specific Date Values Add a new employee. SQL> INSERT INTO emp 2 VALUES (2296,'AROMANO','SALESMAN',7782, 3 TO_DATE('FEB 3,97', 'MON DD, YY'), 4 1300, NULL, 10); 1 row created. Verify your addition. EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ----- ------- -------- ---- --------- ---- ---- ----- 2296 AROMANO SALESMAN 7782 03-FEB-97 1300 10 149
Inserting Values by Using Substitution (&) Variables Create an interactive script by using SQL*Plus substitution parameters. SQL> INSERT INTO dept (deptno, dname, loc) 2 VALUES (&department_id, 3 '&department_name', '&location'); Enter value for department_id: 80 Enter value for department_name: EDUCATION Enter value for location: ATLANTA
1 row created. 150 Creating a Script with Customized Prompts ACCEPT stores the value into a variable. PROMPT displays your customized text. ACCEPT department_id PROMPT 'Please enter the - department number:' ACCEPT department_name PROMPT 'Please enter - the department name:' ACCEPT location PROMPT 'Please enter the - location:' INSERT INTO dept (deptno, dname, loc) VALUES (&department_id, '&department_name', '&location'); 151
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. 152 The UPDATE Statement Modify existing rows with the UPDATE statement. UPDATE table SET column = value [, column = value] [WHERE condition]; Update more than one row at a time, if required. 153 Updating Rows in a Table All rows in the table are modified if you omit the WHERE clause. SQL> UPDATE employee 2 SET deptno = 20; 14 rows updated. 154 UPDATE emp * ERROR at line 1: ORA-02291: integrity constraint (USR.EMP_DEPTNO_FK) violated - parent key not found SQL> UPDATE emp 2 SET deptno = 55 3 WHERE deptno = 10; Updating Rows: Integrity Constraint Error 155 The DELETE Statement You can remove existing rows from a table by using the DELETE statement. DELETE [FROM] table [WHERE condition]; 156 Specific row or rows are deleted when you specify the WHERE clause. Deleting Rows from a Table SQL> DELETE FROM department 2 WHERE dname = 'DEVELOPMENT'; 1 row deleted. SQL> DELETE FROM department; 4 rows deleted. All rows in the table are deleted if you omit the WHERE clause. 157 Deleting Rows: Integrity Constraint Error SQL> DELETE FROM dept 2 WHERE deptno = 10; DELETE FROM dept * ERROR at line 1: ORA-02292: integrity constraint (USR.EMP_DEPTNO_FK) violated - child record found 158 Database Transactions Consist of one of the following statements: DML statements that make up one consistent change to the data One DDL statement One DCL statement 159 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 160 DELETE Controlling Transactions Transaction Savepoint A ROLLBACK to Savepoint B DELETE Savepoint B COMMIT INSERT UPDATE ROLLBACK to Savepoint A INSERT UPDATE INSERT ROLLBACK INSERT 161 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. 162 State of the Data After COMMIT Data changes are made permanent in the database. The previous state of the data is permanently lost. All users can view the results. Locks on the affected rows are released; those rows are available for other users to manipulate. All savepoints are erased. 163 Committing Data SQL> UPDATE emp 2 SET deptno = 10 3 WHERE empno = 7782; 1 row updated. Make the changes. Commit the changes. SQL> COMMIT; Commit complete. 164
State of the Data After ROLLBACK Discard all pending changes by using the ROLLBACK statement. Data changes are undone. 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. 165 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. 166 Statement-Level Rollback If a single DML statement fails during execution, only that statement is rolled back. Oracle Server implements an implicit savepoint. All other changes are retained. The user should terminate transactions explicitly by executing a COMMIT or ROLLBACK statement. 167 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. Ensures that on the same data: Readers do not wait for writers Writers do not wait for readers 168 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 Statement INSERT UPDATE DELETE COMMIT SAVEPOINT ROLLBACK Review Questions 170 Objectives Describe the main database objects Create tables Describe the datatypes that can be used when specifying column definition Alter table definitions Drop, rename, and truncate tables 171 Database Objects Object Description Table Basic unit of storage; composed of rows and columns View Logically represents subsets of data from one or more tables Sequence Generates primary key values Index Improves the performance of some queries Synonym Gives alternative names to objects 172 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 173 The CREATE TABLE Statement You must have : CREATE TABLE privilege A storage area
You specify: Table name Column name, column datatype, and column size
CREATE TABLE [schema.]table (column datatype [DEFAULT expr]; 174 Referencing Another Users Tables Tables belonging to other users are not in the users schema. You should use the owners name as a prefix to the table. 175 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 pseudocolumn. The default datatype must match the column datatype. 176 Creating Tables
SQL> CREATE TABLE dept 2 (deptno NUMBER(2), 3 dname VARCHAR2(14), 4 loc VARCHAR2(13)); Table created. Create the table. Confirm table creation. SQL> DESCRIBE dept Name Null? Type --------------------------- -------- --------- DEPTNO NOT NULL NUMBER(2) DNAME VARCHAR2(14) LOC VARCHAR2(13) 177 Querying the Data Dictionary Describe tables owned by the user.
View distinct object types owned by the user. View tables, views, synonyms, and sequences owned by the user. SQL> SELECT * 2 FROM user_tables; SQL> SELECT DISTINCT object_type 2 FROM user_objects; SQL> SELECT * 2 FROM user_catalog; 178 Datatypes Datatype Description VARCHAR2(size) Variable-length character data CHAR(size) Fixed-length character data NUMBER(p,s) Variable-length numeric data DATE Date and time values LONG Variable-length character data up to 2 gigabytes CLOB Single-byte character data up to 4 gigabytes RAW and LONG RAW Raw binary data BLOB Binary data up to 4 gigabytes BFILE Binary data stored in an external file; up to 4 gigabytes 179 Creating a Table Using a Subquery Create a table and insert rows by combining the CREATE TABLE statement and AS subquery option.
CREATE TABLE table [column(, column...)] AS subquery; 180
SQL> CREATE TABLE dept30 2 AS 3 SELECT empno,ename,sal*12 ANNSAL,hiredate 4 FROM emp 5 WHERE deptno = 30;
Table created. Creating a Table Using a Subquery
Name Null? Type ---------------------------- -------- ----- EMPNO NOT NULL NUMBER(4) ENAME VARCHAR2(10) ANNSAL NUMBER HIREDATE DATE SQL> DESCRIBE dept30 181 The ALTER TABLE Statement Use the ALTER TABLE statement to: Add a new column Modify an existing column Define a default value for the new column
ALTER TABLE table ADD (column datatype [DEFAULT expr] [, column datatype]...); ALTER TABLE table MODIFY (column datatype [DEFAULT expr] [, column datatype]...); 182 Adding a Column
DEPT30 EMPNO ENAME ANNSAL HIREDATE ------ ---------- -------- 7698 BLAKE 34200 01-MAY-81 7654 MARTIN 15000 28-SEP-81 7499 ALLEN 19200 20-FEB-81 7844 TURNER 18000 08-SEP-81 ... add a new column into DEPT30 table
JOB New column 183 Adding a Column You use the ADD clause to add columns.
EMPNO ENAME ANNSAL HIREDATE JOB --------- ---------- --------- --------- ---- 7698 BLAKE 34200 01-MAY-81 7654 MARTIN 15000 28-SEP-81 7499 ALLEN 19200 20-FEB-81 7844 TURNER 18000 08-SEP-81 ... 6 rows selected. SQL> ALTER TABLE dept30 2 ADD (job VARCHAR2(9)); Table altered. The new column becomes the last column. 184 Modifying a Column You can change a column's datatype, size, and default value.
A change to the default value affects only subsequent insertions to the table.
ALTER TABLE dept30 MODIFY (ename VARCHAR2(15)); Table altered. 185 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. 186 Changing the Name of an Object To change the name of a table, view, sequence, or synonym, you execute the RENAME statement.
You must be the owner of the object.
SQL> RENAME dept TO department; Table renamed. 187 Truncating a Table The TRUNCATE TABLE statement: Removes all rows from a table Releases the storage space used by that table
Cannot roll back row removal when using TRUNCATE Alternatively, remove rows by using the DELETE statement
SQL> TRUNCATE TABLE department; Table truncated. 188 Adding Comments to a Table You can add comments to a table or column by using the COMMENT statement.
Comments can be viewed through the data dictionary views. ALL_COL_COMMENTS USER_COL_COMMENTS ALL_TAB_COMMENTS USER_TAB_COMMENTS
SQL> COMMENT ON TABLE emp 2 IS 'Employee Information'; Comment created. Review Questions 190 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 191 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. 192 Defining Constraints
Table constraint level column [CONSTRAINT constraint_name] constraint_type, column,... [CONSTRAINT constraint_name] constraint_type (column, ...), 194 The NOT NULL Constraint Ensures that null values are not permitted for the column
EMP EMPNO ENAME JOB ... COMM DEPTNO
7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 7782 CLARK MANAGER 10 7566 JONES MANAGER 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 195
The NOT NULL Constraint Defined at 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); 196 The UNIQUE Key Constraint
DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON UNIQUE key constraint
50 SALES DETROIT
60 BOSTON Insert into Not allowed (DNAME-SALES already exists) Allowed 197 The UNIQUE Key Constraint Defined at either the table level or the column level
DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON PRIMARY KEY Insert into
20 MARKETING DALLAS
FINANCE NEW YORK Not allowed (DEPTNO-20 already exists) Not allowed (DEPTNO is null) 199 The PRIMARY KEY Constraint Defined at either the table level or the column level
DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS ... PRIMARY KEY
EMP EMPNO ENAME JOB ... COMM DEPTNO
7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 ... FOREIGN KEY
7571 FORD MANAGER ... 200 9 7571 FORD MANAGER ... 200 Insert into Not allowed (DEPTNO-9 does not exist in the DEPT table Allowed
201 The FOREIGN KEY Constraint Defined 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)); 202 FOREIGN KEY Constraint Keywords FOREIGN KEY Defines the column in the child table at the table constraint level REFERENCES Identifies the table and column in the parent table ON DELETE CASCADE Allows deletion in the parent table and deletion of the dependent rows in the child table 203 The CHECK Constraint Defines a condition that each row must satisfy Expressions that are not allowed: References to pseudocolumns CURRVAL, NEXTVAL, LEVEL, 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),... 204 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 ALTER TABLE table ADD [CONSTRAINT constraint] type (column); 205 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. 206 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. 207 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. 208 Enabling Constraints Activate an integrity constraint currently disabled in the table definition by using the ENABLE clause.
A UNIQUE or PRIMARY KEY index is automatically created if you enable a UNIQUE key or PRIMARY KEY constraint. SQL> ALTER TABLE emp 2 ENABLE CONSTRAINT emp_empno_pk; Table altered. 209
Viewing Constraints Query the USER_CONSTRAINTS table to view all constraint definitions and names. CONSTRAINT_NAME C SEARCH_CONDITION ------------------------ - ------------------------- SYS_C00674 C EMPNO IS NOT NULL SYS_C00675 C DEPTNO IS NOT NULL EMP_EMPNO_PK P ... SQL> SELECT constraint_name, constraint_type, 2 search_condition 3 FROM user_constraints 4 WHERE table_name = 'EMP'; 210 Viewing the Columns Associated with Constraints CONSTRAINT_NAME COLUMN_NAME ------------------------- ---------------------- EMP_DEPTNO_FK DEPTNO EMP_EMPNO_PK EMPNO EMP_MGR_FK MGR SYS_C00674 EMPNO SYS_C00675 DEPTNO SQL> SELECT constraint_name, column_name 2 FROM user_cons_columns 3 WHERE table_name = 'EMP'; View the columns associated with the constraint names in the USER_CONS_COLUMNS view 211 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. Review Questions 213 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 214
Database Objects 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 Object Table
View
Sequence Index Synonym 215 Why Use Views? To restrict database access To make complex queries easy To allow data independence To present different views of the same data 216 Simple Views and Complex Views Feature Simple View Complex View Number of tables One One or More Contain Functions No Yes Contain Groups of data No Yes DML via View Yes Not Always 217 Creating a View You embed a subquery within the CREATE VIEW statement.
The subquery can contain complex SELECT syntax. The subquery cannot contain an ORDER BY clause. CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)] AS subquery [WITH CHECK OPTION [CONSTRAINT constraint]] [WITH READ ONLY] 218
Creating a View Create a view, EMPVU10, that contains details of employees in department 10. Describe the structure of the view by using the SQL*Plus DESCRIBE command. SQL> DESCRIBE empvu10 SQL> CREATE VIEW empvu10 2 AS SELECT empno, ename, job 3 FROM emp 4 WHERE deptno = 10; View created. 219
Creating a View Create a view by using column aliases in the subquery.
Select the columns from this view by the given alias names. SQL> CREATE VIEW salvu30 2 AS SELECT empno EMPLOYEE_NUMBER, ename NAME, 3 sal SALARY 4 FROM emp 5 WHERE deptno = 30; View created. 220
Retrieving Data from a View EMPLOYEE_NUMBER NAME SALARY --------------- ---------- --------- 7698 BLAKE 2850 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 7521 WARD 1250
6 rows selected. SQL> SELECT * 2 FROM salvu30; 221 Querying a View USER_VIEWS
EMPVU10 SELECT empno, ename, job FROM emp WHERE deptno = 10; SQL*Plus
SELECT * FROM empvu10; EMP
7839 KING PRESIDENT 7782 CLARK MANAGER 7934 MILLER CLERK 222
Modifying a View Modify the EMPVU10 view by using CREATE OR REPLACE VIEW clause. Add an alias for each column name.
Column aliases in the CREATE VIEW clause are listed in the same order as the columns in the subquery. SQL> CREATE OR REPLACE VIEW empvu10 2 (employee_number, employee_name, job_title) 3 AS SELECT empno, ename, job 4 FROM emp 5 WHERE deptno = 10; View created. 223
Creating a Complex View Create a complex view that contains group functions to display values from two tables. SQL> CREATE VIEW dept_sum_vu 2 (name, minsal, maxsal, avgsal) 3 AS SELECT d.dname, MIN(e.sal), MAX(e.sal), 4 AVG(e.sal) 5 FROM emp e, dept d 6 WHERE e.deptno = d.deptno 7 GROUP BY d.dname; View created. 224 Rules for Performing DML Operations on a View You can perform DML operations on simple views. You cannot remove a row if the view contains the following: Group functions A GROUP BY clause The DISTINCT keyword 225 Rules for Performing DML Operations on a View You cannot modify data in a view if it contains: Any of the conditions mentioned in the previous slide Columns defined by expressions The ROWNUM pseudocolumn You cannot add data if: The view contains any of the conditions mentioned above or in the previous slide There are NOT NULL columns in the base tables that are not selected by the view 226
Using the WITH CHECK OPTION Clause You can ensure that DML on the view stays within the domain of the view by using the WITH CHECK OPTION. Any attempt to change the department number for any row in the view will fail because it violates the WITH CHECK OPTION constraint. SQL> CREATE OR REPLACE VIEW empvu20 2 AS SELECT * 3 FROM emp 4 WHERE deptno = 20 5 WITH CHECK OPTION CONSTRAINT empvu20_ck; View created. 227
Denying DML Operations You can ensure that no DML operations occur by adding the WITH READ ONLY option to your view definition. SQL> CREATE OR REPLACE VIEW empvu10 2 (employee_number, employee_name, job_title) 3 AS SELECT empno, ename, job 4 FROM emp 5 WHERE deptno = 10 6 WITH READ ONLY; View created. Any attempt to perform a DML on any row in the view will result in Oracle Server error ORA-01752. 228
Removing a View Remove a view without losing data because a view is based on underlying tables in the database. SQL> DROP VIEW empvu10; View dropped. DROP VIEW view; 229 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 Review Questions 231 Objectives
Describe some database objects and their uses Create, maintain, and use sequences Create and maintain indexes Create private and public synonyms 232
Database Objects 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 Object Table
View
Sequence Index Synonym 233 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 234 The CREATE SEQUENCE Statement 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}]; 235 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. 236 Confirming Sequences Verify your sequence values in the USER_SEQUENCES data dictionary table.
The LAST_NUMBER column displays the next available sequence number. SQL> SELECT sequence_name, min_value, max_value, 2 increment_by, last_number 3 FROM user_sequences; 237 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. 238 Using a Sequence Insert a new department named MARKETING in San Diego.
View the current value for the DEPT_DEPTNO sequence. SQL> INSERT INTO dept(deptno, dname, loc) 2 VALUES (dept_deptno.NEXTVAL, 3 'MARKETING', 'SAN DIEGO'); 1 row created. SQL> SELECT dept_deptno.CURRVAL 2 FROM dual; 239 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. 240 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. 241 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. 242 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 243 How Are Indexes Created? 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. 244 Creating an Index Improve the speed of query access on the ENAME column in the EMP table SQL> CREATE INDEX emp_ename_idx 2 ON emp(ename); Index created. CREATE INDEX index ON table (column[, column]...); Create an index on one or more columns 245
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> SELECT ic.index_name, ic.column_name, 2 ic.column_position col_pos,ix.uniqueness 3 FROM user_indexes ix, user_ind_columns ic 4 WHERE ic.index_name = ix.index_name 5 AND ic.table_name = 'EMP'; 246 Removing an Index Remove an index from the data dictionary.
Remove the EMP_ENAME_IDX index from the data dictionary.
To drop an index, you must be the owner of the index or have the DROP ANY INDEX privilege. SQL> DROP INDEX emp_ename_idx; Index dropped. SQL> DROP INDEX index; 247 Synonyms Simplify access to objects by creating a synonym (another name for an object). Refer to a table owned by another user. Shorten lengthy object names. CREATE [PUBLIC] SYNONYM synonym FOR object; 248 Creating and Removing Synonyms SQL> CREATE SYNONYM d_sum 2 FOR dept_sum_vu; Synonym Created. SQL> DROP SYNONYM d_sum; Synonym dropped. Create a shortened name for the DEPT_SUM_VU view. Drop a synonym. 249 Summary Automatically generate sequence numbers by using a sequence generator. View sequence information in the USER_SEQUENCES data dictionary table. Create indexes to improve query retrieval speed. View index information in the USER_INDEXES dictionary table. Use synonyms to provide alternative names for objects. Review Questions DCL Statements
252 Objectives Create users Create roles to ease setup and maintenance of the security model GRANT and REVOKE object privileges 253 Controlling User Access Database administrator Users Username and password privileges 254 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 255 System Privileges More than 80 privileges are available. The DBA has high-level system privileges. Create new users Remove users Remove tables Backup tables 256 Creating Users The DBA creates users by using the CREATE USER statement. SQL> CREATE USER scott 2 IDENTIFIED BY tiger; User created. CREATE USER user IDENTIFIED BY password; 257 User System Privileges GRANT privilege [, privilege...] TO user [, user...]; An application developer may have the following system privileges: CREATE SESSION CREATE TABLE CREATE SEQUENCE CREATE VIEW CREATE PROCEDURE Once a user is created, the DBA can grant specific system privileges to a user. 258 Granting System Privileges The DBA can grant a user specific system privileges. SQL> GRANT create table, create sequence, create view 2 TO scott; Grant succeeded. 259 What Is a Role? Allocating privileges without a role Allocating privileges with a role Privileges Users Manager 260 Creating and Granting Privileges to a Role SQL> CREATE ROLE manager; Role created. SQL> GRANT create table, create view 2 to manager; Grant succeeded. SQL> GRANT manager to BLAKE, CLARK; Grant succeeded. 261 Changing Your Password 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. 262 Object Privilege Table View Sequence Procedure ALTER DELETE EXECUTE INDEX INSERT REFERENCES SELECT UPDATE Object Privileges 263 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 object_priv [(columns)] ON object TO {user|role|PUBLIC} [WITH GRANT OPTION]; 264 Granting Object Privileges SQL> GRANT select 2 ON emp 3 TO sue, rich; Grant succeeded. SQL> GRANT update (dname, loc) 2 ON dept 3 TO scott, manager; Grant succeeded. Grant query privileges on the EMP table. Grant privileges to update specific columns to users and roles. 265 Using WITH GRANT OPTION and PUBLIC Keywords Allow all users on the system to query data from Alices DEPT table. SQL> GRANT select, insert 2 ON dept 3 TO scott 4 WITH GRANT OPTION; Grant succeeded. SQL> GRANT select 2 ON alice.dept 3 TO PUBLIC; Grant succeeded. Give a user authority to pass along the privileges. 266 Confirming Privileges Granted Data Dictionary Table Description ROLE_SYS_PRIVS System privileges granted to roles ROLE_TAB_PRIVS Table privileges granted to roles USER_ROLE_PRIVS Roles accessible by the user USER_TAB_PRIVS_MADE Object privileges granted on the user's objects USER_TAB_PRIVS_RECD Object privileges granted to the user USER_COL_PRIVS_MADE Object privileges granted on the columns of the user's objects USER_COL_PRIVS_RECD Object privileges granted to the user on specific columns 267 How to 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. REVOKE {privilege [, privilege...]|ALL} ON object FROM {user[, user...]|role|PUBLIC} [CASCADE CONSTRAINTS]; 268 Revoking Object Privileges As user Alice, revoke the SELECT and INSERT privileges given to user Scott on the DEPT table. SQL> REVOKE select, insert 2 ON dept 3 FROM scott; Revoke succeeded. 269 Summary CREATE USER Allows the DBA to create a user GRANT Allows the user to give other users privileges to access the user's objects CREATE ROLE Allows the DBA to create a collection of privileges ALTER USER Allows users to change their password REVOKE Removes privileges on an object from users Review Questions Thank you