Sie sind auf Seite 1von 8

DBA An oracle server consists of an Oracle database and an Oracle server instance.

Every time a database is started, a system global area (SGA) is allocated and Oracle background processes are started. SGA is an area of memory used for database information shared by the database users. The combination of the background processes and memory buffers is called an Oracle instance. Normalization: is the process of efficiently organizing data in a database. First Normal Form (1NF): Eliminate duplicate columns from the same table. Second Normal Form (2NF): Remove subsets of data that apply to multiple rows of a table and place them in separate tables and Create relationships between these new tables through the use of foreign keys. Third Normal Form (3NF): Remove columns that are not dependent upon the primary key. Fourth Normal Form (4NF or BCNF): relation is in 4NF if it has no multi-valued dependencies. Denormalization is a technique to move from higher to lower normal forms of database modeling in order to speed up database access. Tablespace: A tablespace is a logical storage unit within an Oracle database.
CREATE TABLESPACE LMTBS DATAFILE '/u02/oracle/data/dbtest01.dbf' SIZE 50M EXTENT MANAGEMENT LOCAL / DICTIONARY UNIFORM SIZE 128K / SEGMENT SPACE MANAGEMENT AUTO; ALTER TABLESPACE LMTBS ADD DATAFILE '/u02/oracle/data/dbtest02.dbf' SIZE 1M;

System TableSpace: Created at database creation. Cannot drop or rename. Undo TableSpace: Used to rollback or undo Permanent and Temporary TableSpace: Explain Plan [Hierarchical Table (Connect by)]: Use the EXPLAIN PLAN statement to determine the execution plan Oracle Database follows to execute a specified SQL statement. This statement inserts a row describing each step of the execution plan into a specified table. EXPLAIN PLAN SET STATEMENT_ID = 'Raise in Tokyo' INTO plan_table FOR UPDATE employees SET salary = salary * 1.10 WHERE department_id = (SELECT department_id FROM departments WHERE location_id = 1200); The following SELECT statement queries the plan_table table and returns the execution plan and the cost: SELECT LPAD(' ',2*(LEVEL-1))||operation operation, options, object_name, position FROM plan_table START WITH id = 0 AND statement_id = 'Raise in Tokyo' CONNECT BY PRIOR id = parent_id AND statement_id = 'Raise in Tokyo';

By examining this plan, you can find out if Oracle is picking the right indexes and joining your tables in the most efficient manner.

SELECT employee_id, last_name, manager_id FROM emp CONNECT BY PRIOR employee_id = manager_id; Index: An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value
that appears in the indexed columns. By default, Oracle creates B-tree indexes.

Unique Index: A unique index means that two rows cannot have the same index value. Simple Index or b-tree index Bitmap Index: a bitmap index is always advisable for systems in which data is not frequently updated or columns having low distinct valuessuch as GENDER Function based index

Clustered Vs. Non Clustered index What is Transaction? If we use create and commit, is it transaction? Yes Constraints: Unique Key, Primary Key, Foreign Key, Check, Not Null DDL: CREATE, ALTER, DROP, TRUNCATE, COMMENT, RENAME DML: SELECT, INSERT, UPDATE, DELETE, MERGE, CALL, EXPLAIN PLAN, LOCK TABLE DCL: GRANT, REVOKE TCL: COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION

Redo logs are logical and physical structures that are designed to hold all the changes made to a database and are intended to aid in the recovery of a database. Encrypt PL/SQL code WRAP iname=sql_file_name oname=encrypt_file_name Trace TKPROF Advanced queuing With this functionality, message queuing operations can be performed similar to that of SQL operation from the Oracle database. The features illustrated in this Sample Application are Internet Data Access Protocol (IDAP), Message Propagation, Message Transformation and Notifications (PLSQL/Email). Send messages using DBMS_AQ package. DBMS JOB package: Oracle DBMS_JOB package is a built-in package that is used as an API/Interface to manage the Oracle job queue. The oracle job queue is the mechanism that is used to schedule the execution of various PL/SQL Blocks or Procedures at predefined intervals of time. Mutating Table: When you are updating a table using a function that is inserting a row then the table is called as mutating table. AVG, Count, Max, Min, STDDEV, Sum, Variance are Group Functions. All other functions are Single row functions. Group functions can be nested to two: Select Max(Avg(salary)) Query not executing (Hang): Temporary table space may be less or locking How to get nth Highest Salary?
SELECT MIN (SAL) FROM (SELECT SAL FROM EMP order by SAL DESC) WHERE ROWNUM<(&nth_heighest+1); Select a.sal from emp a where &n=(select count(distinct b.sal) from emp b where a.sal<=b.sal)

