EMP

advertisement
CH3 Part2
Displaying Data from Multiple Tables
(Join)
 Sub queries
 Creating Sequences
 Creating Views
 Dynamic SQL Queries
 Controlling User Access

Displaying Data
from Multiple Tables
(Join)
Objectives

After completing this lesson, you should be
able to do the following:
Write SELECT statements to access data from
more than one table using equality and
nonequality joins
 View data that generally does not meet a join
condition by using outer joins
 Join a table to itself

Obtaining Data from Multiple Tables
EMP
EMPNO
-----7839
7698
...
7934
DEPT
ENAME
----KING
BLAKE
... DEPTNO
... -----...
10
...
30
MILLER ...
10
DEPTNO
-----10
20
30
40
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.
DNAME
---------ACCOUNTING
RESEARCH
SALES
OPERATIONS
LOC
-------NEW YORK
DALLAS
CHICAGO
BOSTON
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.

Cartesian Product

A Cartesian product is formed when:
A join condition is omitted
 A join condition is invalid
 All rows in the first table are joined to all rows in
the second table


To avoid a Cartesian product, always include a
valid join condition in a WHERE clause.
Generating a Cartesian Product
EMP (14 rows)
EMPNO
-----7839
7698
...
7934
ENAME
----KING
BLAKE
DEPT (4 rows)
... DEPTNO
... -----...
10
...
30
MILLER ...
“Cartesian
product:
14*4=56 rows”
10
DEPTNO
-----10
20
30
40
DNAME
---------ACCOUNTING
RESEARCH
SALES
OPERATIONS
ENAME
DNAME
--------------KING
ACCOUNTING
BLAKE
ACCOUNTING
...
KING
RESEARCH
BLAKE
RESEARCH
...
56 rows selected.
LOC
-------NEW YORK
DALLAS
CHICAGO
BOSTON
Types of Joins
Equijoin Non-equijoin Outer join Self join
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.
Foreign key
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.
Primary key
LOC
-------NEW YORK
CHICAGO
NEW YORK
DALLAS
CHICAGO
CHICAGO
CHICAGO
CHICAGO
CHICAGO
DALLAS
DALLAS
Retrieving Records
with Equijoins
SQL> SELECT
2
3 FROM
4 WHERE
emp.empno,
emp.ename, emp.deptno,
dept.deptno, dept.loc
emp, dept
emp.deptno=dept.deptno;
EMPNO ENAME DEPTNO DEPTNO LOC
----- ------ ------ ------ --------7839 KING
10
10 NEW YORK
7698 BLAKE
30
30 CHICAGO
7782 CLARK
10
10 NEW YORK
7566 JONES
20
20 DALLAS
...
14 rows selected.
Qualifying Ambiguous
Column Names
Use table prefixes to qualify column names
that are in multiple tables.
 Improve performance by using table prefixes.
 Distinguish columns that have identical names
but reside in different tables by using column
aliases.

Additional Search Conditions
Using the AND Operator
EMP
EMPNO ENAME
DEPTNO
------ ------- ------7839 KING
10
7698 BLAKE
30
7782 CLARK
10
7566 JONES
20
7654 MARTIN
30
7499 ALLEN
30
7844 TURNER
30
7900 JAMES
30
7521 WARD
30
7902 FORD
20
7369 SMITH
20
...
14 rows selected.
DEPT
DEPTNO DNAME
------ --------10 ACCOUNTING
30 SALES
10 ACCOUNTING
20 RESEARCH
30 SALES
30 SALES
30 SALES
30 SALES
30 SALES
20 RESEARCH
20 RESEARCH
...
14 rows selected.
LOC
-------NEW YORK
CHICAGO
NEW YORK
DALLAS
CHICAGO
CHICAGO
CHICAGO
CHICAGO
CHICAGO
DALLAS
DALLAS
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;
Joining More Than Two Tables
CUSTOMER
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.
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”
Retrieving Records
with Non-Equijoins
SQL>
2
3
4
SELECT
FROM
WHERE
BETWEEN
e.ename, e.sal, s.grade
emp e,
salgrade s
e.sal
s.losal AND s.hisal;
ENAME
SAL
GRADE
---------- --------- --------JAMES
950
1
SMITH
800
1
ADAMS
1100
1
...
14 rows selected.
Outer Joins
EMP
ENAME
----KING
BLAKE
CLARK
JONES
...
DEPT
DEPTNO
-----10
30
10
20
DEPTNO
-----10
30
10
20
...
40
DNAME
---------ACCOUNTING
SALES
ACCOUNTING
RESEARCH
OPERATIONS
No employee in the
OPERATIONS department
Outer Joins
You use an outer join to also see rows that do
not usually meet the join condition.
 Outer join operator is the plus sign (+).

