Beruflich Dokumente
Kultur Dokumente
SQL works with database programs like MS Access, DB2, Informix, MS SQL
Server, Oracle, Sybase, etc.
What is SQL?
What is SQL?
Pronounced as SEQUEL
Oracle SQL
Oracle has enhancements to the basic SQL engine. These
enhancement include the following:
PL/SQL is the procedural portion. It combines SQL and a procedural language. It
is incorporated into SQL engine
Data Retrieval
Data Retrieval
SELECT:
used to retrieve the data present in the database tables
CREATE
ALTER
DROP
RENAME
GRANT :Allow access privileges to users (e.g. select, insert, update, alter, delete,
etc to nominated tables or attribute in tables)
Data Types
Data Types
The Basic Select Statement
Writing SQL Statements
The SELECT statement is used to select data from a table. The tabular result is
stored in a result table (called the result-set).
Syntax
SELECT <column_name(s)>
FROM <table_name>
Selecting Columns
All Columns
SELECT *
FROM departments;
Specific Columns
SELECT department_id,location_id
FROM departments;
Example
Changing the column order
SELECT FirstName, LastName
FROM Persons
Selecting all coloumns
The SELECT DISTINCT Statement
SELECT DISTINCT Company FROM Orders
Orders
Restricting and Sorting Data
The WHERE Clause
Character Strings and Dates
Comparison Operators
Use the LIKE condition to perform wildcard searches of valid search string values
% denotes zero or many characters
_ denotes one character (underscore)
Examples
BETWEEN..AND operator
SELECT ename, sal FROM emp
WHERE sal BETWEEN 2500 AND 3500;
IN operator
SELECT empno, ename, sal FROM emp
WHERE mgr IN (100, 101, 201);
LIKE operator
SELECT ename FROM
emp
WHERE ename LIKE S% ;
IS NULL operator
FROM
employees
ORDER BY hire_date ;
SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date DESC ;
Sort order can be specified by position value also
Sorting (Examples)
Summary
In this lesson, you learned about :
SQL
What is Data?
Data (plural of the word Datum) - Data is a factual information used as a basis
for reasoning, discussion, or calculation
Data may be numerical data which may be integers or floating point numbers, and
non-numerical data such as characters, date and etc. Data by itself normally doesnt have
a meaning associated with it.
e.g:Krishnan
01-Jan-71
15-Jun-05
50000
Information
Related data is often called as information. Information will always have a meaning
and context attached to the data element. Let us consider the same example that we
gave for data. When we add meaning and context to the data it becomes information:
Basic Constructs
Sequential records
A record contains sequential fields
Basic operation
Open, close, or reset a file
Read, write or delete a record
Disadvantages of File processing system
Data isolation
Integrity problems
Atomicity problem
Concurrent access anomalies
Security problems
Data are represented by collection of records and the relationship among data are
represented by links, which can be viewed as pointers.
A record is a collection of fields (attributes), each of which contains only one data
value.
Hierarchical Model
Network Model (1960s)
Data are represented by collection of records and the relationship among data are
represented by links, which can be viewed as pointers.
Record is a collection of fields (attributes), each of which contains only one data
Network Model
Relational Model (1980s)
Every table has one or more set of attributes that taken together as a "key"
uniquely identifies each entity
Customer
Account
Relational Model
Relationship is established with the help of keys
Database Management System
(DBMS)
The general purpose of a DBMS is to provide for the definition, storage, and
management of data in a centralized area that can be shared by many users.
Purpose of a DBMS
DBMS developed to handle the following difficulties:
Functionality of a DBMS
Integrity enforcement
integrity constraints
Concurrent control
multiple user environment
Crash recovery
Data Models
Record-Based Logical
Models
Physical Data
Models
Unifying
Frame-Memory
Data Abstraction
View Level
describes only a part of the database useful for a particular user
Database Languages
host language:
DBMS Structure
Relations
Relations
Relations
Codds Rule for RDBMS
Rule 1: The Information Rule
All data should be presented to the user in table form
Rule 2: Guaranteed Access Rule
All data should be accessible without ambiguity.
This can be accomplished through a combination
of the table name, primary key, and column name.
Rule 3: Systematic Treatment of Null Values
A field should be allowed to remain empty. This
involves the support of a null value, which is distinct
from an empty string or a number with a value of
zero. Of course, this can't apply to primary keys. In
addition, most database implementations support the
concept of a not null field constraint that prevents null
values in a specific table column.
Rule 4: Dynamic On-Line Catalog Based on the Relational Model
A relational database must provide access to its structure
through the same tools that are used to access the data.
This is usually accomplished by storing the structure
definition within special system tables.
DELETE. If a row is deleted, then not only is the information about quantity and
part lost but also information about the supplier.
UPDATE. If supplier s1 moved from London to New York, then six rows would
have to be updated with this new information.
Identify any determinants other than the composite key, and the columns they
determine.
Create and name a new table for each determinant and the unique columns it
determines.
Move the determined columns from the original table to the new table. The
determinate becomes the primary key of the new table.
Delete the columns you just moved from the original table except for the determinate
which will serve as a foreign key.
The original table may be renamed to maintain semantic meaning.
2 NF
To transform FIRST into 2NF we move the columns s#,
status, and city to a new table called SECOND. The column
s# becomes the primary key of this new table
2 NF Anomalies
Tables in 2NF but not in 3NF still contain modification
anomalies. In the example of SECOND, they are:
INSERT. The fact that a particular city has a certain status (Rome has a status of
50) cannot be inserted until there is a supplier in the city.
DELETE. Deleting any row in SUPPLIER destroys the status information about
the city as well as the association between supplier and city.
Third Normal Form (3 NF)
3 NF
Table PARTS is already in 3NF. The non-key column, qty, is fully dependent upon
the primary key (s#, p#).
SUPPLIER is in 2NF but not in 3NF because it contains the following transitive
dependency.
s# > status
s# > city
city > status
3 NF
The process of transforming a table into 3NF is:
Identify any determinants, other the primary key, and the columns they determine.
Create and name a new table for each determinant and the unique columns it
determines.
Move the determined columns from the original table to the new table. The
determinate becomes the primary key of the new table.
Delete the columns you just moved from the original table except for the
determinate which will serve as a foreign key.
"psuedo-SQL" as:
PARTS (#s, p#, qty)
Primary Key (s#,#p)
Foreign Key (s#) references SUPPLIER_CITY.s#
SUPPLIER_CITY(s#, city)
Primary Key (s#)
Foreign Key (city) references CITY_STATUS.city
CITY_STATUS (city, status)
Primary Key (city)
Advantages of Third Normal Form
The advantage of having relational tables in 3NF is that it
eliminates redundant data which in turn saves space and
reduces manipulation anomalies. For example, the
improvements to our sample database are:
INSERT. Facts about the status of a city, Rome has a status of 50, can be added
even though there is not supplier in that city. Likewise, facts about new suppliers can be
added even though they have not yet supplied parts.
Single-Row Functions
Objectives
After completing this lesson, you should be able to do the following :
Describe various types of functions available in SQL
Use character, number and date functions in SELECT statements
Describe the use of conversion functions.
Two types of SQL Functions
Single row functions : Operate on single rows only and return
one result per row .
Different Types of Single row functions :
Character Number Date Conversion General
Multiple row functions: Manipulates groups of rows to give one result per group
of rows. Also called as group functions
Single row functions :
Manipulate data items
Accept arguments and return one value
Act on each row returned
Return one result per row
May modify the data type
Can be nested
Accept arguments which can be a column or an
expression
function_name [ (arg1, arg2, ) ]
Can be used in SELECT, WHERE, and ORDER BY
clauses
Character Functions
Case-manipulation functions
LOWER UPPER INITCAP
Character-manipulation functions
CONCAT SUBSTR LENGTH
INSTR
LPAD | RPAD TRIM
REPLACE
These functions convert case for character strings.
- LOWER : converts character strings to lowercase
- UPPER : converts character strings to uppercase
- INITCAP: converts the first letter of each word to uppercase and remaining
letters to lowercase
Example :
SELECT LOWER(SQL Course) , INITCAP(SQL Course)
FROM dual;
These functions are useful for String comparisons in WHERE clause
Example
SELECT * FROM emp WHERE ename = UPPER(scott);
These functions manipulate character strings :
CONCAT
SUBSTR
LENGTH
decimal
defaults to
Use + operator to Add or Subtract number of days to/from a date for a resultant
date value
Use operator to find the number of days between those dates.
Add hours to a date by dividing the number of hours by 24
- date + number/24 will add a number of hours to a date
Example :
SELECT ename, (SYSDATE hiredate)/7 AS WEEKS
FROM emp
WHERE deptno = 90 ;
Date Functions
Function
Description
MONTHS_BETWEEN(date1,
date2)
ADD_MONTHS(date, n)
NEXT_DAY(date, char)
LAST_DAY(date)
ROUND(date [, fmt] )
Round date
TRUNC(date [,fmt])
Truncate date
YEAR
MM
MONTH
MON
DY
DAY
DD
Minute (0-59)
SS
Second (0-59)
SSSSS
AM or PM
Meridian indicator
A.M. or P.M.
Examples
SELECT TO_CHAR(sysdate,mm) ,sysdate
FROM DUAL;
O/p : 07 28-JUL-03
SELECT TO_NUMBER(12.238)
FROM DUAL;
O/p : 12.238
SELECT TO_DATE(18-07-2003,DD-MM-YYYY)
FROM DUAL;
O/p : 18-JUL-03
RR Date Format
If the specified two-digit year is
0-49
If two
0-49 The return date is in
digits of the
current century
current year
are :
50-99 The return date is in the
century after current one
50-99
The return date is in
century before current one
The return date is in
current century
Example :
SELECT ename, hiredate FROM emp
WHERE hiredate < TO_DATE(01-JAN-60 ,DD-MON-RR);
Nesting Functions
Single row functions can be nested to any level
Nested Functions are evaluated from deepest level to the least deep level
Example :
SELECT
TO_NUMBER(TO_CHAR(SYSDATE,YYYY))+1
AS Next year
FROM dual;
O/p : 2007
General Functions
These functions work with any data type and pertain to using nulls.
NVL( expr1, expr2)
NVL2(expr1, expr2, expr3)
NULLIF(expr1, expr2)
COALESCE(expr1, expr2,..,exprn)
Note : The NVL2, NULLIF, COALESCE functions are introduced in Oracle 9i
NVL Function
Converts a null to an actual value
Data types must match
Useful for expressions having null values as with this,
null values converts to a meaningful value
Syntax :
NVL (expr1, expr2 )
If expr1 is null then expr2 is returned else expr1 is returned
Example :
CASE expression
CASE expr WHEN comparison_expr1 THEN return_expr1
[WHEN comparison_expr2 THEN return_expr2
ELSE else_expr ]
END
DECODE function
DECODE(col/expr, search1, result1
[, search2, result2,] [, default] )
Examples
SELECT CASE a WHEN b THEN hello b
WHEN a THEN hello a
ELSE hello somebody
END
FROM DUAL;
SELECT ENAME, CASE SAL WHEN 100 THEN LOW
WHEN 5000 THEN HIGH ELSE MEDIUM END FROM EMP;
SELECT DECODE(A,B,HELLO B,A,HELLO A,
HELLO X) HELLO
FROM DUAL;
SELECT JOB, SAL, DECODE(JOB,ANALYST,SAL*1.1,
CLEARK, SAL*1.15, MANAGER, SAL*1.20,SAL) Updated Sal
From Emp;
In this lesson, you should have learned how to :
Perform calculations on data using functions
Modify individual data items using functions
Manipulate output for groups of rows using functions
Alter date formats for display using functions
Convert column data types using functions
User NVL functions
Use IF-THEN-ELSE logic
Cartesian product
Equijoin
Non-equijoin
Outer join
Self join
Cross joins
Natural joins
Using Clause
Full or two sided outer joins
Arbitrary join conditions for
outer joins
Cartesian Products
Cartesian products are useful for some tests when we need to generate a large
number of rows to simulate a reasonable amount of data
Example :
SELECT last_name, department_name dept_name
FROM employees, departments;
Joining Tables
Prefix the column name with the table name when the same column name appears
in more than one table
simplify queries
Improve performance
Example :
SELECT e.employee_id, e.last_name, e.department_id,
d.department_id,d.location_id
FROM employees e, departments d
WHERE e.department_id = d.department_id
AND e.salary > 10000;
Non-Equi join
Example :
SELECT last_name, salary, grade_level
FROM employees, job_grades
WHERE salary BETWEEN 5000 AND 15000 ;
Outer Joins
Example :
SELECT worker.last_name|| works for || manager.last_name
FROM employees worker, employees manager
WHERE worker.manager_id = manager.employee_id ;
Oracle 9i feature
No matter how many common columns are available in the tables, NATURAL
JOIN will join with all the common columns
Example :
SELECT empno,ename,mgr,deptno,dname
FROM
emp
JOIN dept
USING (deptno,mgr);
ON clause
JOIN
dept d
ON (e.deptno = d.deptno)
AND d.dname =SALES ;
Left Outer Join
SELECT e.ename,e.sal,d.deptno,d.dname
FROM
emp e
LEFT OUTER JOIN
dept d
ON (e.deptno = d.deptno) ;
Right Outer Join
SELECT e.ename,e.sal,d.deptno,d.dname
FROM emp e
RIGHT OUTER JOIN
dept d
ON (e.deptno = d.deptno) ;
FULL Outer Join
SELECT e.ename, e.sal,d.deptno,d.dname
FROM emp e
FULL OUTER JOIN
dept d
ON (e.deptno = d.deptno ) ;
Summary
In this lesson, you have learned :
Group Functions
After completing this lesson, you should be able to do the following :
Identify the available group functions
Describe the use of group functions
Group data using the GROUP BY clause
Include or exclude grouped rows by using the HAVING clause
Group Functions
Group Functions operate on sets of rows to give one result per group
Syntax :
SELECT [column, ] group_function(column), .
FROM table
[WHERE
condition]
[GROUP BY column]
[HAVING
group_condition]
[ORDER BY column] ;
All group functions ignore null values. To substitute a value for null values use
NVL functions
The Oracle server implicitly sorts the result set in ascending order when using a
GROUP BY clause.
Types of Group Functions
Function
Description
AVG( [DISTINCT | ALL] n)
Average value of n
STDDEV( [DISTINCT|ALL] x)
Standard deviation of n
SUM ( [DISTINCT|ALL] n)
Sum values of n
VARIANCE( [DISTINCT|ALL]x)
Variance of n
SET Operators
The SET Operators combine the results of two or more component queries into one
result. Queries containing SET operators are called compound queries.
Operator
UNION
UNION ALL
INTERSECT
MINUS
Returns
All distinct rows selected by either query
All rows selected by either query,including
duplicates
All distinct rows selected by both queries
All distinct rows that are selected by the first
SELECT statement and not selected in the second
SELECT statement.
Example :
SELECT empno, job, deptno FROM emp
UNION ALL
SELECT employee_id, job_id, dept_id FROM
ORDER BY employee_id;
job_history
Subqueries
Objectives
After completing this lesson, you should be able to do the following :
Define subqueries
Scalar subqueries
Correlated subqueries
The ORDER BY clause in the subquery is not needed unless we are performing
Top-N analysis ( later discussed)
Syntax :
SELECT column, column, FROM table
WHERE (column, column,) IN
(SELECT column,column FROM table
WHERE condition) ;
The column comparisons can be :
- Pair wise comparisons
- Non pair wise comparisons
Multiple-Column Subqueries
Pair wise comparisons
A subquery that returns exactly one column value from one row.
Can be used in :
- condition and expression part of DECODE and CASE
- All clauses of SELECT except GROUP BY
Example :
SELECT empno, ename, (CASE WHEN deptno =
(SELECT deptno FROM dept where loc=HYDERABAD )
THEN Hyderabad ELSE Foreign END) location
FROM emp ;
Correlated Subqueries
They are executed once for every row of the outer query
Returns TRUE if subquery returns at least one row else FALSE is returned
Syntax :
UPDATE table1 alias1
SET column = ( SELECT expression FROM table2 alias2
WHERE alias1.column = alias2.column ) ;
Example :
UPDATE emp e SET deptname = (select dname
FROM dept d WHERE e.deptno = d.deptno);
Similarly Correlated Delete can be used
The WITH Clause
Introduced in Oracle 9i
Using the WITH clause, the same query block in SELECT statement can be used
more than once within a complex query
It retrieves the results of a query block and stores it in the users temporary table
space and thus improves performance
Example
Averts the usage of re-writing the same subquery multiple times in complex sub
queries
Example :
SELECT dname, SUM(sal) AS dept_total
FROM emp, dept
WHERE emp.deptno = dept.deptno GROUP BY dname
HAVING SUM(sal) > (SELECT SUM(sal) * 1/3
FROM emp, dept WHERE emp.deptno = dept.deptno)
ORDER BY SUM(sal) DESC;
Example
WITH summary
AS( SELECT dname, SUM(sal) AS dept_total
FROM emp, dept WHERE emp.deptno = dept.deptno
GROUP BY dname)
SELECT dname, dept_total
FROM summary WHERE dept_total >
( SELECT SUM(dept_total) * 1/3 FROM summary)
ORDER BY dept_total DESC;
Summary
In this lesson, you should have learned :
Manipulating Data
Objectives
After completing this lesson, you should be able to do :
Control transactions
Data Manipulation Language
Use a subquery in place of the table name in the INTO clause of the INSERT
statement.
The select list must have the same number of columns as the column list of the
VALUES clause.
Ex :
INSERT INTO ( SELECT dname, deptno FROM dept)
VALUES (ODS,100) ;
Using a Subquery in an INSERT Statement
Use WITH CHECK OPTION to prohibit insertion of rows that are not in the
subquery.
INSERT INTO ( SELECT dname, deptno, loc
FROM dept
WHERE loc = NEW YORK WITH CHECK OPTION)
VALUES ( SAP, 200, NEW YORK ) ;
If other than NEW YORK is given for loc, it will result an error
Oracle9i allows to use Default Keyword not only in DDL statements but also in
DML statements too.
DEFAULT can be used as a column value where its default value is desired
Example :
UPDATE emp
SET sal=DEFAULT
where deptno=10;
Merge Statement
Facilitates the user to conditionally update or insert values into database table
Does an Update if the row exists; else inserts a new row into database table
Syntax:
MERGE INTO table_name table_alias
USING (table|view|sub_query) alias ON (join condition)
WHEN MATCHED THEN
UPDATE SET
col1=col_val1, col2=col_val2
WHEN NOT MATCHED THEN
INSERT(column_list)
VALUES(column_values);
Merge Statement
Example :
MERGE INTO dest_tab d
USING source_tab s ON (s.no=d.no)
WHEN MATCHED THEN
UPDATE SET
d.name=s.name,
d.address=s.address
d.salary=s.salary
WHEN NOT MATCHED THEN
INSERT (d.name,d.address,d.salary)
VALUES(s.name,s.address,s.salary) ;
Transaction Control Statements
Implicit Transaction Processing
After COMMIT
- Data changes are made permanent in the database
- The previous state of the data is permanently lost
- All users can view the result
- Locks are released
-All savepoints are erased
State of the Data
After ROLLBACK
- Data changes are undone
- Previous state of the data is restored
- Locks on the affected rows are released
Statement-Level Rollback
- If a single DML statement fails during execution, only that
statement is rolled back.
- The Oracle server implements an implicit savepoint
- All other changes are retained
- The user should terminate transactions explicitly by executing
COMMIT or ROLLBACK statement
Read Consistency
Changes made by one user do not conflict with changes made by other user
The purpose of read consistency is to ensure that each user sees data as it existed
at last commit, before DML operation started.
Except the user who is doing DML operation, all others see the consistent view of
data only. They will see the changes only when the DML operations are committed .
Locking
In an Oracle database, locks :
Create tables
Describe the data types that can be used when specifying column definition
Must not duplicate the name of another object owned by the same user
Syntax :
CREATE TABLE [schema . ]table
Specify
Table name
Column name, column data type, and column size
Specify a default value for a column during an insert.
Data Types
Examples
User Tables :
- Are a collection of tables created and maintained by the user
- Contain user information
Data Dictionary
- Is a collection of tables created and maintained by Oracle Server
- Contain database information
Create a table and insert rows by combining the CREATE TABLE statement and
the select query with AS keyword
CREATE TABLE table [ ( column, column, ) ]
AS subquery ;
Modify an existing column and define a default value for the new column
ALTER TABLE table
ADD | MODIFY (column datatype [DEFAULT expr]
[,column datatype]) ;
Drop a column
ALTER TABLE table
DROP (column) ;
Examples
Adding a column
ALTER TABLE dept80
ADD (job_id varcahr2(9) );
Modifying a column
- we can change data type, size and default value
ALTER TABLE dept80
MODIFY (last_name varchar2(30) );
Dropping a column
ALTER TABLE dept80
DROP COLUMN job_id ;
The SET UNUSED Option
Use the SET UNUSED option to mark one or more columns as unused. They are
logically removed and cant be viewed or used .
Example :
- ALTER TABLE dept SET UNUSED (loc) ;
The SET UNUSED Option
Example :
- ALTER TABLE dept DROP UNUSED COLUMNS;
Dropping, Renaming, Truncating a Table
Dropping
- All data , structure in the table and indexes are dropped
Renaming
- We can change the name of a table, view, sequence
- Syntax : RENAME oldname TO newname ;
Truncating
- Removes all rows from a table
- Releases storage space used by that table
- Syntax : TRUNCATE TABLE table ;
Including Constraints
Objective
After completing this lesson, you should be able to do :
Describe constraints
Constraints enforce rules at the table level. They prevent the deletion of a table if
there are dependencies
Name a constraint or the Oracle server generates a name by using the SYS_Cn
format.
Defining Constraints
CREATE TABLE [schema .] table
(column datatype [DEFAULT expr] [column_constraint] ,
[table_constraint ] [, ] ) ;
Defining Constraints
NOT NULL
CREATE TABLE employees (
employee_id NUMBER(6) NOT NULL,
name VARCHAR2(20) CONSTRAINT emp_name_nn
NOT
NULL ) ;
UNIQUE
CREATE TABLE employees (
employee_id NUMBER(6) , name VARCAHR2(20)
CONSTRAINT emp_id_uk UNIQUE(employee_id) ) ;
PRIMARY
CREATE TABLE employees (
employee_id NUMBER(6) , name VARCAHR2(20)
FOREIGN KEY : Defines the column in the child table at the table constraint
level
ON DELETE CASCADE : Deletes the dependent rows in the child table when a
row in the parent table is deleted
Without the ON DELETE CASCADE, ON DELETE SET NULL options, the row
in the parent table cannot be deleted if it is referenced in the child table.
Examples
FOREIGN KEY
- column level
CREATE TABLE employees
( employee_id number(6) ,
department_id number(4) CONSTRAINT emp_dept_fk
references departments(dept_id),
name varchar2(20) );
- Table level
CREATE TABLE employees
( employee_id number(6), department_id number(4),
name varchar2(20), CONSTRAINT emp_dept_fk
FOREIGN
KEY(department_id)
REFERENCES departments(dept_id) );
The CHECK Constraint
Syntax :
ALTER TABLE table
DROP PRIMARY KEY | UNIQUE (column) |
CONSTRAINT constraint
[CASCADE] ;
Disabling :
- Execute the DISABLE clause of the ALTER TABLE
statement to deactivate an integrity constraint
- Apply the CASCADE option to disable dependent integrity
constraints
- Syntax :
ALTER TABLE table
DISABLE CONSTRAINT constraint [CASCADE] ;
Example :
ALTER TABLE employees
DISABLE CONSTRAINT emp_id_pk CASCADE;
Enabling Constraints
Enabling :
- Activate an integrity constraint currently disabled in the table definition by using the
ENABLE clause.
ALTER TABLE table
ENABLE CONSTRAINT constraint ;
Example :
ALTER TABLE employees
ENABLE CONSTRAINT emp_id_pk ;
Cascading Constraints
The CASCADE CONSTRAINTS clause is used along with the DROP COLUMN
clause
names
View the columns associated with the constraint names in the
USER_CONS_COLUMNS view.
Example :
SELECT constraint_name, constraint_type,
search_condition
FROM USER_CONSTRAINTS
WHERE table_name = EMP ;
Summary
In this lesson, you should have learned :
Types of constraints
- NOT NULL
- UNIQUE
- PRIMARY KEY
- FOREIGN KEY
- CHECK
You can query the USER_CONSTRAINTS table to view all constraint definitions
and names
Creating VIEWS
Objectives
What is a view ?
It contains no data of its own but is like window through which data can be
viewed or changed.
The tables from which data retrieved are called base tables.
Why use views?
Is a sharable object
Example
CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999 ;
Example :
ALTER SEQUENCE dept_deptid_seq
INCREMENT BY 20
MAXVALUE 999999
NOCACHE
NOCYCLE ;
Dropping a Sequence
is a schema object
is used by the Oracle server to speed up the retrieval of rows by using a pointer
can reduce disk I/O by using a rapid path access method to locate data quickly
One or more columns are frequently used together in a WHERE clause or a join
condition
The table is large and most queries are expected to retrieve less than 2 to 4
percent of the rows
When not to create an Index
It is usually not worth creating an Index if :
Most queries are expected to retrieve more than 2 to 4 percent of rows in the
table
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.
Example:
SELECT ic.index_name,ic.column_name,ix.uniqueness
FROM user_indexes ix, user_ind_columns ic
WHERE ic.index_name=ix.index_name
AND ic.table_name=EMPLOYEES;
Function-Based Indexes
The index expression is built from table columns, constants, SQL functions, and
user-defined functions.
CREATE INDEX upper_dept_name_idx
ON departments(UPPER(department_name));
Removing an Index
Synonyms
Summary
Create users
Create roles to ease setup and maintenance of the security model
Use the GRANT and REVOKE statements to grant and revoke object privileges
Create and access database links
Privileges
Database Security
- System Security
- Data Security
The Data Base Administrator (DBA) has high-level system privileges for tasks
such as :
Removing Tables
Backing up tables
Creating Users and User System Privileges
Once a user is created, the DBA can grant specific system privileges to a user
using GRANT clause
GRANT privileges [, privileges..]
TO user [,user/role, PUBLIC] ;
Example :
A user can have access to several roles, and several users can be assigned the
same role
The DBA creates your user account and initializes your password
You can change your password by using the ALTER USER statement
The Syntax is :
ALTER USER user
IDENTIFIED BY password;
Example :
ALTER USER scott
IDENTIFIED BY lion ;
To perform this you must have the ALTER USER privilege.
Object privileges
Object Privileges
Example :
GRANT select ON employees TO sue,rich;
GRANT update(department_name,location_id) ON departments TO scott,
manager;
Using Other GRANT options
GRANT select,insert
ON departments
TO scott
WITH GRANT OPTION;
- Allow all users on the system to query data from Alices DEPARTMENTS table
GRANT select
ON alice.departments
TO PUBLIC;
Confirming Privileges Granted
Revoking of Object Privileges
The great advantage of database links is that they allow users to access another
users objects in a remote database so that they are bounded by the privilege set of the
objects owner.
Database Links
Objective
handling errors,
usage of cursors
Agenda
Introduction to PL/SQL
PL/SQL Data Types
Control Structures
Cursors
Exception handling
It bridges the gap between the database technology and procedural programming
language
All PL/SQL programs are made up of blocks, which can be nested within each
other.
Declaration Section
Variables and constants are declared here
Executable Section
Consists of SQL and PL/SQL statements and is meant for manipulating
objects during execution
Exception Section
Errors or exceptions raised during execution are handled here
EXCEPTION (Optional)
< Error handlers >
END ; (Mandatory)
Variables
Should not be the same name as database column name Or database table name
Example :
v_age CONSTANT number(2) := 20 ;
v_name
employees.last_name % TYPE ;
DBMS_OUTPUT.PUT_LINE
Example:
SET SERVEROUTPUT ON
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE (hello world );
END ;
P-code Generation
Anonymous Blocks
Named Blocks
Operators in PL/SQL
Logical
Arithmetic
Concatenation
Exponential operator ( ** )
Note :
comparisons involving nulls always yield NULL
Note :
dept.deptno% TYPE ;
deptno
v_dept
dept
dept_name = Sales ;
Use DML statements same as in SQL in the executable and exception blocks.
Example :
BEGIN
DELETE FROM employees ;
END ;
VARIABLE name VARCHAR2(30)
DECLARE
v_no employees.employee_id % TYPE := 176;
BEGIN
SELECT last_name
INTO
: name
WHERE employee_id = v_employee_id ;
DBMS_OUTPUT.PUT_LINE(hello || : name ) ;
END ;
/
PRINT name
IF Statements
Syntax :
IF condition THEN
statements ;
[ ELSIF condition THEN
statements ; ]
[ ELSE
statements ; ]
END IF;
Set SERVEROUTPUT ON
DECLARE
sal NUMBER(9,2) := 20000 ;
BEGIN
IF( sal > 25000)
DBMS_OUTPUT.PUT_LINE(BEST);
ELSIF ( sal > 15000)
DBMS_OUTPUT.PUT_LINE( BETTER );
ELSE
DBMS_OUTPUT.PUT_LINE(Good);
END IF
END ;
CASE Expression
Basic Loops
Syntax :
LOOP
statement1 ;
DECLARE
v_counter number(2) :=1 ;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE( Number : || v_counter );
v_counter := v_counter + 1 ;
EXIT WHEN v_counter > 5 ;
END ;
WHILE Loops
Syntax :
WHILE condition LOOP
statement 1 ;
statement 2 ;
END LOOP ;
DECLARE
v_counter number(2) :=1 ;
BEGIN
WHILE v_counter < 6 LOOP
DBMS_OUTPUT.PUT_LINE( Number : || v_counter );
v_counter := v_counter + 1 ;
END LOOP ;
END ;
FOR Loops
Syntax :
FOR counter IN [REVERSE] lower_bound..upper_bound
LOOP
statement 1 ;
statement 2 ;
END LOOP ;
BEGIN
FOR v_counter IN 1..5
LOOP
DBMS_OUTPUT.PUT_LINE( Number : || v_counter );
INSERT INTO numbers VALUES (v_counter) ;
END LOOP
END ;
cursor
Implicit cursors :
- Declared for all DML and PL/SQL SELECT statements.
- User has no control over it
- PL/SQL refers most recent implicit cursor as the
SQL
cursor
Explicit cursors :
- Declared and named by the programmer
- User has control over it and names it
- Useful when more than one row is returned by the query
Explicit Cursors
Syntax :
CURSOR cursor_name IS
select_statement ;
Opening Cursors
Syntax :
OPEN cursor_name ;
OPEN dept_cursor ;
Fetching Data from the cursor
Syntax :
FETCH cursor_name INTO [variable1, variable2,] |
record_name ;
Example :
FETCH dept_cursor INTO v_no, v_name, v_location ;
Closing the cursor
Syntax :
CLOSE cursor_name ;
Note :
Before the first fetch %NOTFOUND returns NULL
DECLARE
CURSOR dept_cursor IS
SELECT * FROM dept ;
dept_record dept_cursor % ROWTYPE ;
BEGIN
OPEN dept_cursor ;
LOOP
FETCH dept_cursor INTO dept_record ;
EXIT WHEN dept_cursor % NOTFOUND ;
DBMS_OUTPUT.PUT_LINE(dept_record .dname || location : ||
dept_record.loc) ;
END LOOP ;
CLOSE dept_cursor ;
END ;
Cursor FOR Loops
Syntax :
FOR record_name IN cursor_name LOOP
statement 1 ;
statement 2 ;
END LOOP ;
Syntax :
TYPE type_name is RECORD
( field_declaration [, field_declaration] ) ;
identifier type_name ;
Where field_declaration is :
field_name { field_type | variable % TYPE |
table.column%TYPE | table %ROWTYPE}
[ [NOT NULL] { := | DEFAULT } expr ]
DECLARE
TYPE student IS RECORD
( name varchar2(25),
htnumber varchar2(25),
status varchar2(10) ) ;
candidate student ;
BEGIN
Fields in the record take their names and data types from the columns of the table
or view
Syntax :
identifier
reference % ROWTYPE ;
Advantages :
- The number of columns and data types of underlying database columns need not be
known
- The number of columns and data type may change at run time.
DECLARE
candidate students % ROWTYPE ;
BEGIN
SELECT * INTO candidate
FROM students
WHERE RegdNo = 1116097 ;
DBMS_OUTPUT.PUT_LINE(candidate.name||is||
candidate.status) ;
END ;
Handling Exceptions with PL/SQL
It is raised when
- An Oracle error occurs
- You raise it explicitly
It can be handled by
- Trapping it with a handler
- Propagating it to the calling environment
Exception Types
Trapping Exceptions
Syntax :
EXCEPTION
WHEN exception1 [ OR exception2] THEN
statement(s) ;
[WHEN exception3 [OR exception4] THEN
statement(s) ;
]
[WHEN OTHERS THEN
statement(s) ;
]
Trapping Predefined Oracle Server Errors
Steps :
Declare
Declarative section
Associate
Declarative section
Reference
Exception-handling section
x:='welcome';
dbms_output.put_line('x='||x);
EXCEPTION
when num_val then
dbms_output.put_line('my exception');
END ;
Functions for Trapping Exceptions
When an exception occurs, identify the associated error code and message by
using two functions :
- SQLCODE : Returns the numeric value for the error code
- SQLERRM : Returns character data containing the message associated with the error
number
- Useful to know the error code and message in OTHERS exception block
DECLARE
e_invalid_deptno
EXCEPTION ;
BEGIN
DELETE FROM emp
WHERE deptno = (SELECT MAX(deptno)+1 FROM dept );
IF SQL%NOTFOUND THEN
RAISE e_invalid_deptno ;
EXCEPTION
Use this procedure to issue user-defined error messages from stored subprograms
Syntax :
raise_application_error( error_number, message [,
{TRUE|FALSE} ] ) ;
Returns error condition to user in a manner consistent with other Oracle server
errors
DECLARE
e_invalid_deptno
EXCEPTION ;
BEGIN
DELETE FROM emp
WHERE deptno = (SELECT MAX(deptno)+1 FROM dept );
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR(-20345,No candidate
with such department number);
END ;
Objective
At the end of the session participants will be able to appreciate the use of
Functions
Procedures
Packages
Triggers
Agenda
Functions
Stored Procedures
Packages
Triggers
Sub Programs
A subprogram :
Is a named PL/SQL block that can accept parameters and be invoked from a
calling environment
Is of two types :
- A procedure that performs an action
- A function that computes a value
BEGIN
Executable section
EXCEPTION
Exception section
END ;
Functions
(optional)
A function
Syntax :
CREATE [OR REPLACE] FUNCTION function_name
[ parameter1 [mode] datatype1, parameter2 [mode] datatype2,... ]
RETURN data type
IS | AS
PL/SQL Block ;
Creating a Function
Example :
Advantages
SQL
Extend SQL where activities are too complex, too awkward, or unavailable with
They should not contain calls to subprograms that break the previous restrictions
Removing Functions
To drop a function
DROP FUNCTION function_name ;
Example :
DROP FUNCTION square ;
All the privileges granted on a function are revoked when the function is dropped.
Required Privileges
PROCEDURE
- DROP
PROCEDURE
ANY
Syntax :
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter1 [mode1] datatype1, parameter2 [mode2]
datatype2, ) ]
IS | AS
PL/SQL Block ;
Developing Procedures
Parameter Modes
Declaring Procedures
It can be invoked as
Execute ins_emp(123, sunil , 20);
Exceptions
BEGIN
SELECT * INTO emprecord
FROM emp
WHERE empno = p_empno ;
DBMS_OUTPUT.PUT_LINE( 'hello || emprecord.ename ) ;
END ;
emp%ROWTYPE ;
BEGIN
sel_emp(p_empnumber);
DBMS_OUTPUT.PUT_LINE( 'Bye.. ' || p_empnumber );
EXCEPTION
DBMS_OUTPUT.PUT_LINE('exception occurred');
END ;
Removing Procedures
Syntax :
DROP PROCEDURE procedure_name ;
Example :
DROP PROCEDURE ins_emp ;
Procedures Vs Functions
Packages
Components of a Package
Public package constructs :
- Those that are declared in package specification and defined in the package body
- These can be referenced from any Oracle server environment
Invoke any public construct within the package from an Oracle server environment
Syntax :
CREATE [OR REPLACE] PACKAGE package_name
IS | AS
public type and item declarations
subprogram specifications
END package_name ;
All constructs declared in specification are visible to users who are granted
privileges on the package.
Example
Syntax :
Can be invoked directly from a procedure / function within the same package
Example :
SELECT operations.raise_to(12,10) FROM DUAL ;
Removing Packages
Example :
DROP PACKAGE operations ;
The package specification should contain only those constructs that you want to
be public
Place items in the declaration part of the package body when you must maintain
them throughout a session or across transactions.
Advantages of Packages
Easier application design : code and compile specification and body separately.
Better performance :
- The entire package is loaded in memory when the package is first referenced.
- There is only one copy in memory for all users.
- Database Trigger : Fires whenever a data event or system event occurs on a schema
or database
Trigger timing
- for table : before , after
- for view : instead of
BEFORE
Execute the trigger body before the triggering DML event on a table.
AFTER
Execute the trigger body after the triggering DML event on a table
INSTEAD OF
Execute the trigger body instead of the triggering statement. This is used for
views that are not otherwise modifiable.
Trigger user event
Specifies the DML statement causing the trigger to execute.
It can be
INSERT
UPDATE
DELETE
Trigger type
Specifies the execution type of trigger.
It can be :
Statement Trigger:
-executes once for the triggering event.
A view can not be modified by normal DML statements if the view query contains
set operators, group functions or joins
Syntax :
CREATE [OR REPLACE] TRIGGER trigger_name
INSTEAD OF event1 [ OR event2 OR event3]
ON view_name
[REFERENCING OLD AS old/NEW AS new]
[FOR EACH ROW]
trigger_body
TRIGGERS
Remove a trigger
DROP TRIGGER trigger_name
USER_TRIGGER
USER_ERRORS
Example :
SELECT trigger_body from USER_TRIGGERS
WHERE trigger_name = WISH_TRIG ;
Guidelines for Designing Triggers
Design triggers to :
Create, store procedures and invoke them in a trigger, if the PL/SQL code is very
lengthy.