Presentation On Oracle SQL
Presentation On Oracle SQL
Database
Dept
Location ------------Dallas New York Santa Clara
Objectives Capabilities of SQL SELECT statements Execute a basic SELECT statement Differentiate between SQL statements and SQL*Plus commands
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.
DEPTNO --------10 20 30 40
Arithmetic Expressions
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
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.
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.
ENAME JOB COMM ---------- --------- --------KING PRESIDENT BLAKE MANAGER ... TURNER SALESMAN 0 ... 14 rows selected.
DEPTNO --------10 20 30
Objectives
Using the WHERE Clause Restrict the rows returned by using the WHERE clause.
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'
Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to
ENAME SAL ---------- --------MARTIN 1250 TURNER 1500 WARD 1250 ADAMS 1100 MILLER 1300
Lower limit
Higher limit
ENAME SAL MGR ---------- --------- --------FORD 3000 7566 SMITH 800 7902 SCOTT 3000 7566 ADAMS 1100 7788
Using the LIKE Operator You can use the ESCAPE identifier to search for "%" or "_".
SQL> SELECT 2 FROM 3 WHERE ENAME ---------JAMES WARD ename emp ename LIKE '_A%';
Logical Operators
Operator AND OR
Meaning Returns TRUE if both component conditions are TRUE Returns TRUE if either component condition is TRUE Returns TRUE if the following condition is FALSE
NOT
SQL> 2 3 4
empno, ename, job, sal emp sal>=1100 job='CLERK'; JOB SAL --------- --------CLERK 1100 CLERK 1300
EMPNO ENAME JOB SAL --------- ---------- --------- --------7839 7698 7782 7566 7654 KING BLAKE CLARK JONES MARTIN PRESIDENT MANAGER MANAGER MANAGER SALESMAN 5000 2850 2450 2975 1250
SQL> SELECT ename, job 2 FROM emp 3 WHERE job NOT IN ('CLERK','MANAGER','ANALYST');
Rules of Precedence
Order Evaluated 1 2 3 4
Using the ORDER BY Clause Sort rows with the ORDER BY clause
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.
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.
SQL> SELECT ename, deptno, sal 2 FROM emp 3 ORDER BY deptno, sal DESC;
ENAME DEPTNO SAL ---------- --------- --------KING 10 5000 CLARK 10 2450 MILLER 10 1300 FORD 20 3000 ... 14 rows selected.
Summary
[DISTINCT] {*, column [alias], ...} table condition(s)] {column, expr, alias} [ASC|DESC]];
Objectives
Describe various types of functions available in SQL Use character, number, and date functions in SELECT statements Describe the use of conversion functions
Functions
Single-row Singlefunctions
Multiple-row Multiplefunctions
Single-Row Functions
Act on each row returned Return one result per row Can be nested
Single-Row Functions
Character
General
Single-row Singlefunctions
Number
Conversion
Date
Result
******5000
SQL> SELECT ename, CONCAT (ename, job), LENGTH(ename), 2 INSTR(ename, 'A') 3 FROM emp 4 WHERE SUBSTR(job,1,5) = 'SALES';
ROUND(45.926, 2)
TRUNC(45.926, 2)
Returns remainder of
100
MOD(1600, 300)
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.
SQL> SELECT ename, (SYSDATE-hiredate)/7 WEEKS 2 FROM emp 3 WHERE deptno = 10;
Conversion Functions
Datatype conversion
NUMBER
CHARACTER
DATE
TO_CHAR
TO_CHAR
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
Full year in numbers Year spelled out 2-digit value for month Full name of the month 3-letter abbreviation of the day of the week Full name of the day
HH24:MI:SS AM
15:45:32 PM
DD "of" MONTH
12 of OCTOBER
ddspth
fourteenth
TO_CHAR(number, 'fmt')
Use these formats with the TO_CHAR function to display a number value as a character.
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
TO_NUMBER and TO_DATE Functions Convert a character string to a number format using the TO_NUMBER function
TO_NUMBER(char)
TO_DATE(char[, 'fmt'])
50-99
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.
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
Summary Perform calculations on data Modify individual data items Alter date formats for display Convert column data types
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
DEPT
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON
MILLER ...
EMPNO DEPTNO LOC ----- ------- -------7839 10 NEW YORK 7698 30 CHICAGO 7782 10 NEW YORK 7566 20 DALLAS 7654 30 CHICAGO 7499 30 CHICAGO ... 14 rows selected.
What Is a Join?
Use a join to query data from more than one table.
SELECT FROM WHERE table1.column, table2.column table1, table2 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.
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
Cartesian Product
EMP (14 rows)
EMPNO -----7839 7698 ... 7934 ENAME ----KING BLAKE ... DEPTNO ... -----... 10 ... 30 10
DEPT (4 rows)
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON
MILLER ...
ENAME DNAME --------------KING ACCOUNTING BLAKE ACCOUNTING ... KING RESEARCH BLAKE RESEARCH ... 56 rows selected.
Types of Joins
What Is an Equijoin?
EMP
EMPNO ENAME DEPTNO ------ ------- ------7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20 ... 14 rows selected.
DEPT
DEPTNO ------10 30 10 20 30 30 30 30 30 20 20 ... 14 rows DNAME ---------ACCOUNTING SALES ACCOUNTING RESEARCH SALES SALES SALES SALES SALES RESEARCH RESEARCH selected. LOC -------NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO DALLAS DALLAS
EMPNO ENAME DEPTNO DEPTNO LOC ----- ------ ------ ------ --------7839 KING 10 10 NEW YORK 7698 BLAKE 30 30 CHICAGO 7782 CLARK 10 10 NEW YORK 7566 JONES 20 20 DALLAS ... 14 rows selected.
SQL> SELECT e.empno, e.ename, e.deptno, 2 d.deptno, d.loc 3 FROM emp e, dept d 4 WHERE e.deptno=d.deptno;
ORD
CUSTID ORDID ------- ------101 610 102 611 104 612 106 601 102 602 ITEM 106 604 ORDID ITEMID 106 605 ------ ------... 610 3 21 rows selected. 611 1 612 1 601 1 602 1 ... 64 rows selected.
Non-Equijoins
EMP
EMPNO ENAME SAL ------ ------- -----7839 KING 5000 7698 BLAKE 2850 7782 CLARK 2450 7566 JONES 2975 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 ... 14 rows selected.
SALGRADE
GRADE LOSAL HISAL ----- ----- -----1 700 1200 2 1201 1400 3 1401 2000 4 2001 3000 5 3001 9999
salary in the EMP table is between low salary and high salary in the SALGRADE table
ENAME SAL GRADE ---------- --------- --------JAMES 950 1 SMITH 800 1 ADAMS 1100 1 ... 14 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
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;
SQL> 2 3 4
ENAME DEPTNO DNAME ---------- --------- ------------KING 10 ACCOUNTING CLARK 10 ACCOUNTING ... 40 OPERATIONS 15 rows selected.
Self Joins
EMP (WORKER)
EMPNO ----7839 7698 7782 7566 7654 7499 ENAME -----KING BLAKE CLARK JONES MARTIN ALLEN MGR ---7839 7839 7839 7698 7698
EMP (MANAGER)
EMPNO ENAME ----- -------7839 7839 7839 7698 7698 KING KING KING BLAKE BLAKE
Objectives
Various group functions Group data using the GROUP BY clause Include or exclude grouped rows by using the HAVING clause
MAX(SAL) --------5000
Common Group Functions AVG COUNT MAX MIN STDDEV SUM VARIANCE
AVG(COMM) --------550
AVG(NVL(COMM,0)) ---------------157.14286
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
Divide rows in a table into smaller groups by using the GROUP BY clause.
--------- ---------
sum salaries in the EMP table for each job, grouped by department
DEPTNO JOB SUM(SAL) --------- --------- --------10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 ANALYST 6000 20 CLERK 1900 ... 9 rows selected.
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.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
DEPTNO 10 20
3000
--------- ---------
2850
SQL> 2 3 4
MAX(AVG(SAL)) ------------2916.6667
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
Main Query
Subqueries
SELECT FROM WHERE select_list table expr operator (SELECT FROM
select_list table);
The subquery (inner query) executes once before the main query. The result of the subquery is used by the main query (outer query).
Using a Subquery
SQL> SELECT ename 2 FROM 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.
CLERK
Multiple-row subquery
Main query Subquery returns
CLERK MANAGER
Multiple-column subquery
Main query Subquery returns
Single-Row Subqueries Return only one row Use single-row comparison operators
Operator = > >= < <= <> Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to
CLERK
AND
800
MIN(sal) emp);
HAVING Clause with Subqueries The Oracle Server executes subqueries first.
SQL> 2 3 4 5 6 7
800
SQL> SELECT empno, ename 2 FROM emp 3 WHERE sal = 4 (SELECT 5 FROM 6 GROUP BY
ERROR: ORA-01427: single-row subquery returns more than one row no rows selected
job
no rows selected
Multiple-Row Subqueries Return more than one row Use multiple-row comparison operators
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
Operator IN ANY
ALL
AND
Multiple-Column Subqueries
Main query
MANAGER 10
Subquery
SALESMAN MANAGER CLERK 30 10 20
to
WHERE AND
ENAME SAL DEPTNO SALAVG ---------- --------- --------- ---------KING 5000 10 2916.6667 JONES 2975 20 2175 SCOTT 3000 20 2175 ... 6 rows selected.
Objectives Insert rows into a table Update rows in a table Delete rows from a table Controlling the Transactions
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.
The INSERT Statement Add new rows to a table by using the INSERT statement.
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 2 VALUES 1 row created. dept (deptno, dname, loc) (50, 'DEVELOPMENT', 'DETROIT');
Inserting Rows with Null Values Implicit method: Oit the column from the column list.
SQL> INSERT INTO 2 VALUES 1 row created. dept (deptno, dname ) (60, 'MIS');
emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) (7196, USER, 'SALESMAN', 7782, SYSDATE, 2000, NULL, 10);
emp (2296,'AROMANO','SALESMAN',7782, TO_DATE('FEB 3,97', 'MON DD, YY'), 1300, NULL, 10);
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 sub-query.
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.
The UPDATE Statement Modify existing rows with the UPDATE statement.
UPDATE SET [WHERE table column = value [, column = value] condition];
Updating Rows in a Table All rows in the table are modified if you omit the WHEE clause.
UPDATE emp * ERROR at line 1: ORA-02291: integrity constraint (USR.EMP_DEPTNO_FK) violated - parent key not found
table condition];
Deleting Rows from a Table Specific row or rows are deleted when you specify the WHERE clause.
All rows in the table are deleted if you omit the WHERE clause.
SQL> DELETE FROM 4 rows deleted. department;
DELETE FROM dept * ERROR at line 1: ORA-02292: integrity constraint (USR.EMP_DEPTNO_FK) violated - child record found
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
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
Controlling Transactions
Transaction
INSERT
COMMIT
UPDATE
INSERT
DELETE
Savepoint A
Savepoint B
ROLLBACK to Savepoint B
ROLLBACK to Savepoint A
ROLLBACK
Data changes are undone. Previous state of the data is restored. Locks on the affected rows are released.
SQL> DELETE FROM 14 rows deleted. SQL> ROLLBACK; Rollback complete. employee;
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 Server 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. Ensures that on the same data:
Readers do not wait for writers Writers do not wait for readers
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
Database Objects
Object Table
View
Generates primary key values Improves the performance of some queries Gives alternative names to objects
Naming Conventions Must begin with a letter Can be 130 characters long Must contain only AZ, az, 09, _, $, and # Must not duplicate the name of another object owned by the same user Must not be an Oracle Server reserved word
You specify:
Tables belonging to other users are not in the users schema. You should use the owners name as a prefix to the table.
The DEFAULT Option Specify a default value for a column during an insert.
hiredate DATE DEFAULT SYSDATE,
Legal values are literal value, expression, or SQL function. Illegal values are another columns name or pseudocolumn. The default datatype must match the column datatype.
Datatypes
Datatype VARCHAR2(size) CHAR(size) NUMBER(p,s) DATE LONG CLOB RAW and LONG RAW BLOB BFILE Description Variable-length character data Fixed-length character data Variable-length numeric data Date and time values Variable-length character data up to 2 gigabytes Single-byte character data up to 4 gigabytes Raw binary data Binary data up to 4 gigabytes Binary data stored in an external file; up to 4 gigabytes
Creating a Table Using a Subquery Create a table and insert rows by combining the CREATE CREATE TABLE table TABLE statement and AS subquery option.
[column(, column...)] AS subquery;
SQL> CREATE TABLE 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
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]...);
Adding a Column
DEPT30
EMPNO -----7698 7654 7499 7844 ... ENAME ANNSAL ---------- -------BLAKE 34200 MARTIN 15000 ALLEN 19200 TURNER 18000
New column
HIREDATE 01-MAY-81 28-SEP-81 20-FEB-81 08-SEP-81 JOB
DEPT30
EMPNO -----7698 7654 7499 7844 ... ENAME ANNSAL ---------- -------BLAKE 34200 MARTIN 15000 ALLEN 19200 TURNER 18000 HIREDATE 01-MAY-81 28-SEP-81 20-FEB-81 08-SEP-81 JOB
Modifying a Column You can change a column's datatype, size, and default value.
ALTER TABLE dept30 MODIFY (ename VARCHAR2(15)); Table altered.
A change to the default value affects only subsequent insertions to the table.
Dropping a 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.
Changing the Name of an Object To change the name of a table, view, sequence, or synonym, you execute the RENAME statement.
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.
Cannot roll back row removal when using TRUNCATE Alternatively, remove rows by using the DELETE statement
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:
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 emp( empno NUMBER(4), ename VARCHAR2(10), deptno NUMBER(7,2) NOT NULL, CONSTRAINT emp_empno_pk PRIMARY KEY (EMPNO));
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)
SQL> CREATE TABLE 2 empno 3 ename 4 job 5 mgr 6 hiredate 7 sal 8 comm 9 deptno
emp( NUMBER(4), VARCHAR2(10) NOT NULL, VARCHAR2(9), NUMBER(4), DATE, NUMBER(7,2), NUMBER(7,2), NUMBER(7,2) NOT NULL);
DEPT
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON
DEPT
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON
Not allowed (DEPTNO 20 already (DEPTNO20 exists) Not allowed (DEPTNO is null)
EMP
EMPNO ENAME 7839 KING 7698 BLAKE ... ... COMM DEPTNO 10 30 Not allowed (DEPTNO9 (DEPTNO 9 does not exist in the DEPT table Allowed FOREIGN KEY
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));
Adding a Constraint
Add or drop, but not modify, a constraint Enable or disable constraints Add a NOT NULL constraint by using the MODIFY clause
Adding a Constraint
Add a FOREIGN KEY constraint to the EMP table indicating that a manager must already exist as a valid employee in the EMP table.
SQL> ALTER TABLE 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 2 DROP CONSTRAINT Table altered. emp emp_mgr_fk;
Remove the PRIMARY KEY constraint on the DEPT table and drop the associated FOREIGN KEY constraint on the EMP.DEPTNO column.
SQL> ALTER TABLE dept 2 DROP PRIMARY KEY CASCADE; Table altered.
Disabling Constraints Execute the DISABLE clause of the ALTER TABLE statement to deactivate an integrity constraint. Apply the CASCADE option to disable dependent integrity constraints.
SQL> ALTER TABLE 2 DISABLE CONSTRAINT Table altered. emp emp_empno_pk CASCADE;
Enabling Constraints
Activate an integrity constraint currently disabled in the table definition by using the ENABLE clause.
emp emp_empno_pk;
A UNIQUE or PRIMARY KEY index is automatically created if you enable a UNIQUE key or PRIMARY KEY constraint.
Viewing Constraints
Query the USER_CONSTRAINTS table to view all constraint definitions and names.
SQL> 2 3 4 SELECT constraint_name, constraint_type, search_condition FROM user_constraints WHERE table_name = 'EMP'; C C C P SEARCH_CONDITION ------------------------EMPNO IS NOT NULL DEPTNO IS NOT NULL
View the columns associated with the constraint names in the USER_CONS_COLUMNS view
SQL> SELECT 2 FROM 3 WHERE constraint_name, column_name user_cons_columns table_name = 'EMP'; COLUMN_NAME ---------------------DEPTNO EMPNO MGR EMPNO DEPTNO
Objectives Describe a view Create a view Retrieve data through a view Alter the definition of a view Insert, update, and delete data through a view Drop a view
Database Objects
Object Table
Description Basic unit of storage; composed of rows and columns Logically represents subsets of data from one or more tables Generates primary key values Improves the performance of some queries Alternative name for an object
View
Why Use Views? To restrict database access To make complex queries easy To allow data independence To present different views of the same data
Number of tables
One
One or More
Contain Functions No
Yes
No
Yes
Yes
Not Always
Creating a View
You embed a subquery within the CREATE VIEW statement.
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)] AS subquery [WITH CHECK OPTION [CONSTRAINT constraint]] [WITH READ ONLY]
The subquery can contain complex SELECT syntax. The subquery cannot contain an ORDER BY clause.
Creating a View Create a view, EMPVU10, that contains details of employees in department 10.
SQL> 2 3 4 View CREATE VIEW AS SELECT FROM WHERE created. empvu10 empno, ename, job emp deptno = 10;
Describe the structure of the view by using the SQL*Plus DESCRIBE command.
SQL> DESCRIBE empvu10
Select the columns from this view by the given alias names.
SQL> 2
SELECT * FROM salvu30; NAME SALARY ---------- --------BLAKE 2850 MARTIN 1250 ALLEN 1600 TURNER 1500 JAMES 950 WARD 1250
6 rows selected.
Querying a View
SQL*Plus
SELECT * FROM empvu10;
USER_VIEWS
EMPVU10
SELECT FROM WHERE empno, ename, job emp deptno = 10;
EMP
Modifying a View
Modify the EMPVU10 view by using CREATE OR REPLACE VIEW clause. Add an alias for each column name.
SQL> 2 3 4 5 View
CREATE OR REPLACE VIEW empvu10 (employee_number, employee_name, job_title) AS SELECT empno, ename, job FROM emp WHERE deptno = 10; created.
Column aliases in the CREATE VIEW clause are listed in the same order as the columns in the subquery.
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:
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
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.
SQL> 2 3 4 5 View CREATE OR REPLACE VIEW empvu20 AS SELECT * FROM emp WHERE deptno = 20 WITH CHECK OPTION CONSTRAINT empvu20_ck; created.
Any attempt to change the department number for any row in the view will fail because it violates the WITH CHECK OPTION constraint.
Denying DML Operations You can ensure that no DML operations occur by adding the WITH READ ONLY option to your view definition.
SQL> 2 3 4 5 6 View CREATE OR REPLACE VIEW empvu10 (employee_number, employee_name, job_title) AS SELECT empno, ename, job FROM emp WHERE deptno = 10 WITH READ ONLY; created.
Any attempt to perform a DML on any row in the view will result in Oracle Server error ORA-01752.
Removing a View
Remove a view without losing data because a view is based on underlying tables in the database.
Objectives
Describe some database objects and their uses Create, maintain, and use sequences Create and maintain indexes Create private and public synonyms
Database Objects
Object Table
Description Basic unit of storage; composed of rows and columns Logically represents subsets of data from one or more tables Generates primary key values Improves the performance of some queries Alternative name for an object
View
What Is a Sequence? Automatically generates unique numbers Is a sharable object Is typically used to create a primary key value Replaces application code Speeds up the efficiency of accessing sequence values when cached in memory
CREATE SEQUENCE sequence [INCREMENT BY n] [START WITH n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}];
Creating a Sequence Create a sequence named DEPT_DEPTNO to be used for the primary key of the 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.
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.
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:
Modifying a Sequence
Change the increment value, maximum value, minimum value, cycle option, or cache option.
SQL> ALTER SEQUENCE dept_deptno 2 INCREMENT BY 1 3 MAXVALUE 999999 4 NOCACHE 5 NOCYCLE; Sequence altered.
Removing a Sequence Remove a sequence from the data dictionary by using the DROP SEQUENCE statement. Once removed, the sequence can no longer be referenced.
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
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.
Creating an Index
Create an index on one or more columns
CREATE INDEX index ON table (column[, column]...);
Improve the speed of query access on the ENAME column in the EMP table
SQL> CREATE INDEX 2 ON Index created. emp_ename_idx emp(ename);
Confirming Indexes The USER_INDEXES data dictionary view contains the name of the index and its uniqueness. The USER_IND_COLUMNS view contains the index name, the table name, and the
SQL> SELECT name. column 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';
To drop an index, you must be the owner of the index or have the DROP ANY INDEX privilege.
Synonyms
Simplify access to objects by creating a synonym (another name for an object).
Creating and Removing Synonyms Create a shortened name for the DEPT_SUM_VU view.
Drop a synonym.
SQL> DROP SYNONYM d_sum; Synonym dropped.
DCL Statements
Objectives Create users Create roles to ease setup and maintenance of the security model GRANT and REVOKE object privileges
Database administrator
System Privileges More than 80 privileges are available. The DBA has high-level system privileges.
Creating Users
The DBA creates users by using the CREATE USER statement.
user password;
An application developer may have the following system privileges: CREATE SESSION CREATE TABLE CREATE SEQUENCE CREATE VIEW CREATE PROCEDURE
SQL> GRANT create table, create sequence, create view 2 TO scott; Grant succeeded.
What Is a Role?
Users
Manager
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.
Object Privileges
Object Privilege ALTER DELETE EXECUTE INDEX INSERT REFERENCES SELECT UPDATE Table View Sequence Procedure
Object Privileges Object privileges vary from object to object. An owner has all the privileges on the object. An owner can give specific privileges on that owners object.
GRANT ON TO [WITH GRANT object_priv [(columns)] object {user|role|PUBLIC} OPTION];
Allow all users on the system to query data SQL> GRANT select from Alices DEPT table.
2 ON alice.dept 3 TO PUBLIC; Grant succeeded.
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];
Thank you