SELECT table1.column, table2.column
FROM
table1, table2
WHERE table1.column(+) = table2.column;
SELECT table1.column, table2.column
FROM
table1, table2
WHERE table1.column = table2.column(+);
Using Outer Joins
SQL>
2
3
4
SELECT
FROM
WHERE
ORDER BY
e.ename, d.deptno, d.dname
emp e,
dept d
e.deptno(+) = d.deptno
e.deptno;
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
“MGR in the WORKER table is equal to EMPNO in the
MANAGER table”
Joining a Table to Itself
SQL> SELECT worker.ename||' works for '||manager.ename
2 FROM
emp worker, emp manager
3 WHERE worker.mgr = manager.empno;
WORKER.ENAME||'WORKSFOR'||MANAG
------------------------------BLAKE works for KING
CLARK works for KING
JONES works for KING
MARTIN works for BLAKE
...
13 rows selected.
Summary
SELECT
FROM
WHERE
table1.column, table2.column
table1, table2
table1.column1 = table2.column2;
Equijoin Non-equijoin Outer join Self join
Sub queries
Objectives

After completing this lesson, you should be
able to do the following:
Describe the types of problems that
subqueries can solve
 Define subqueries
 List the types of subqueries
 Write single-row and multiple-row subqueries

Using a Subquery
to Solve a Problem

“Who has a salary greater than Jones’?”
Main Query
?
“Which employees have a salary greater
than Jones’ salary?”
Subquery
?
“What is Jones’ salary?”
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 multiple-row
subqueries.

Types of Subqueries

Single-row subquery
Main query
returns
Subquery
CLERK
• Multiple-row subquery
Main query
returns
Subquery
CLERK
MANAGER
• Multiple-column subquery
Main query
returns
Subquery
CLERK
7900
MANAGER 7698
Single-Row Subqueries
Return only one row
 Use single-row comparison operators

Operator
Meaning
=
Equal to
>
Greater than
>=
Greater than or equal to
<
Less than
<=
Less than or equal to
<>
Not equal to
Executing Single-Row
SQL> SELECT
ename,
job
Subqueries
2 FROM
emp
3 WHERE
4
5
6
7 AND
8
9
10
job =
CLERK
(SELECT
FROM
WHERE
sal >
ENAME
JOB
---------- --------MILLER
CLERK
job
emp
empno = 7369)
1100
(SELECT
FROM
WHERE
sal
emp
empno = 7876);
Using Group Functions
in a Subquery
SQL> SELECT
2 FROM
3 WHERE
4
5
ename, job, sal
emp
sal =
(SELECT
FROM
ENAME
JOB
SAL
---------- --------- --------SMITH
CLERK
800
800
MIN(sal)
emp);
HAVING Clause with Subqueries
The Oracle Server executes subqueries first.
 The Oracle Server returns results into the
HAVING clause of the main query.

SQL>
2
3
4
5
6
7
SELECT
FROM
GROUP BY
HAVING
deptno, MIN(sal)
emp
deptno
MIN(sal) >
(SELECT
FROM
WHERE
800
MIN(sal)
emp
deptno = 20);
What Is Wrong
with This Statement?
SQL> SELECT empno, ename
2 FROM
emp
3 WHERE sal =
4
(SELECT
5
FROM
6
GROUP BY
MIN(sal)
emp
deptno);
ERROR:
ORA-01427: single-row subquery returns more than
one row
no rows selected
Will This Statement Work?
SQL> SELECT ename,
2 FROM
emp
3 WHERE job =
4
5
6
no rows selected
job
(SELECT job
FROM
emp
WHERE
ename='SMYTHE');
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
Using ANY Operator
in Multiple-Row Subqueries
SQL>
2
3
4
5
6
7
SELECT
FROM
WHERE
AND
EMPNO
--------7654
7521
empno, ename, job 1300
1100
emp
800
sal < ANY
950
(SELECT
sal
FROM
emp
WHERE
job = 'CLERK')
job <> 'CLERK';
ENAME
---------MARTIN
WARD
JOB
--------SALESMAN
SALESMAN
Using ALL Operator
in Multiple-Row Subqueries
SQL> SELECT
2 FROM
3 WHERE
4
5
6
EMPNO
--------7839
7566
7902
7788
empno, ename, job
2175
emp
2916.6667
sal > ALL
(SELECT
FROM
GROUP BY
ENAME
---------KING
JONES
FORD
SCOTT
JOB
--------PRESIDENT
MANAGER
ANALYST
ANALYST
1566.6667
avg(sal)
emp
deptno);
Summary

