Friday, November 18, 2016

45 Creating and Revoking Object Privileges


1.  What is a role?
A role is named group of related privileges that can be granted to users.
2.  What are the advantages of a role to a DBA?
It makes easier to grant/revoke/maintain privileges. A user can be given multiple roles and a role could be assigned to multiple users. So, rather than assigning multiple privileges to a user, I may prefer to assign/revoke a role and I am good to go.
It also means, a user having multiple roles get all the privileges in all assigned roles.

3.  Give the ability to another user in your class to look at one of your tables. Give him the right to let other students have that ability.
GRANT SELECT ON hkumar.d_clients to strange_uname
WITH GRANT OPTION;
Verify: SELECT * FROM user_tab_privs_made;

REVOKE  SELECT ON  hkumar.d_clients  FROM strange_uname;

SELECT * FROM user_tab_privs_made;

4.  You are the DBA. You are creating many users who require the same system privileges. What should you use to make your job easier?
I will group together the privileges in role. And grant this role to the user. If there are multiple set of privileges given based on what kind of job user does, I will create multiple roles: As in problem 5 below.
5.  What is the syntax to accomplish the following?

a.  Create a role of manager that has the privileges to select, insert, and update and delete from the employees table
CREATE ROLE manager;
GRANT SELECT, INSERT, UPDATE, DELETE ON employees TO manager;
b.  Create a role of clerk that just has the privileges of select and insert on the employees table
CREATE ROLE clerk;
GRANT SELECT, INSERT ON employees TO clerk;
c.  Grant the manager role to user scott
GRANT manager TO scott;
d.  Revoke the ability to delete from the employees table from the manager role
REVOKE DELETE ON employees FROM manager;
6.  What is the purpose of a database link?
DB link is a pointer that defines a one-way communication path from one oracle DB to another oracle db.
They allow users to access another user's objects in a remote DB, so that they are bounded by the privilege set of the object's owner. A local user gets access to remote database via DB link.  Database Links allow users to work on remote database objects without having to log into the other database.


44 Controlling User Access