How do I eliminate the duplicate rows ?


SQL> delete from table_name where rowid not in (select max(rowid) from table group by duplicate_values_field_name);

An inner join (sometimes called a simple join) is a join of two or more tables that returns only those rows that satisfy the join condition.

Password Control by creating Profile FAILED_LOGIN_ATTENPTS: PASSWORD_LIFE_TIME: PASSWORD_REUSE_TIME: PASSWORD_REUSE_MAX: PASSWORD_LOCK_TIME:

Failed login attempts before the account is locked. Number of days the same password can be used for authentication. Number of days before a password can be reused. Number of password changes before the current password can be reused. Number of days an account will be locked after max failed login attempt.

PASSWORD_GRACE_TIME: Number of days after the grace period begins with warning and login allowed. PASSWORD_VERIFY_FUNCTION: Password complexity verification script. CREATE PROFILE MY_PROFILE LIMIT PASSWORD_LIFE_TIME 30; ALTER USER SCOTT PROFILE MY_PROFILE; Oracle 10g features Server Manageability Managing Automatic System Tasks using the Maintenance Window Automatic Storage Management Drop Database Statement Flashback Features Flashback Transaction Query Flashback Version Query Flashback table Flashback Drop Flash Recovery Area
SQL> show recyclebin; SQL> flashback table test1 to before drop [RENAME TO TEST1]; SQL>FLASHBACK TABLE TEST1 to timestamp TO_TIMESTAMP( '2005-09-13 08:00:00','YYYY-MMDD HH24:MI:SS'); SQL> FLASHBACK TABLE RECYCLETEST TO SCN 2202666520; (Read versioning feature) DROP TABLE test1 PURGE; to drop table permanently.

Select * from flashback_query_ex_1 as of scn xxxxxxxxx;

Table Partitioning Range, Hash, List, Range-Hash, Range-List What are PCT Free and PCT Used in Table Creation?

The PCTFREE parameter is used to set the percentage of a block to be reserved for possible updates to rows that already are contained in that block. For example, assume that you specify the following parameter within a CREATE TABLE statement:
PCTFREE 20

This indicates that 20% of each data block used for the data segment of this table will be kept free and available for possible updates to the existing rows already within each block.
The PCTUSED=40 setting means that a block must become less than 40 percent full before being re-linked on the table free list.
PCTFREE = 100 means nothing can be inserted! PCT free is used for update. When PCTFREE is set to 0, then every update on a row requires a row migration. When PCTUSED is set to 0, then after deleting all rows in the block, it will be added into FREELIST.

Water marking: Let's asume that we have filled a table with 100'0000 rows. And let's asume that we deleted 50'000 rows afterwards. In this case the high watermark will have reached the level of 100'000 and will have stayed there. This means that we have empty blocks below the high watermark now. To adjust high watermark: TRUNCATE the table ALTER TABLE emp MOVE TABLESPACE users ALTER TABLE emp ENABLE ROW MOVEMENT ALTER TABLE emp SHRINK SPACE (If not using Long datatype) Can we create the synonym of synonym? Yes Create a table in 1st schema. Grant access rights in 2nd schema for table in 1st and 2nd to 3rd to access table in 1st schema. if revoke between 1st and 2nd then what happen with the grant rights between 2nd and 3rd. Table not found error. When inserting value in table then what will be the order of checking constraints? No standard order (It will follow whatever order is mentioned in table creation) However you can disable a constraint for initial value by initially deferrable Deferred. Mirroring (Entry in 1st table and simultaneous backup in 2nd same time). Global Temp Table: The data in a global temporary table is private, such that data inserted by a session can only be accessed by that session. The session-specific rows in a global temporary table can be preserved for the whole session, or just for the current transaction. The ON COMMIT DELETE ROWS clause indicates that the data should be deleted at the end of the transaction. Autonomous Transaction: Autonomous Transactions allow you to create a new sub transaction that may commit or rollback changes independent of the parent transaction. Autonomous transactions are commonly used by error logging routines, where the error messages must be preserved, regardless of the commit/rollback status of the transaction. Parent Transaction: Insert 2 records (Do not commit ;) Child Transaction: Insert 5 records using DECLARE PRAGMA AUTONOMOUS_TRANSACTION; BEGIN Insert statement; COMMIT; END; ROLLBACK; Now it will show records of child transaction only. Inline Views: The inline view is a construct in Oracle SQL where you can place a query in the SQL FROM, clause, just as if the query was a table name.