Subqueries are useful when a query is
based on unknown values.
SELECT
FROM
WHERE
select_list
table
expr operator
(SELECT select_list
FROM
table);
Creating Sequences
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

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}];
Creating a Sequence
Create a sequence named DEPT_DEPTNO to be
used for the primary key of the
DEPT table.
 Do not use the CYCLE option.

SQL> CREATE SEQUENCE dept_deptno
2
INCREMENT BY 1
3
START WITH 91
4
MAXVALUE 100
5
NOCACHE
6
NOCYCLE;
Sequence created.
Confirming Sequences

Verify your sequence values in the
USER_SEQUENCES data dictionary table.
SQL> SELECT
2
3 FROM

sequence_name, min_value, max_value,
increment_by, last_number
user_sequences;
The LAST_NUMBER column displays the
next available sequence number.
NEXTVAL 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.

Using a Sequence

Insert a new department named
“MARKETING” in San Diego.
SQL> INSERT INTO
2 VALUES
3
1 row created.

dept(deptno, dname, loc)
(dept_deptno.NEXTVAL,
'MARKETING', 'SAN DIEGO');
View the current value for the
DEPT_DEPTNO sequence.
SQL> SELECT
2 FROM
dept_deptno.CURRVAL
dual;
Using a Sequence
Caching sequence values in memory allows faster
access to those values.
 Gaps in sequence values can occur when:

A rollback occurs
 The system crashes
 A sequence is used in another table


View the next available sequence, if it was created
with NOCACHE, by querying the
USER_SEQUENCES table.
Modifying a Sequence

Change the increment value, maximum
value, minimum value, cycle option, or
cache option.
SQL> ALTER SEQUENCE dept_deptno
2
INCREMENT BY 1
3
MAXVALUE 999999
4
NOCACHE
5
NOCYCLE;
Sequence altered.
Guidelines for Modifying
a Sequence
You must be the owner or have the ALTER
privilege for the sequence.
 Only future sequence numbers are affected.
 The sequence must be dropped and
re-created to restart the sequence at a different
number.

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.
Creating Views
What Is a View?
EMP Table
EMPNO ENAME
JOB
JOB
MGR HIREDATE
SAL
SAL COMM
COMM DEPTNO
----- ------- --------- ----- --------- ----- ----- ------DEPTNO
----7839 KING
--------PRESIDENT
--------- ---- 17-NOV-81
--------- -----5000 ----- -----10
-7698 BLAKE
MANAGER
7839
7782 CLARK
KING
10
7566 JONES
7839 01-MAY-81
2850
30
MANAGER
PRESIDENT 7839 09-JUN-81
17-NOV-81
2450
5000
10
MANAGER
2975
20
1250
1500 1400
300
30
1600
300
30
0
30
7839 02-APR-81
7782
7654 MARTIN
CLARK
MANAGER
7698
7839 28-SEP-81
09-JUN-81
EMPVU10
ViewSALESMAN
10
7499 ALLEN
SALESMAN
7698 20-FEB-81
EMPNO 7844
ENAME
JOB 7698
TURNER
MILLER SALESMAN
CLERK
7782 08-SEP-81
23-JAN-82
------ 7934
-----------------10
7900 JAMES
CLERK
7698 03-DEC-81
7839 7566
KING
PRESIDENT
7521 WARD
JONES
SALESMAN
MANAGER
7698
7839 22-FEB-81
02-APR-81
FORD
ANALYST
7566 03-DEC-81
7782 207902
CLARK
MANAGER
7369 SMITH
SCOTT
CLERK
ANALYST
7902
7566 17-DEC-80
09-DEC-82
7934 7788
MILLER
CLERK
1500
1300
950
1250
2975
3000
800
3000
30
500
30
20
20
20
7788 SCOTT
ANALYST
7566 09-DEC-82
3000
20
7876
7876 ADAMS
CLERK
CLERK
7788 12-JAN-83
1100
1100
20
20
7934 MILLER
CLERK
7782 23-JAN-82
1300
10
7369
SMITH
CLERK
7902 17-DEC-80
800
FORD
ANALYST
7566 03-DEC-81
3000
BLAKE
MANAGER
7839 01-MAY-81
2850
20
7902
20
7698
Why Use Views?
To restrict data access
 To make complex queries easy
 To allow data independence
 To present different views of the same data