1.  What are system privileges concerned with?
System privileges determine what the user can do at the DB level. They are concerned with right to perform a particular action or to perform an action on any object (tables, views, materialized views, synonyms, indexes, sequences, cache groups, replication schemes and PL/SQL functions, procedures and packages) of a particular type. Some system privileges examples:
·         CREATE SESSION (Enables a user to create a connection to the database. - bare minimum)
·         ADMIN (Enables a user to perform administrative tasks including checkpointing, backups, migration, and user creation and deletion.)
·         CACHE_MANAGER (Enables a user to perform operations related to cache groups.)
·         CREATE TABLE (Enables a user to create a table owned by that user.)
·         CREATE ANY TABLE ( To create a table in another user's schema, I must have the CREATE ANY TABLE privileges)
·         XLA (Enables a user to connect to a database as an XLA reader.)
And so on.
2.  What are object privileges concerned with?
Object privilege target specifically object level security (data security). These are concerned with right to perform a particular action on an object or to access another user's object (table, view, materialized view, index, synonyms [converted to privileges on base table referenced by synonym], sequences, cache group, replication schemes, PL/SQL function, procedure, and package). Object's owner has all privileges for that object and can't be revoked. Owner can grant object privileges for that object to other DB users. Also a user with ADMIN privilege can grant and revoke object privileges from users who do not own the object under consideration. Examples:
·         ALTER, DELETE, INDEX, INSERT, REFRENCEs, SELECT, UPDATE table;
·         DELETE, INDEX, INSERT,  SELECT, UPDATE view;
·         ALTER (excluding START WITH), SELECT sequence;
·         EXECUTE procedure;
·         FLUSH,LOAD,REFRESH, UNLOAD ON Cache group
And so on
3.  What is another name for object security?
Data Security
4.  What commands are necessary to allow Scott access to the database with a password of tiger?
If I get:
ORA-01031: insufficient privileges
Means I don't have sufficient permissions for that action.


CREATE USER scott IDENTIFIED BY tiger;

If I wanted to give only create session privilege to scott ( he will also get privileges given as to public):
GRANT CREATE SESSION TO  scott;

If I wanted to give something more than create session, say create table, create sequence and so on:

GRANT CREATE SESSION, CREATE TABLE, CREATE sequence, CREATE VIEW TO scott;


Another way could be just giving a role: CONNECT which has privileges like CREATE SESSION and also other system privileges, like CREATE TABLE.
GRANT CONNECT TO scott;

5.  What are the commands to allow Scott to SELECT from and UPDATE the d_clients table?
GRANT SELECT, UPDATE ON hkumar.d_clients to scott;
Opposite: REVOKE SELECT, UPDATE ON  d_clients FROM scott;
Verify: SELECT * FROM user_tab_privs_made;
6.  What is the command to allow everybody the ability to view the d_songs table?
GRANT SELECT ON hkumar.d_songs to PUBLIC;
Opposite: REVOKE SELECT ON hkumar.d_songs FROM PUBLIC;
Verify: SELECT * FROM user_tab_privs_made;
7.  Query the data dictionary to view the object privileges granted to you the user.
SELECT * from user_tab_privs_recd;
DESCRIBE   user_tab_privs_recd;

8.  What privilege should a user be given to create tables?
CREATE TABLE -  Enables a user to create a table owned by that user.
CREATE ANY TABLE - Enables a user to create a table owned by any user in the database.
9.  If you create a table, how can you pass along privileges to other users just to view your table?
GRANT SELECT ON hkumar.d_songs to   scott1, scott2, scott3;
Verify: SELECT * FROM user_tab_privs_made;
10. What syntax would you use to grant another user access to your copy_employees table?
I assume all type of permissions here now (if it were on read privilege I will use SELECT instead of ALL):
GRANT ALL ON hkumar.copy_employees to   scott1, scott2, scott3;x`
Verify: SELECT * FROM user_tab_privs_made;

11. How can you find out what privileges you have been granted for columns in the tables belonging to others?

SELECT * FROM user_col_privs_recd;


DESCRIBE user_col_privs_recd;

43 Indexes and Synonyms


  • ·         Confirms the existence of indexes from the USER_INDEXES data dictionary view-Confirming Index

e.g. SELECT * FROM user_indexes  where table_name = 'EMPLOYEES';
SELECT ucm.index_name, ucm.column_name, ucm.column_position, uix.uniqueness
FROM user_indexes uix INNER JOIN user_ind_columns ucm ON uix.index_name = ucm.index_name
WHERE ucm.table_name = 'EMPLOYEES';
  • ·         Schema object that speeds up retrieval of rows-INDEX

Unique indexes guarantee that no two rows of a table have duplicate values in the key column (or columns). Non-unique indexes do not impose this restriction on the column values
  • ·         To refer to a table by another name to simplify access- CREATE PUBLIC SYNONYM

Public: creates synonym accessible to all users
  • ·         An index that you create on multiple columns in a table-Composite Index
  • ·         The Oracle Server automatically creates this index when you define a column in a table to have a PRIMARY KEY or a UNIQUE KEY constraint- Unique index
  • ·         Stores the indexed values and uses the index based on a SELECT statement to retrieve the data- function-based index

A function-based index stores indexed values and uses the index based on SELECT statement to retrieve the data. It is based on expressions. The index expression is built from table columns, constants, SQL functions and user-defined functions.
  • ·         Removes an index-DROP INDEX
  • ·         Gives alternative names to objects- Synonym



1.  What is an index and what is it used for?
Definition: These are schema objects which make retrieval of rows from table faster.
  - They are meant to be efficient way to find data in database. I may like to drop an index if, queries in application are not using some index or say it is not speeding up the queries or may be table is very small. An index provides direct and fast access to row in table. 
·         I should create an index if the table is large and most queries are expected to retrieve less than 2 to 4 percent of the rows.
·         I should create an index if one or more columns are frequently used together in a join condition.
Purpose: An index provides direct and fast access to row in table. They provide indexed path to locate data quickly, so hereby reduce necessity of heavy disk input/output operations.
Track usage of index:
Look into what indexes employees table has:
SELECT ucm.index_name, ucm.column_name, ucm.column_position, uix.uniqueness
FROM user_indexes uix INNER JOIN user_ind_columns ucm ON uix.index_name = ucm.index_name
WHERE ucm.table_name = 'EMPLOYEES';

Start monitoring an index:
ALTER INDEX emp_id_pk MONITORING USAGE;

Note down column values in V$OBJECT_USAGE:
SELECT * FROM v$object_usage WHERE index_name = 'EMP_ID_PK';

Run a statement which may be using the index:
SELECT * from employees where employee_id = 100;

Note down column values in V$OBJECT_USAGE:
SELECT * FROM v$object_usage WHERE index_name = 'EMP_ID_PK';

Stop monitoring an index:
ALTER INDEX emp_id_pk NOMONITORING USAGE;

2.  What is a ROWID, and how is it used?
Indexes use ROWID's (base 64 string representation of the row address containing block identifier, row location in the block and the database file identifier) which is the fastest way to access any particular row.


3.  When will an index be created automatically?

For primary/unique keys: Although unique index can   be created manually, but preferred should be by using unique/primary constraint in the table. So, it   means that primary key/unique key use already existing unique index but if index is not present already, it is created while applying unique/primary key constraint.
Oracle also creates index automatically for LOB storage, xmltype and materialized view.

4.  Create a nonunique index (foreign key) for the DJs on Demand column (cd_number) in the D_TRACK_LISTINGS table. Use the Oracle Application Developer SQL Workshop Data Browser to confirm that the index was created.
Creating index (non-unique):

CREATE INDEX d_tlg_cd_number_fk_i
 on d_track_listings (cd_number);

Verify by SQL statement:
SELECT ucm.index_name, ucm.column_name, ucm.column_position, uix.uniqueness
FROM user_indexes uix INNER JOIN user_ind_columns ucm ON uix.index_name = ucm.index_name
WHERE ucm.table_name = 'D_TRACK_LISTINGS' AND column_name = 'CD_NUMBER';
Verify by object browser:

Or search in object browser:


5.  Use the join statement to display the indexes and uniqueness that exist in the data dictionary for the DJs on Demand D_SONGS table.

SELECT ucm.index_name, ucm.column_name, ucm.column_position, uix.uniqueness
FROM user_indexes uix INNER JOIN user_ind_columns ucm ON uix.index_name = ucm.index_name
WHERE ucm.table_name = 'D_SONGS';

6.  Use a SELECT statement to display the index_name, table_name, and uniqueness from the data dictionary USER_INDEXES for the DJs on Demand D_EVENTS table.
SELECT index_name, table_name,uniqueness  FROM user_indexes  where table_name = 'D_EVENTS';

7.  Write a query to create a synonym called dj_tracks for the DJs on Demand d_track_listings table.
CREATE PUBLIC SYNONYM dj_tracks FOR d_track_listings;
ORA-01031: insufficient privileges

Means I don't have CREATE PUBLIC SYNONYM privilege
CREATE SYNONYM dj_tracks FOR d_track_listings;


8.  Create a function-based index for the last_name column in DJs on Demand D_PARTNERS table that makes it possible not to have to capitalize the table name for searches. Write a SELECT statement that would use this index.
Read this as last_name
What All indexes this table has right now:
SELECT ucm.index_name, ucm.column_name, ucm.column_position, uix.uniqueness
FROM user_indexes uix INNER JOIN user_ind_columns ucm ON uix.index_name = ucm.index_name
WHERE ucm.table_name = 'D_PARTNERS';

Create index:

CREATE INDEX d_ptr_last_name_idx
ON d_partners(LOWER(last_name));


Start monitoring an index:
ALTER INDEX d_ptr_last_name_idx MONITORING USAGE;

Note down column values in V$OBJECT_USAGE:
SELECT * FROM v$object_usage WHERE index_name = 'D_PTR_LAST_NAME_IDX';


Run a statement which may be using the index:
SELECT *
FROM d_partners
WHERE LOWER(last_name) = 'something';


Note down column values in V$OBJECT_USAGE:
SELECT * FROM v$object_usage WHERE index_name = 'D_PTR_LAST_NAME_IDX';


Stop monitoring an index:
ALTER INDEX d_ptr_last_name_idx NOMONITORING USAGE;



If I want case insensitive search rather than upper or lower confusion:

CREATE INDEX d_ptr_last_name2_idx
ON d_partners(NLSSORT (last_name, 'NLS_SORT=BINARY_CI'));

ALTER INDEX d_ptr_last_name2_idx MONITORING USAGE;

SELECT * FROM v$object_usage WHERE index_name = 'D_PTR_LAST_NAME2_IDX';



Just making sure, the previous index is not used in execution plan:
DROP INDEX d_ptr_last_name_idx;


SELECT *
FROM d_partners
WHERE NLSSORT (last_name, 'NLS_SORT=BINARY_CI') = NLSSORT ('pLuMb', 'NLS_SORT=BINARY_CI');



SELECT * FROM v$object_usage WHERE index_name = 'D_PTR_LAST_NAME2_IDX';


ALTER INDEX d_ptr_last_name2_idx NOMONITORING USAGE;

9.  Create a synonym for the D_TRACK_LISTINGS table. Confirm that it has been created by querying the data dictionary.
See problem 7 above for creation part too.
CREATE SYNONYM dj_tracks FOR d_track_listings;
ORA-00955: name is already used by an existing object
CREATE SYNONYM dj_tracks2 FOR d_track_listings;
Synonym created.
SELECT * FROM user_synonyms WHERE table_NAME = UPPER('d_track_listings');


10. Drop the synonym that you created in question 9.
DROP SYNONYM dj_tracks2;
Synonym dropped.
SELECT * FROM user_synonyms WHERE table_NAME = UPPER('d_track_listings');



42 Working with Sequences



  •  ·         Command that automatically generates sequential numbers- CREATE SEQUENCE (CREATE SEQUENCE some_name)
  • ·         Generates a numeric value- Sequences
  • ·         Returns the next available sequence value- NEXTVAL
  • ·         Specifies the interval between sequence numbers- INCREMENT BY (INCREMENT BY n)
  • ·         Specifies a maximum value of 10^27 for an ascending sequence and -1 for a descending sequence (default)- NOMAXVALUE
  • ·         returns the current sequence value- CURRVAL
  • ·         specifies the minimum sequence value- MINVALUE (MINVALUE n)
  • ·         specifies whether the sequence continues to generate values after reaching its maximum or minimum values- CYCLE/NOCYCLE
  • ·         specifies a minimum value of 1 for an ascending sequence and – (10^26) for a descending sequence (default)- NOMINVALUE
  • ·         specifies a maximum or default value the sequence can generate- MAXVALUE/NOMAXVALUE (MAXVALUE n | NOMAXVALUE)
  • ·         specifies the first sequence number to be generated- START WITH (START WITH n)
  • ·         specifies how many values the Server pre-allocates and keeps in memory- CACHE/NOCACHE (CACHE n | NOCACHE)


1.  Using CREATE TABLE AS subquery syntax, create a seq_d_songs table of all the columns in the DJs on Demand database table d_songs. Use the SELECT * in the subquery to make sure that you have copied all of the columns.
CREATE TABLE seq_d_songs
AS ( SELECT * FROM d_songs);
DESCRIBE seq_d_songs;
DESCRIBE d_songs;
SELECT * FROM d_songs;
SELECT * FROM seq_d_songs;

2.  Because you are using copies of the original tables, the only constraints that were carried over were the NOT NULL constraints. Create a sequence to be used with the primary-key column of the seq_d_songs table. To avoid assigning primary-key numbers to these tables that already exist, the sequence should start at 100 and have a maximum value of 1000. Have your sequence increment by 2 and have NOCACHE and NOCYCLE. Name the sequence seq_d_songs_seq.
CREATE SEQUENCE seq_d_songs_seq
INCREMENT BY 2
START WITH 100
MAXVALUE 1000
NOCYCLE
NOCACHE;

When I alter a sequence, a new increased MAXVALUE can be entered without changing the existing number order.
3.  Query the USER_SEQUENCES data dictionary to verify the seq_d_songs_seq SEQUENCE settings.
SELECT * FROM user_sequences WHERE sequence_name = UPPER('seq_d_songs_seq');


4.  Insert two rows into the seq_d_songs table. Be sure to use the sequence that you created for the ID column. Add the two songs shown in the graphic.
ID
TITLE
DURATION
ARTIST
TYPE_CODE

Surfing Summer
-
-
12

Victory Victory
5 min
-
12

INSERT INTO seq_d_songs (id,title,duration,artist,type_code)
VALUES(seq_d_songs_seq.NEXTVAL,'Surfing Summer',NULL,NULL,12);
INSERT INTO seq_d_songs (id,title,duration,artist,type_code)
VALUES(seq_d_songs_seq.NEXTVAL,'Victory Victory','5 min',NULL,12);
SELECT * FROM seq_d_songs ORDER BY id DESC;
SELECT * FROM user_sequences WHERE sequence_name = UPPER('seq_d_songs_seq');



5.  Write out the syntax for seq_d_songs_seq to view the current value for the sequence. Use the DUAL table. (Oracle Application Developer will not run this query.)
SELECT seq_d_songs_seq.CURRVAL FROM DUAL;

CURRVAL is a pseudocolumn used to refer to a sequence number that the current user has just generated by referencing NEXTVAL.
6.  What are three benefits of using SEQUENCEs?
·         May be used to generate identity column values - the unique numbers. They also avoid concurrency issues.
·         Save time and efforts of coding.
·         Same sequence may be used in multiple tables since they are generated independent of the table using it, but I will prefer to use one sequence for one purpose.
·         There is cache option available in sequences.
·         These are sharable objects and multiple users can access it.

7.  What are the advantages of caching sequence values?
Using cache option gives a slight performance advantage as the numbers are pre-allocated and stored in-memory.

8.  Name three reasons why gaps may occur in a sequence?

·         Rolling back a statement containing a sequence.
·         System crash if system caches values in-memory
·         Same sequence being used by multiple tables.

Extras:

1.  Create a table called “students”. You can decide which columns belong in that table and what datatypes these columns require. (The students may create a table with different columns; however, the important piece that must be there is the student_id column with a numeric datatype. This column length must allow the sequence to fit, e.g. a column length of 4 with a sequence that starts with 1 and goes to 10000000 will not work after student #9999 is entered.)
CREATE TABLE students(
student_id NUMBER(6) CONSTRAINT sdt_sdt_id_pk PRIMARY KEY,
fname VARCHAR2(12),
lname VARCHAR(20),
sex CHAR(1),
major VARCHAR2(24)
);

2.  Create a sequence called student_id_seq so that you can assign unique student_id numbers for all students that you add to your table.

CREATE SEQUENCE student_id_seq
INCREMENT BY 1
START WITH 1
MAXVALUE 999999
NOCYCLE
NOCACHE;

SELECT * FROM user_sequences WHERE sequence_name = UPPER('student_id_seq');

3.  Now write the code to add students to your STUDENTS table, using your sequence “database object.”
INSERT INTO students(student_id ,fname,lname ,sex ,major )
VALUES(student_id_seq.NEXTVAL,'Hemant','Kumar','M','Web');
INSERT INTO students(student_id ,fname,lname ,sex ,major )
VALUES(student_id_seq.NEXTVAL,'Hemant2','Kumar2','M','CyberSec');
SELECT * FROM user_sequences WHERE sequence_name = UPPER('student_id_seq');

SELECT * FROM students;