Presentation is loading. Please wait.

Presentation is loading. Please wait.

Oracle Database Administration

Similar presentations


Presentation on theme: "Oracle Database Administration"— Presentation transcript:

1 Oracle Database Administration
Schema objects 1

2 Schema objects The following types of schema objects exist: Tables
Indexes Views Clusters Synonyms Sequences Database links Materialized views PL/SQL objects: procedures, functions, packages, object types Java objects 2

3 Tables Tables are used to store data
Tables can be permanent and temporary Temporary tables – two types: data is only stored for a duration of a session data is only stored for a duration of a transaction Table data is stored in a data segment in a single tablespace Table can be a part of a cluster when using clusters, several tables can be stored together in a single cluster segment 3

4 Tables - examples Permanent table: Temporary table:
CREATE TABLE perm (ID NUMBER); Temporary table: CREATE GLOBAL TEMPORARY TABLE temp1 (ID NUMBER) ON COMMIT DELETE ROWS; CREATE GLOBAL TEMPORARY TABLE temp2 4

5 Tables cont. Tables can be organized: as heap – default
CREATE TABLE as_heap (ID NUMBER); as index – table data stored together with primary key data CREATE TABLE as_index (ID NUMBER PRIMARY KEY, NAME VARCHAR2(100)) ORGANIZATION INDEX; 5

6 Table columns Oracle supports the following data types:
CHAR – fixed length character data, maximum size: 2000 bytes or characters VARCHAR2 – variable length character data, maximum length: 4000 bytes or characters, size must be specified NCHAR – fixed length Unicode data NVARCHAR2 – variable length Unicode data, size must be specified (max bytes) NUMBER – number, can include precision and scale 6

7 Table columns DATE – stores date and time, time is stored with a precision up to a second TIMESTAMP – contains date and time, time is stored with a precision up to fraction of a second TIMESTAMP WITH TIME ZONE – same as TIMESTAMP, but time zone information is stored TIMESTAMP WITH LOCAL TIME ZONE – data is normalized to the database time zone, clients see data in their time zone INTERVAL DAY TO SECOND – stores time interval 7

8 Table columns RAW – raw binary data, size is up to 2000 bytes, size is required LONG RAW – deprecated, BLOB type is recommended instead ROWID, UROWID – types that store Oracle row identifiers CLOB – large character data, maximum size over 4GB BLOB – large binary data NCLOB – large character data stored as Unicode BFILE – contains locator to large binary file stored outside of the database 8

9 Table columns BINARY_FLOAT – 32 bit floating point number, occupies 5 bytes BINARY_DOUBLE – 64 bit floating point number, occupies 9 bytes 9

10 Character columns Difference between CHAR and VARCHAR2:
CREATE TABLE test ( c CHAR(10), c VARCHAR2(10)); INSERT INTO test VALUES ('text', 'text'); -- the same as: INSERT INTO test VALUES ('text ', 'text'); CHAR texts are padded with spaces to the maximum length VARCHAR2 texts are stored unchanged 10

11 Character column length
Character column length can be specified in bytes or characters: CREATE TABLE test ( c CHAR(10 CHAR), c VARCHAR2(10 CHAR), c CHAR(10 BYTE), c VARCHAR2(10 BYTE), c CHAR); -- default to 1 BYTE Difference between CHAR and BYTE is important when using UTF8 encoding 11

12 Number column Number column can include:
precision – number of significant digits scale – number of digits after decimal point (can be negative) if value exceeds precision – error if values exceeds scale – value is rounded CREATE TABLE test ( n NUMBER, -- maximum range and precision n NUMBER(10,2), n NUMBER(3)) -- same as NUMBER(3,0) 12

13 Number column Value inserted Column specification Stored as
NUMBER(4,2) error NUMBER(4,-2) 13