Simple Views
and Complex Views
Feature
Simple Views
Complex Views
Number of tables
One
One or more
Contain functions
No
Yes
Contain groups of data
No
Yes
DML through view
Yes
Not always
Creating a View

You embed a subquery within the CREATE
VIEW statement.
CREATE [OR REPLACE] VIEW view_name
AS
subquery;
The subquery can contain complex SELECT
syntax.
 The subquery cannot contain an ORDER BY
clause.

Creating a View

SQL>
2
3
4
View
Create a view, EMPVU10, that contains details
of employees in department 10.
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
Creating a View

SQL>
2
3
4
5
View

Create a view by using column aliases in the
subquery.
CREATE VIEW
AS SELECT
FROM
WHERE
created.
salvu30
empno EMPLOYEE_NUMBER, ename NAME,
sal SALARY
emp
deptno = 30;
Select the columns from this view by the given
alias names.
Retrieving Data from a View
SQL>
2
SELECT *
FROM
salvu30;
EMPLOYEE_NUMBER
--------------7698
7654
7499
7844
7900
7521
NAME
SALARY
---------- --------BLAKE
2850
MARTIN
1250
ALLEN
1600
TURNER
1500
JAMES
950
WARD
1250
6 rows selected.
Querying a View
SQL*Plus
USER_VIEWS
SELECT *
FROM
empvu10;
7839
7782
7934
KING
PRESIDENT
CLARK MANAGER
MILLER CLERK
EMPVU10
SELECT
FROM
WHERE
empno, ename, job
emp
deptno = 10;
EMP
Modifying a View

SQL>
2
3
4
5
View

Modify the EMPVU10 view by using CREATE
OR REPLACE VIEW clause. Add an alias for
each column name.
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.
Removing a View

Remove a view without losing data because a
view is based on underlying tables in the
database.
DROP VIEW view;
SQL> DROP VIEW empvu10;
View dropped.
Dynamic SQL Queries
Objectives

After completing this lesson, you should be
able to do the following:
Produce queries that require an input variable
 Produce more readable output

Interactive Reports
...sal = ? …
… deptno = ? …
.. ename = ? ...
I want to input query
values at runtime.
User
Substitution Variables

Use SQL*Plus substitution variables to
temporarily store values.
Single ampersand (&)
 Double ampersand (&&)
 DEFINE and ACCEPT commands


Pass variable values between SQL statements.
Using the & Substitution Variable

Use a variable prefixed with an ampersand
(&) to prompt the user for a value.
SQL> SELECT
2 FROM
3 WHERE
empno, ename, sal, deptno
emp
empno = &employee_num;
Enter value for employee_num: 7369
EMPNO ENAME
SAL
DEPTNO
--------- ---------- --------- --------7369 SMITH
800
20
Using the SET VERIFY
 Toggling the Command
display of the text of a
command before and after SQL*Plus
replaces substitution variables with values.
SQL>
SQL>
2
3
SET VERIFY ON
SELECT empno, ename, sal, deptno
FROM
emp
WHERE
empno = &employee_num;
Enter value for employee_num: 7369
old
3: WHERE empno = &employee_num
new
3: WHERE empno = 7369
...
Character and Date Values
with Substitution Variables

Use single quotation marks for date and
character values.
SQL> SELECT ename, deptno, sal*12
2 FROM
emp
3 WHERE job='&job_title';
Enter value for job_title: ANALYST
ENAME
DEPTNO
SAL*12
---------- --------- --------SCOTT
20
36000
FORD
20
36000
Specifying Column Names,
Expressions, and Text at
Runtime
 Use substitution
variables to supplement
the following:
WHERE condition
 ORDER BY clause
 Column expression
 Table name
 Entire SELECT statement

Specifying Column Names,
Expressions, and Text at
SQL> SELECT
empno, ename, job, &column_name
Runtime
2 FROM
emp
3
4
WHERE
ORDER BY
&condition
&order_column;
Enter value for column_name: sal
Enter value for condition: sal>=3000
Enter value for order_column: ename
EMPNO
--------7902
7839
7788
ENAME
---------FORD
KING
SCOTT
JOB
SAL
--------- --------ANALYST
3000
PRESIDENT
5000
ANALYST
3000
Using the && Substitution
 Use the double-ampersand