(Subquery with alias name)


ROLLUP: By simply invoking the ROLLUP facility in the GROUP BY clause, we direct Oracle to summarize the data at levels above the columns specified, all the way to the grand total. Select decode (grouping (deptno), 0, to_char (deptno),'Total') deptno, count (*) From EMP Group by rollup (deptno); CUBE: CUBE summarizes data based on all possible combinations of the columns specified in the GROUP BY clause. Select deptno, job, count (*), grouping (deptno), grouping (job) From EMP Group by cube (deptno, job); Ref Cursor: A REF CURSOR is basically a data type. A variable created based on such a data type is generally called a cursor variable. A cursor variable can be associated with different queries at run-time. The primary

advantage of using cursor variables is their capability to pass result sets between sub programs (like stored procedures, functions, packages etc.). Let us start with a small sub-program as follows: declare type r_cursor is REF CURSOR; c_emp r_cursor; en emp.ename%type; begin open c_emp for select ename from emp; // Every cursor variable must be opened with an associated SELECT statement loop fetch c_emp into en; exit when c_emp%notfound; dbms_output.put_line(en); end loop; close c_emp; end; Procedures: A stored procedure is a program (or procedure) which is physically stored within a database. Trigger: Trigger is an event based program. (SYSTEM on Database/Schema, INSTEADOF on views, DML on tables). You can not do any commit or rollback within trigger code. Table Functions: are designed to return a set of rows through PL/SQL logic but are intended to be used as a normal table or view in a SQL statement. They are also used to pipeline information in an ETL process. Is there OUT parameter in Function? No, it uses RETURN keyword. How to check if there is any procedure associated with a table? USER_DEPENDENCIES Collections in PL/SQL: a collection variable is a variable that can store zero, one ore more elements of a specific type (either an internal data type or a user defined data types).
There are three collection types in PL/SQL:

nested tables

index-by tables also known as associative arrays varrays

Nested tables extend the functionality of index-by tables. The main difference is that nested tables can be stored in a table column while index by tables can not.

Nested table declare type varchar2_nested_table_type is table of varchar2(100); begin null; end; / create type number_nested_table_type as table of number / Varray declare type varchar2_varray_type is

varray(50) of varchar2(100); begin null; end; / create type varchar2_varray_type as varray(50) of varchar2(100) / Index-by table: Is similar to an array. Must contain a primary key of data type binary_integer and a column of scalar or record data type. PL/SQL Tables PL/SQL tables are PL/SQLs way of providing arrays. Arrays are like temporary tables in memory and thus are processed very quickly. It is important for you to realize that they are not database tables, and DML statements cannot be issued against them. This type of table is indexed by a binary integer counter (it cannot be indexed by another type of number) whose value can be referenced using the number of the index. Remember that PL/SQL tables exist in memory only, and therefore dont exist in any persistent way, disappearing after the session ends. DECLARATION There are two steps in the declaration of a PL/SQL table. First, you must define the table structure using the TYPE statement. Second, once a table type is created, you then declare the actual table. DECLARE TYPE NameType IS TABLE OF Customer.name_name%TYPE INDEX BY BINARY_INTEGER; -- Create the actual table CnameTab NameType; KnameTab NameType; BEGIN NULL; -- ... END; Where Current of

If you plan on updating or deleting records that have been referenced by a Select For Update statement, you can use the Where Current Of statement. The syntax for the Where Current Of statement is either:
UPDATE table_name SET set_clause WHERE CURRENT OF cursor_name; OR DELETE FROM table_name WHERE CURRENT OF cursor_name; The Where Current Of statement allows you to update or delete the record that was last fetched by the cursor.

Implicit cursors and Explicit Cursors