14 Date, timestamp Date columns use client date and time formatting, e.g.: INSERT INTO test VALUES (' ', ' :30:05'); -- converted by the client before sending to the server To use date in client independent format, use TO_DATE, TO_CHAR functions: INSERT INTO test VALUES (TO_DATE(' ', 'YYYY-MM-DD') TO_DATE(' :30:05', 'YYYY-MM-DD HH24:MI:SS') SELECT TO_CHAR(d1, 'YYYY-MM-DD'), TO_CHAR(d2, 'YYYY-MM-DD HH24:MI:SS') 14

15 Date, timestamp cont. Timestamp columns accept fractional seconds:
CREATE TABLE test (d1 DATE, d2 TIMESTAMP(6)); INSERT INTO test VALUES (SYSDATE, SYSDATE); SELECT * FROM test; :16: :16:27,000000 DELETE FROM test; INSERT INTO test values (SYSTIMESTAMP, SYSTIMESTAMP); :17: :17:35,076000 15

16 LOB columns LOB columns include:
BLOB – large binary object CLOB, NCLOB – large text objects LOBs are stored separate from the rest of the data record Each LOB column requires two additional segments (possibly in another tablespace) 16

17 Indexes Indexes are used to: Two types of indexes exist in Oracle:
enforce primary key and unique constraints help validate foreign key constraints improve performance of queries Two types of indexes exist in Oracle: B-Tree indexes (default) Bitmap indexes B-Tree indexes can be: unique non-unique 17

18 Indexes cont NULL values are ignored by an index (even unique index):
CREATE TABLE test (id NUMBER UNIQUE); INSERT INTO test VALUES (1); INSERT INTO test VALUES (1); -- error INSERT INTO test VALUES (NULL); INSERT INTO test VALUES (NULL); -- ok Composite index value is null if all columns are null: CREATE TABLE test (id1 NUMBER, id2 NUMBER, UNIQUE(id1, id2)); INSERT INTO test VALUES (1, 1); INSERT INTO test VALUES (1, 1); -- error INSERT INTO test VALUES (1, NULL); INSERT INTO test VALUES (1, NULL); -- error INSERT INTO test VALUES (NULL, NULL); INSERT INTO test VALUES (NULL, NULL); -- ok 18

19 Compound indexes Column values are combined together in the order they appear in CREATE INDEX statement Statements: CREATE INDEX IND1 ON EMP(ID, SALARY); CREATE INDEX IND2 ON EMP(SALARY,ID); create two different indexes 19

20 Views View is a SQL query definition Views are used to: View security:
simplify complex SQL statements provide additional security View security: It is possible to grant privileges for querying a view, to users that do not have privileges to view the base table(s) View storage: view is stored as text SQL definition, no data is stored 20

21 View examples CREATE TABLE test (id NUMBER UNIQUE, name VARCHAR2(256), description VARCHAR2(4000)); CREATE VIEW test_view AS SELECT id, name FROM test; GRANT SELECT ON test_view TO some_user; -- some_user can select data from view test_view, -- but cannot select data from table test CREATE VIEW test1_view AS SELECT sum(salary), dept_id FROM employees GROUP BY dept_id HAVING sum(salary) > 10000 21

22 Updating a view Some views can be updated. Updating a view causes base table to be updated Updateable view cannot contain: Set Operators (INTERSECT, MINUS, UNION, UNION ALL) DISTINCT Group Aggregate Functions (AVG, COUNT, MAX, MIN, SUM, etc.) GROUP BY Clause ORDER BY Clause CONNECT BY Clause START WITH Clause Collection Expression In A Select List Subquery In A Select List Join Query 22

23 Synonyms Synonym is an alias for a schema object Synonyms enable to:
hide the name and owner of the object move the underlying object without modifying statements that refer to synonyms Synonyms and security: synonym is just a simple alias, the privilege to access the underlying object is required (unlike with views) 23

24 Synonyms cont. Synonyms can be public and private Private synonyms:
affect only one user, exist in this user schema, e.g.: CREATE SYNONYM s1 FOR test1.table1; SELECT * FROM s1; -- you still need privilege to -- access test1.table1 Public synonyms CREATE PUBLIC SYNONYM s1 FOR test1.table1; -- any user SELECT * FROM s1; -- the user still needs privilege -- to access test1.table1 Example: USER_TABLES is a public synonym 24

25 Synonyms cont. To create synonym, user needs:
CREATE SYNONYM or CREATE ANY SYNONYM privilege CREATE PUBLIC SYNONYM To drop synonym user needs: to drop user’s own private synonym - no special privilege to drop other user’s private synonym - DROP ANY SYNONYM to drop public synonym - DROP PUBLIC SYNONYM 25

26 Sequences Sequence: Examples: generates sequential numbers
used to generate primary keys Examples: sequence with default parameters: CREATE SEQUENCE seq1; sequence with non-default parameters CREATE SEQUENCE seq2 INCREMENT BY 1 START WITH 1 NOMAXVALUE NOCYCLE CACHE 10; 26

27 Using sequences Sequences are used to generate primary keys:
It is possible to use: one sequence for one table one sequence for a group of tables or for entire application Sequence behaves like a function, e.g.: INSERT INTO test1 (date_col) VALUES (SYSDATE); -- sysdate function used CREATE SEQUENCE s1; INSERT INTO test1 (id) VALUES (s1.NEXTVAL); -- s1.NEXTVAL function used 27

28 The DUAL table Oracle has special DUAL table with one record.
Dual table is useful for getting function values: SELECT SYSDATE FROM DUAL -- SYSDATE function computed for every -- row in DUAL table. Content of DUAL table –- is ignored, only function value is -- computed SELECT s1.NEXTVAL FROM DUAL -- next sequence value returned for every -- row in DUAL table 28

29 Nextval and Currval Each sequence has two functions:
nextval - gets next value from a sequence currval - gets current sequence value (last sequence value returned for current session) To insert table row using a sequence and find out what was inserted use: INSERT INTO table1 (id) VALUES (s1.NEXTVAL); SELECT s1.CURRVAL FROM DUAL; OR SELECT s1.NEXTVAL FROM DUAL; INSERT INTO table1 (id) VALUES (<value from the previous statement>); 29

30 Remaining schema objects
Materialized views - views that cache data, used to improve performance Database links - for connections between databases, selecting data from remote databases PL/SQL objects - procedures, functions, packages, object types Java objects - starting from Oracle 8i it is possible to store Java objects as stored procedures, functions etc. 30

31 Constraints 5 types of contraints: NOT NULL UNIQUE PRIMARY KEY
FOREIGN KEY CHECK 31

32 NOT NULL constraint Disallows empty (NULL) values in a table column
Single column constraint In Oracle empty string ('') is considered NULL, empty strings cannot be inserted into columns with NOT NULL constraints 32

33 Unique constraint Disallows multiple non-NULL values in a table column or set of columns Multiple NULL values are allowed (NULLs are ignored by unique constraint check) Can be created on a single column or on a set of columns 33

34 Primary key constraint
Disallows duplicate and null values There can only be one primary key on a single table Can be created on a single column or on a set of columns 34

35 Foreign key constraint
Requires each value in a column or set of columns to match a value in related tables's UNIQUE or PRIMARY KEY. Specifies what should be done if the data in the related table is modified: default – raise exception on delete cascade – delete child records on delete set null – set column value to null 35

36 Foreign key constraint
ALTER TABLE table1 ADD CONSTRAINT FK_1 FOREIGN KEY (col1) REFERENCES table2(id) ON DELETE CASCADE; INSERT INTO table2 VALUES (1); INSERT INTO table1(id, col1) VALUES (1, 1); INSERT INTO table1(id, col1) VALUES (1, 2); -- error –- referenced record does not exist in table2 DELETE FROM table2 WHERE id = 1; -- record removed -- from table1 36

37 Check constraint Disallows values that do not satisfy the logical expression of the constraint Example: ALTER TABLE TABLE1 ADD CONSTRAINT CHK_1 CHECK (column1 IN ('A', 'B', 'C')) ALTER TABLE EVENTS_TABLE ADD CONSTRAINT CHK_2 CHECK (start_date < end_date) 37

38 Constraint names Each constraint in Oracle has a name
If name is not provided when the constraint is created, Oracle creates default: 'SYSxxxxx' Names are useful because: easier to enable, disable, modify constraints easier to find constraints in dictionary tables when exporting and importing data constraint names don’t change 38

39 Constraint names To specify constraint name create constraints like that: CREATE TABLE tab1 ( id NUMBER CONSTRAINT pk_tab1 PRIMARY KEY, col1 VARCHAR2(256) CONSTRAINT unk_tab1 UNIQUE, col2 VARCHAR2(10) CONSTRAINT chk_tab1 CHECK (col2 in ('A', 'AB', 'ABC')), CONSTRAINT chk_tab2 CHECK (length(col1) < length(col2)) ); 39

40 Deferred constraints Constraints can be:
immediate – checked at the end of each DML statement deferred – checked when the transaction is committed By default constraints are immediate – validated after each statement Session can request constraints to be deferred: SET CONSTRAINTS ALL DEFERRED Deferred mode is ended with: SET CONSTRAINTS ALL IMMEDIATE COMMIT 40

41 Deferred constraints Example:
create table table1 (id number primary key); create table table2 (id number primary key, col1 number references table1 deferrable); set constraints all deferred; insert into table2 values(1, 1); insert into table1 values(1); commit; -- ok insert into table2 values(2, 2); commit; -- error set constraints all immediate; -- error 41

42 Constraint states Constraint can be in one of the following states:
ENABLE VALIDATE (same as ENABLE) – constraint is true for all rows in the table ENABLE NOVALIDATE – checked for new or modified rows DISABLE NOVALIDATE (same as DISABLE) – constraint not checked, ignored DISABLE VALIDATE – constraint not checked, but disallows modifications to the constrained rows 42

43 Enabling, disabling constraints
alter table table2 enable novalidate primary key; Constraint that is enabled novalidate: new data is checked against the constraint old data is not checked, some values in the table can violate the constraint 43

44 Security and privileges
Two types of privileges: system privileges - privilege to perform some action, e.g. create table, drop user, alter index etc. when the database is created, user SYS is granted all system privileges object privileges - privilege to access some object in some user’s schema, e.g. insert data into table, select value from a sequence, execute procedure etc. when the object is created, no object privileges are granted. Object owner can always do any action on the object 44

45 Security and privileges
All privileges are granted using the GRANT statement: GRANT CREATE SESSION TO user1; GRANT SELECT ON table1 TO user2; GRANT SELECT ON table1 TO PUBLIC GRANT ALL ON table1 TO user2 WITH GRANT OPTION GRANT CREATE USER TO user1 WITH ADMIN OPTION Privileges are revoked using the REVOKE statement: REVOKE CREATE SESSION FROM user1; REVOKE SELECT ON table1 FROM user2; REVOKE ALL ON table1 FROM user2; 45

46 System privileges To grant or revoke system privilege:
you must have been granted that privilege with the ADMIN OPTION, or you must have GRANT ANY PRIVILEGE system privilege 46

47 System privileges Granting system privilege:
GRANT CREATE USER TO user1; CONNECT user1; CREATE USER user2 IDENTIFIED BY user2; -- ok GRANT CREATE USER TO user2; -- error CONNECT SYSTEM GRANT CREATE USER TO user1 WITH ADMIN OPTION; GRANT CREATE USER TO user2; -- ok GRANT GRANT ANY PRIVILEGE TO user2; CONNECT user2; GRANT CREATE USER TO user3 WITH ADMIN OPTION; REVOKE CREATE USER FROM user3; 47

48 ANY privileges Special ANY privileges (CREATE ANY xxx, DROP ANY xxx, ALTER ANY xxx) enable access to other user schema: CREATE ANY xxx - enables creation of objects in other user schema (e.g. CREATE ANY TABLE) DROP ANY xxx - enables dropping other user’s objects ALTER ANY xxx - enables modifying other user’s objects 48

49 Object privileges Object privilege - permission to perform action on a specific schema object Owner of the object always has all privileges to the owned object, object privileges are granted to other users Privilege can be granted with GRANT OPTION - grantee can later grant privilege to other users GRANT SELECT ON table1 TO user1, user2; GRANT SELECT ON table1 TO user3 WITH GRANT OPTION; -- user3 can select data from table1 and can -- grant SELECT privilege to other users 49

50 Revoking object privileges
Example: owner grants privilege to user1 with grant option GRANT SELECT ON table1 TO user1 WITH GRANT OPTION; user1 grants privilege to user2 GRANT SELECT ON table1 TO user2 owner revokes privilege from user1 REVOKE SELECT ON table1 FROM user1 -- privilege is also revoked from user2 50

51 Table privileges Two types of table privileges:
DML (Data Modification Language): SELECT - permission to select data from a table UPDATE - permission to update a table, can be granted on specific columns INSERT - permission to insert rows, can be granted on specific columns DELETE - permission to delete rows DDL (Data Definition Language) INDEX - permission to create index on the table ALTER - permission to alter the table REFERENCES - permission to create foreign keys, can be granted on specific columns ALL – grants all DML and DDL privileges 51

52 Privileges for creating a view
In order to create a view user needs: create view system privilege or create any view system privilege explicitly granted object privileges on all base tables not owned by the creator of the view (ability to select data from all base tables), or explicitly granted SELECT ANY TABLE system privilege to grant other users privilege on a view, base table privileges must be granted with GRANT OPTION Create view privilege is included in the Resource role 52

53 Privileges for creating a view
CREATE USER test1/test1; GRANT DBA TO test1; CREATE USER test2/test2; GRANT DBA TO test2; CONNECT test1/test1; CREATE TABLE table1 (id NUMBER); CONNECT test2/test2; SELECT * FROM test1.table1; -- ok, SELECT ANY DATA CREATE VIEW test_view AS SELECT * FROM test1.table1; -- error - insufficient privileges CONNECT TEST1/TEST1; GRANT SELECT ON table1 TO test2; CONNECT TEST2/TEST2; CREATE VIEW test_view AS SELECT * FROM TEST1.table1; -- ok, explicitly granted privilege GRANT SELECT ON test_view TO TEST3; -- test3 cannot access test_view 53

54 Sequences and procedures
Sequence privileges: SELECT - permission to select next value from a sequence ALTER - permission to modify a sequence GRANT SELECT ON s1 TO user1 WITH GRANT OPTION Procedure/function/package privilege: EXECUTE - permission to execute specific procedure GRANT EXECUTE ON proc1 TO user1 54

55 Roles Roles are used to group privileges Role can contain:
System privileges Object privileges Other roles Predefined roles in every Oracle database: CONNECT – permissions needed to connect to the database RESOURCE – permissions needed to create tables, views, sequences in user's own schema DBA – database administrator privileges 55

56 Roles Role is created using CREATE ROLE statement:
CREATE ROLE role1 Privileges are added to role using GRANT statement: GRANT CREATE USER TO role1; GRANT SELECT ON table1 TO role1; GRANT CONNECT TO role1; Role is granted using the GRANT statement: GRANT DBA TO user1; Role is revoked using the REVOKE statement: REVOKE DBA FROM user1; 56

57 Granting roles To grant or revoke a role you need:
GRANT ANY ROLE system privilege, or having the role granted with ADMIN OPTION Roles can be granted to other roles To grant privilege to a role the same privileges are required as when granting privilege to a user Default database roles: DBA, CONNECT, RESOURCE EXP_FULL_DATABASE – for exporting IMP_FULL_DATABASE – for importing SELECT_CATALOG_ROLE – privileges for reading dictionary views (DBA_ views) 57


Download ppt "Oracle Database Administration"

Similar presentations


Ads by Google