Variable(&&) if you
want to reuse the variable value without
prompting the user each time.
SQL> SELECT
2 FROM
3 ORDER BY
empno, ename, job, &&column_name
emp
&column_name;
Enter value for column_name: deptno
EMPNO ENAME
JOB
DEPTNO
--------- ---------- --------- --------7839 KING
PRESIDENT
10
7782 CLARK
MANAGER
10
7934 MILLER
CLERK
10
...
14 rows selected.
Defining User Variables

You can predefine variables using one of two
SQL*Plus commands:
DEFINE: Create a CHAR datatype user variable
 ACCEPT: Read user input and store it in a variable


If you need to predefine a variable that
includes spaces, you must enclose the value
within single quotation marks when using the
DEFINE command.
The ACCEPT Command
Creates a customized prompt when accepting
user input
 Explicitly defines a NUMBER or DATE
datatype variable
 Hides user input for security reasons

ACCEPT variable [datatype] [FORMAT format]
[PROMPT text] [HIDE]
Using the ACCEPT Command
ACCEPT
SELECT
FROM
WHERE
/
dept PROMPT 'Provide the department name: '
*
dept
dname = UPPER('&dept')
Provide the department name: Sales
DEPTNO DNAME
LOC
--------- -------------- ------------30 SALES
CHICAGO
DEFINE and UNDEFINE
Commands
 A variable remains
defined until you either:
Use the UNDEFINE command to clear it
 Exit SQL*Plus

You can verify your changes with the DEFINE
command.
 To define variables for every session, modify your
login.sql file so that the variables are created
at startup.

Using the DEFINE Command

Create a variable to hold the department
name.
SQL> DEFINE deptname = sales
SQL> DEFINE deptname
DEFINE DEPTNAME
= "sales" (CHAR)
• Use the variable as you would any other
variable.
SQL> SELECT *
2 FROM
dept
3 WHERE dname = UPPER('&deptname');
Controlling User Access
Objectives

After completing this lesson, you should be
able to do the following:
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

Controlling User Access
Database
administrator
Username and password
privileges
Users
Privileges

Database security:
System security
 Data security

System privileges: Gain access to the database
 Object privileges: Manipulate the content of
the database objects
 Schema: Collection of objects, such as tables,
views, and sequences

System Privileges
More than 80 privileges are available.
 The DBA has high-level system privileges:

Create new users
 Remove users
 Remove tables
 Back up tables

Creating Users

The DBA creates users by using the CREATE
USER statement.
CREATE
USER user
IDENTIFIED BY
password;
SQL> CREATE
USER scott
2 IDENTIFIED BY
tiger;
User created.
User System Privileges
• Once a user is created, the DBA can grant
specific system privileges to a user.
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
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.
What Is a Role?
Users
Manager
Privileges
Allocating privileges
without a role
Allocating privileges
with a role
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.
Changing Your Password
The DBA creates your user account and initializes
your password.
 You can change your password by using the ALTER
USER statement.

SQL> ALTER USER scott
2
IDENTIFIED BY lion;
User altered.
Object Privileges
Object
Privilege
Table

ALTER
*

DELETE
*

EXECUTE

INDEX
*

INSERT
*

REFERENCES

SELECT
*
*

UPDATE
*
*

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 owner’s
object.
GRANT
ON
TO
[WITH GRANT
object_priv [(columns)]
object
{user|role|PUBLIC}
OPTION];
Granting Object Privileges

Grant query privileges on the EMP table.
SQL> GRANT
select
2 ON
emp
3 TO
sue, rich;
Grant succeeded.
• Grant privileges to update specific
columns to users and roles.
SQL> GRANT
update (dname, loc)
2 ON
dept
3 TO
scott, manager;
Grant succeeded.
Using WITH GRANT
OPTION and PUBLIC
• Give a user authority to pass along the
privileges. Keywords
SQL> GRANT
select, insert
2 ON
dept
3 TO
scott
4 WITH GRANT OPTION;
Grant succeeded.

Allow all users on the system to query data
from Alice’s DEPT table.
SQL> GRANT
select
2 ON
alice.dept
3 TO
PUBLIC;
Grant succeeded.
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
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];
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.
Summary

Statement
Action

CREATE USER Allows the DBA to create a user

GRANT

CREATE ROLE Allows the DBA to create a collection
of privileges

ALTER USER Allows users to change their
password

REVOKE
Allows the user to give other users
privileges to access the user’s
objects
Removes privileges on an object from
users
Practice Overview
Granting other users privileges to your table
 Modifying another user’s table through the privileges
granted to you
 Creating a synonym
 Querying the data dictionary views related to
privileges

Download