If you use an implicit cursor, Oracle performs the open, fetches, and close for you automatically; these actions are outside of your programmatic control. PL/SQL employs an implicit cursor for each UPDATE, DELETE, or INSERT statement you execute in a program. You cannot execute these statements within an explicit cursor, even if you want to. If you have a SELECT statement that returns more than one row, you must use an explicit cursor for that query and then process the rows returned one at a time.
Example Implicit Cursor

BEGIN UPDATE Customers

SET Cust_name = 'B' WHERE Cust_name LIKE 'B%'; DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT); END; Example Explicit Cursor DECLARE vr_customer Customers%ROWTYPE; BEGIN SELECT * INTO vr_customer FROM Customers WHERE Cust_no = 701; DBMS_OUTPUT.PUT_LINE (vr_customer.Cust_name has an ID of 701'); EXCEPTION WHEN no_data_found THEN RAISE_APPLICATION_ERROR (-2001,'The Customer is not in the database'); END; If you are updating records after open the cursor then it will not show you the updated records while fetching. ---------------------------------Exceptions: Implicit (Predefined and undefined) and Explicit (User defined) User defined exceptions DECLARE myexception EXCEPTION; BEGIN -----Raising Exception: BEGIN RAISE myexception; Oracle Exceptions
NO_DATA_FOUND, INVALID_CURSOR, CURSOR_ALREADY_OPEN, ZERO DIVIDE, INVALID_NUMBER

Using RAISE_APPLICATION_ERROR you can pass your message in the predefined exception output. Install the Oracle Database Server Enroll users and control user access to the database Performance tuning of the database Planning for backup and recovery strategy Global functions in package Unix

1. Command to find and delete files older than 7 days. 2.


find /your_directory -mtime +7 -exec rm -f {} \; $ find . -type f -ctime +1 -exec ls -ltr {} \; Command to find a text in all files in a directory and sub directory.

Grep -R 3. Command to check if a process a running or not.


ps -ax | grep -e processname

4. 5. 6. 7.

Command to find top 5 directory occupying most of the space. What is awk and sed used for? Command to see the continuously updated log file. How do you find the jobs running in background? FIND=`ps -elf | grep "usr_script" | grep -v grep` if [ $? -eq 0 ] then

else

echo $FIND FINDPROC=`awk {print $4}` # it reads forth column to find process id kill -9 $FINDPROC # kills process id of the usr_scirpts procsses

echo "process no found" fi 8. How to cut the first 4 characters of each line (i.e. start on the 5th char): tail -f logfile | grep org.springframework | cut -c 5Database 1. Can we use truncate/delete/commit statements in a procedure code? 2. How to find the active and inactive session in Oracle. V$SESSION 3. How to find the blocking sessions in Oracle.

Yes

You can query the dba_blockers and dba_waiters views to locate blocking sessions, but you can also get this information from v$lock and v$session. 4. What is the difference between using IN and EXIST clause.
IN is used for matching one field value with a set of values. This set of values could be literals - string, number etc. or could be result of a subquery. If, that field value is equal to at least one of the set of values, then the condition is true. But, when we come to EXISTS, this is always followed by a subquery. If the subquery returns at least one row, the condition is said to be 'met'.

5. Can you write a SQL code like select * from employee in a procedure code. 6. How to run scheduled jobs in oracle and where to check for their log files.
BEGIN DBMS_SCHEDULER.create_job ( job_name => 'dummy_job', job_type => 'PLSQL_BLOCK', job_action => 'BEGIN NULL; /* Do Nothing */ END;', start_date => SYSTIMESTAMP, repeat_interval => 'SYSTIMESTAMP + 1 /* 1 Day */'); END; Select job_name, enabled from user_scheduler_jobs; DBA_SCHEDULER_SCHEDULES - provides me with information about the schedules that are in effect in the database. DBA_SCHEDULER_PROGRAMS - shows all program objects and their attributes, while view DBA_SCHEDULER_PROGRAM_ARGS shows all program arguments for programs that have them. DBA_SCHEDULER_JOBS - shows all job objects and their attributes.

7.

What is usage of with command in SQL and when to use it.

SELECT * FROM customers WITH (BUFFERING=.T.)


8. How do you optimize a query?
Create good indexes Using optimized query using hints, rules and stored outlines.

Das könnte Ihnen auch gefallen