Вы находитесь на странице: 1из 23

SL No

Questions
Explain the difference between a hot backup and a cold backup and the benefits associated with each. A hot backup is basically taking a backup of the database while it is still up and running and it must be in archive log mode. A cold backup is taking a backup of the database while it is shut down and does not require being in archive log mode. The benefit of taking a hot backup is that the database is still available for use while the backup is occurring and you can recover the database to any point in time. The benefit of taking a cold backup is that it is typically easier to administer the backup and recovery process. In addition, since you are taking cold backups the database does not require being in archive log mode and thus there will be a slight performance gain as the database is not cutting archive logs to disk. You have just had to restore from backup and do not have any control files. How would you go about bringing up this database? I would create a text based backup control file, stipulating where on disk all the data files where and then issue the recover command with the using backup control file clause. How do you switch from an init.ora file to a spfile? Issue the create spfile from pfile command. Explain the difference between a data block, an extent and a segment. A data block is the smallest unit of logical storage for a database object. As objects grow they take chunks of additional storage that are composed of contiguous data blocks. These groupings of contiguous data blocks are called extents. All the extents that an object takes when grouped together are considered the segment of the database object. Give two examples of how you might determine the structure of the table DEPT. Use the describe command or use the dbms_metadata.get_ddl package. Where would you look for errors from the database engine? In the alert log. Compare and contrast TRUNCATE and DELETE for a table. Both the truncate and delete command have the desired outcome of getting rid of all the rows in a table. The difference between the two is that the truncate command is a DDL operation and just moves the high water mark and produces a now rollback. The delete command, on the other hand, is a DML operation, which will produce a rollback and thus take longer to complete. Give the reasoning behind using an index. Faster access to data blocks in a table. Give the two types of tables involved in producing a star schema and the type of data they hold. Fact tables and dimension tables. A fact table contains measurements while dimension tables will contain data that will help describe the fact tables. What type of index should you use on a fact table? A Bitmap index. Give two examples of referential integrity constraints. A primary key and a foreign key. A table is classified as a parent table and you want to drop and re-create it. How would

3 4

5 6 7

8 9

10 11 12

you do this without affecting the children tables? Disable the foreign key constraint to the parent, drop the table, re-create the table, enable the foreign key constraint. Explain the difference between ARCHIVELOG mode and NOARCHIVELOG mode and the benefits and disadvantages to each. ARCHIVELOG mode is a mode that you can put the database in for creating a backup of all transactions that have occurred in the database so that you can recover to any point in time. NOARCHIVELOG mode is basically the absence of ARCHIVELOG mode and has the disadvantage of not being able to recover to any point in time. NOARCHIVELOG mode does have the advantage of not having to write transactions to an archive log and thus increases the performance of the database slightly. 14 15 What command would you use to create a backup control file? Alter database backup control file to trace. Give the stages of instance startup to a usable state where normal users may access it. STARTUP NOMOUNT - Instance startup STARTUP MOUNT - The database is mounted STARTUP OPEN - The database is opened What column differentiates the V$ views to the GV$ views and how? The INST_ID column which indicates the instance in a RAC environment the information came from. How would you go about generating an EXPLAIN plan? Create a plan table with utlxplan.sql. Use the explain plan set statement_id = 'tst1' into plan_table for a SQL statement Look at the explain plan with utlxplp.sql or utlxpls.sql How would you go about increasing the buffer cache hit ratio? Use the buffer cache advisory over a given workload and then query the v$db_cache_advice table. If a change was necessary then I would use the alter system set db_cache_size command. Explain an ORA-01555 You get this error when you get a snapshot too old within rollback. It can usually be solved by increasing the undo retention or increasing the size of rollbacks. You should also look at the logic involved in the application getting the error message. Explain the difference between $ORACLE_HOME and $ORACLE_BASE. ORACLE_BASE is the root directory for oracle. ORACLE_HOME located beneath ORACLE_BASE is where the oracle products reside. How would you determine the time zone under which a database was operating? select DBTIMEZONE from dual; Explain the use of setting GLOBAL_NAMES equal to TRUE. Setting GLOBAL_NAMES dictates how you might connect to a database. This variable is either TRUE or FALSE and if it is set to TRUE it enforces database links to have the same name as the remote database to which they are linking. What command would you use to encrypt a PL/SQL application? WRAP Explain the difference between a FUNCTION, PROCEDURE and PACKAGE.

13

16

17

18

19

20

21 22

23 24

25

A function and procedure are the same in that they are intended to be a collection of PL/SQL code that carries a single task. While a procedure does not have to return any values to the calling application, a function will return a single value. A package on the other hand is a collection of functions and procedures that are grouped together based on their commonality to a business function or application. Explain the use of table functions. 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. Name three advisory statistics you can collect. Buffer Cache Advice, Segment Level Statistics, & Timed Statistics Where in the Oracle directory tree structure are audit traces placed? In unix $ORACLE_HOME/rdbms/audit, in Windows the event viewer Explain materialized views and how they are used. Materialized views are objects that are reduced sets of information that have been summarized, grouped, or aggregated from base tables. They are typically used in data warehouse or decision support systems. When a user process fails, what background process cleans up after it? PMON What background process refreshes materialized views? The Job Queue Processes. How would you determine what sessions are connected and what resources they are waiting for? Use of V$SESSION and V$SESSION_WAIT Describe what redo logs are. 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. How would you force a log switch? ALTER SYSTEM SWITCH LOGFILE; Give two methods you could use to determine what DDL changes have been made. You could use Logminer or Streams What does coalescing a tablespace do? Coalescing is only valid for dictionary-managed tablespaces and de-fragments space by combining neighboring free extents into large single extents. What is the difference between a TEMPORARY tablespace and a PERMANENT tablespace? A temporary tablespace is used for temporary objects such as sort structures while permanent tablespaces are used to store those objects meant to be used as the true objects of the database. Name a tablespace automatically created when you create a database. The SYSTEM tablespace. When creating a user, what permissions must you grant to allow them to connect to the database? Grant the CONNECT to the user.

26 27 28

29 30 31

32

33 34 35

36

37 38

39

How do you add a data file to a tablespace? ALTER TABLESPACE <tablespace_name> ADD DATAFILE <datafile_name> SIZE <size> How do you resize a data file? ALTER DATABASE DATAFILE <datafile_name> RESIZE <new_size>; What view would you use to look at the size of a data file? DBA_DATA_FILES What view would you use to determine free space in a tablespace? DBA_FREE_SPACE How would you determine who has added a row to a table? Turn on fine grain auditing for the table. How can you rebuild an index? ALTER INDEX <index_name> REBUILD; Explain what partitioning is and what its benefit is. Partitioning is a method of taking large tables and indexes and splitting them into smaller, more manageable pieces. You have just compiled a PL/SQL package but got errors, how would you view the errors? SHOW ERRORS How can you gather statistics on a table? The ANALYZE command. How can you enable a trace for a session? Use the DBMS_SESSION.SET_SQL_TRACE or Use ALTER SESSION SET SQL_TRACE = TRUE; What is the difference between the SQL*Loader and IMPORT utilities? These two Oracle utilities are used for loading data into the database. The difference is that the import utility relies on the data being produced by another Oracle utility EXPORT while the SQL*Loader utility allows data to be loaded that has been produced by other utilities from different data sources just so long as it conforms to ASCII formatted or delimited files. Name two files used for network connection to a database. TNSNAMES.ORA and SQLNET.ORA To see current user name Sql> show user; Change SQL prompt name SQL> set sqlprompt Manimara > Manimara > Manimara > Switch to DOS prompt SQL> host 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);

40 41 42 43 44 45

46

47 48

49

50 51 52

53 54

or SQL> delete duplicate_values_field_name dv from table_name ta where rowid <(select min(rowid) from table_name tb where ta.dv=tb.dv); Example. Table Emp Empno Ename 101 Scott 102 Jiyo 103 Millor 104 Jiyo 105 Smith delete ename from emp a where rowid < ( select min(rowid) from emp b where a.ename = b.ename); The output like, Empno Ename 101 Scott 102 Millor 103 Jiyo 104 Smith How do I display row number with records? To achive this use rownum pseudocolumn with query, like SQL> SQL> select rownum, ename from emp; Output: 1 Scott 2 Millor 3 Jiyo 4 Smith Display the records between two range Select rownum, empno, ename from emp where rowid in (select rowid from emp where rownum <=&upto minus select rowid from emp where rownum<&Start); Enter value for upto: 10 Enter value for Start: 7 ROWNUM EMPNO ENAME --------- --------- ---------1 7782 CLARK 2 7788 SCOTT 3 7839 KING 4 7844 TURNER I know the nvl function only allows the same data type(ie. number or char or date Nvl(comm, 0)), if commission is null then the text Not Applicable want to display, instead of blank space. How do I write the query? SQL> select nvl(to_char(comm.),'NA') from emp; Output : NVL(TO_CHAR(COMM),'NA') ----------------------NA 300

55

56

57

58

500 NA 1400 NA NA Oracle cursor : Implicit & Explicit cursors Oracle uses work areas called private SQL areas to create SQL statements. PL/SQL construct to identify each and every work are used, is called as Cursor. For SQL queries returning a single row, PL/SQL declares all implicit cursors. For queries that returning more than one row, the cursor needs to be explicitly declared. Explicit Cursor attributes There are four cursor attributes used in Oracle cursor_name%Found, cursor_name%NOTFOUND, cursor_name%ROWCOUNT, cursor_name%ISOPEN Implicit Cursor attributes Same as explicit cursor but prefixed by the word SQL SQL%Found, SQL%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPEN Tips : 1. Here SQL%ISOPEN is false, because oracle automatically closed the implicit cursor after executing SQL statements. : 2. All are Boolean attributes. Find out nth highest salary from emp table SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal); Enter value for n: 2 SAL --------3700 To view installed Oracle version information SQL> select banner from v$version; 13. Display the number value in Words SQL> select sal, (to_char(to_date(sal,'j'), 'jsp')) from emp; the output like, SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP')) --------- ----------------------------------------------------800 eight hundred 1600 one thousand six hundred 1250 one thousand two hundred fifty If you want to add some text like, Rs. Three Thousand only. SQL> select sal "Salary ", (' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.')) "Sal in Words" from emp / Salary Sal in Words ------- -----------------------------------------------------800 Rs. Eight Hundred only. 1600 Rs. One Thousand Six Hundred only. 1250 Rs. One Thousand Two Hundred Fifty only.

59

60

61

62 63

64

Display Odd/ Even number of records Odd number of records: select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp); 1 3 5 Even number of records: select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp) 2 4 6 Which date function returns number value? months_between Any three PL/SQL Exceptions? Too_many_rows, No_Data_Found, Value_Error, Zero_Error, Others What are PL/SQL Cursor Exceptions? Cursor_Already_Open, Invalid_Cursor Other way to replace query result null value with a text SQL> Set NULL N/A to reset SQL> Set NULL What are the more common pseudo-columns? SYSDATE, USER , UID, CURVAL, NEXTVAL, ROWID, ROWNUM What is the output of SIGN function? 1 for positive value, 0 for Zero, -1 for Negative value. What is the maximum number of triggers, can apply to a single table? 12 triggers. How Oracle Chooses Indexes? It is interesting to note that the fastest execution for an individual task may not always be the best choice. For example, consider the following query against a customer table: SELECT FROM WHERE AND AND AND customer_name CUSTOMER credit_rating = 'POOR' amount_due > 1000 state = 'IOWA' job_description like lower('%computer%');

65 66 67 68

69 70

71 72

Here we see a query where a full-table scan would be the most efficient processing method. Because of the complex conditions and the use of Oracle extensions in the SQL, it might be faster to perform a full-table scan. However, the fast execution of this task may be done at the expense of other tasks on the system as the buffer pool becomes flushed. In general, the type of optimizer will determine how indexes are used. As we know, the Oracle optimizer can run as either rule-based or cost-based. As a general rule, Oracle is intelligent enough to use an index if it exists, but there are exceptions to this rule. The

most notable exception is the n-way join with a complex WHERE clause. The rule-based optimizer will get confused and invoke a full-table scan on at least one of the tables, even if the appropriate foreign key indexes exist for all of the tables. The only remedy to this problem is to use the cost-based optimizer, which involves analyzing statistics for each table. We always need to remember that Oracle will only use an index when the index column is specified in its pure form. The use of the substr, upper, lower, and other functions will invalidate the index. However, we do have a few tricks to help us get around this obstacle. Consider the two equivalent SQL queries: SELECT * FROM CUSTOMER WHERE total_purchases/10 > 5000; SELECT * FROM CUSTOMER WHERE total_purchases > 5000*10; The second query, by virtue of the fact that it does not alter the index column, would be able to use an index on the total_purchases column. Using Multi-Column Indexes When an SQL request is commonly issued using multiple columns, a concatenated or multi-column index can be used to improve performance. Oracle supports the use of multi-valued indexes, but there are some important limitations. Unlike other relational databases, Oracle requires that all columns in the index be sorted in the same order, either ascending or descending. For example, if we needed to index on customer_last_name ascending, followed immediately by gross_pay descending, we would not be able to use a multi-valued index. Sometimes two columnseach with poor selectivity (i.e., the columns have few unique values)can be combined into an index that has better selectivity. For example, we could combine a status field that has three values (good, neutral, bad) with another column such as state_name (only 50 unique values), thereby creating a multi-valued index that has far better selectivity than each column would have if indexed separately. Another reason for creating concatenated indexes is to speed the execution of queries that reference all of the values in the index. For example, consider the following query: SELECT FROM ORDER BY customer_last_name, customer_status, customer_zip_code CUSTOMER customer_last_name;

73

Now, we create an index as follows: CREATE INDEX last_status_zip ON CUSTOMER (customer_last_name, customer_status, customer_zip_code) ascending; If this query were to be issued against the customer table, Oracle would never need to access any rows in the base table! Since all of the key values are contained in the index and the high-order key (customer_last_name) is in the ORDER BY clause, Oracle can scan the index, retrieving the data without ever touching the base table.

With the assistance of this feature, the savvy Oracle developer may also add columns to the end of the concatenated index so that the base table is never touched. For example, if the above query also returned the value of the customer_address column, this column could be added to the concatenated index, dramatically improving performance. In summary, the following guidelines apply when creating a concatenated index: Use a composite index whenever two or more values are used in the SQL where the clause and the operators are ANDed together. Place the columns in the WHERE clause in the same order as in the index, with data items added at the end of the index. Allocating Oracle Tables Several parameters can be used to ensure that all data stored within Oracle tables remains in an optimal configuration. Consider the following Oracle table definition: CREATE TABLE ITEM ( item_nbr item_name item_description INITIAL 50K NEXT 50K PCTFREE 10 PCTUSED 60 FREELISTS 1 NUMBER, VARCHAR(30), VARCHAR(50) )

74

STORAGE

);

75

PCTFREE tells Oracle how much space to reserve in each Oracle block for future updates and can have an important impact on the performance of an Oracle database if it is set too low. For example, if a row contains a lot of VARCHAR data types and the rows are initially inserted without values, later updates of values into the VARCHAR fields will cause the row to expand on the block. If the target block does not have enough room, Oracle must fragment the row and store some row information on the next physical block in the tablespace. If this block is also full, Oracle may create a very long chain until it finds a block with enough room to store the new column data. This condition can lead to many unnecessary I/Os when the row is retrieved, since many database blocks must be read to retrieve the row. The rule here is simple: Determine the average row length and predicted growth for each row, then use PCTFREE to reserve that amount of space on each block. For static read-only tables, it is acceptable to set PCTFREE to a very small number in order to fully occupy each database block. Again, the PCTFREE parameter is only useful for the SQL UPDATE statementand only when the UPDATE will cause the row to grow in size. If this is not the case, then PCTFREE should be set to 5, reserving only 5 percent of each database block for updates. What options do I have when shutting down a database? Shutdown Options Administration Tips Databases can be shutdown with one of the following commands: shutdown normal shutdown transactional (Oracle 7.3 and above only) shutdown immediate shutdown abort In Oracle 7 or 8.0, these commands must be issued within the Server Manager utility, because shutting down a database is a Privileged Action, and Privileged Actions can only be performed in Server Manager. In 8i, SQL Plus acquired the ability to perform

Privileged Actions, so you can use that tool instead. Of course, to perform a Privileged Action, you have to be a Privileged User. That means you must connect as SYS, with the SYSDBA privilege. If you are using O/S authentication, then "connect / as sysdba" will do the trick. If you are using a password file, then it will have to be "connect sys/<whatever the password is> as sysdba". Lots of Oracle 7 Users have got into the habit of doing "connect Internal". Well, get out of the habit quickly! It works for Oracle 7, 8 and 8i. But it stops working in Oracle 9i. If you've any sense, you'll start using the 'as sysdba' technique early, so that scripts etc. don't break when you finally make that move to 9i. Shutdown Normal is terribly polite: it ring-fences the database (so no new connections are allowed). But anybody already connected is left alone to do whatever they like. They can stay in there for days, or weeks -all the while preventing the thing from actually shutting down. When everyone *does* finally remember to log themselves out, then Oracle flushes the entire Buffer Cache, issues a checkpoint, and shuts down the database gracefully. No data whatsoever is lost. Shutdown Transactional is a bit more forceful. Again, the database is ring-fenced. But any existing Users are only allowed to finish their *current* transaction (that is, issue a rollback or commit command). Once they do that, they are forcibly disconected, and (because of the ring-fence) they cannot re-connect. When all Users have been disconnected in this way, Oracle flushes the entire Buffer Cache, issues a checkpoint, and shuts down the database gracefully. No data whatsoever is lost. You still have trouble, though, if you have Users who forget to issue a rollback or commit command. Shutdown Immediate starts getting a bit rude. As ever, the database is ring-fenced from new connections. But existing Users are simply booted off the system, whatever they are doing. If they are in the middle of a transaction, tough. Their session is nevertheless terminated, and whatever updates they had managed to perform are rolled back. Obviously, if they managed to fit in a "commit", that data is safe. All uncommitted transactions are lost, however. When all uncommitted transactions are rolled back, Oracle flushes the entire Buffer Cache, issues a checkpoint, and shuts down the database gracefully. No committed data is lost. Note that the need to rollback pending transactions means that a shutdown immediate isn't always terribly immediate! I've seen one take 6 hours to complete because there were that many outstanding transactions pending at the time. Shutdown Abort is simply the nuclear option. Oracle simply dismantles the Instance. There's no nice flush of the Buffer Cache, no nice checkpoint, no time to finish whatever transaction you were in the middle of. The Instance just disappears, and your connection with it. It's the equivalent of pulling the plug on the box. Shutdown Aborts therefore take practically no time to complete (a matter of seconds). However, just as when you *do* accidentally pull the plug on the box, a subsequent startup can take a long time -because all those transactions that were pending when the Instance disappeared now have to be recovered (and rolled back). In other words, a Shutdown Abort requires a subsequent Instance Recovery -and that can take time (again, I've seen one take 3 hours to complete). Instance Recoveries mean that all committed data is recovered, but all uncommitted stuff is lost -so at the end of the day, it's functionally equivalent to a Shutdown Immediate. It just depends on whether you want the

Instance Recovery performed before the shutdown, or before the subsequent startup. There's a lot of old nonsense talked about Shutdown Abort being somehow "dangerous"; that, somehow, it renders you liable to data loss. Such talk is complete nonsense. Provided your online redo logs are OK, Oracle never loses committed data (and would be a pretty sad product if it did). Nevertheless, there is a glimmer of risk with an Abort (suppose Junior DBA accidentally deletes your current redo log afterwards?), and it is anyway considered a bit rude to be pulling the plug on your Users in such a brutal way. Most DBAs would consider a Shutdown Immediate to be acceptable, and reserve Aborts for dire emergencies. And that's probably a reasonable decision to make. 76

What are the Back ground processes in Oracle and what are they. This is one of the most frequently asked question. There are basically 9 Processes but in a general system we need to mention the first five background processes. They do the house keeping activities for the Oracle and are common in any system. The various background processes in oracle are a) Data Base Writer(DBWR) :: Data Base Writer Writes Modified blocks from Database buffer cache to Data Files. This is required since the data is not written whenever a transaction is committed. b)LogWriter(LGWR) :: LogWriter writes the redo log entries to disk. Redo Log data is generated in redo log buffer of SGA. As transaction commits and log buffer fills, LGWR writes log entries into a online redo log file. c) System Monitor(SMON) :: The System Monitor performs instance recovery at instance startup.This is useful for recovery from system failure d)Process Monitor(PMON) :: The Process Monitor performs process recovery when user Process fails. Pmon Clears and Frees resources that process were using. e) CheckPoint (CKPT) :: At Specified times, all modified database buffers in SGA are written to data files by DBWR at Checkpoints and Updating all data files and control files of database to indicate the most recent checkpoint f)Archieves(ARCH) :: The Archiver copies online redo log files to archival storage when they are busy. g) Recoveror(RECO) :: The Recoveror is used to resolve the distributed transaction in network h) Dispatcher (Dnnn) :: The Dispatcher is useful in Multi Threaded Architecture i) Lckn :: We can have upto 10 lock processes for inter instance locking in parallel sql. How many types of SQL Statements are there in Oracle There are basically 6 types of sql statements.They are a) Data Definition Language(DDL) :: The DDL statements define and maintain objects and drop objects. b) Data Manipulation Language(DML) :: The DML statements manipulate database data. c) Transaction Control Statements :: Manage change by DML d) Session Control :: Used to control the properties of current session enabling and disabling roles and changing .e.g. :: Alter statements, Set Role e) System Control Statements :: Change Properties of Oracle Instance .e.g.:: Alter System

77

78

f) Embedded SQL :: Incorporate DDL,DML and T.C.S in Programming Language. E.g.: Using the SQL Statements in languages such as 'C', Open, Fetch, execute and close What is a Transaction in Oracle? A transaction is a logical unit of work that compromises one or more SQL Statements executed by a single User. According to ANSI, a transaction begins with first executable statement and ends when it is explicitly committed or rolled back. Key Words Used in Oracle The Key words that are used in Oracle are: a) Committing: A transaction is said to be committed when the transaction makes permanent changes resulting from the SQL statements. b) Rollback: A transaction that retracts any of the changes resulting from SQL statements in Transaction. c) SavePoint :: For long transactions that contain many SQL statements, intermediate markers or savepoints are declared. Savepoints can be used to divide a transaction into smaller points. d) Rolling Forward: Process of applying redo log during recovery is called rolling forward. e) Cursor: A cursor is a handle (name or a pointer) for the memory associated with a specific statement. A cursor is basically an area allocated by Oracle for executing the SQL Statement. Oracle uses an implicit cursor statement for Single row query and Uses Explicit cursor for a multi row query. f) System Global Area (SGA): The SGA is a shared memory region allocated by the Oracle that contains Data and control information for one Oracle Instance. It consists of Database Buffer Cache and Redo log Buffer. g) Program Global Area (PGA): The PGA is a memory buffer that contains data and control information for server process. g) Database Buffer Cache: Database Buffer of SGA stores the most recently used blocks of database data. The set of database buffers in an instance is called Database Buffer Cache. h) Redo log Buffer: Redo log Buffer of SGA stores all the redo log entries. I) Redo Log Files: Redo log files are set of files that protect altered database data in memory that has not been written to Data Files. They are basically used for backup when a database crashes. j) Process: A Process is a 'thread of control' or mechanism in Operating System that executes series of steps. What are procedures, functions and Packages? Procedures and functions consist of set of PL/SQL statements that are grouped together as a unit to solve a specific problem or perform set of related tasks. Procedures do not Return values while Functions return one value Packages: Packages Provide a method of encapsulating and storing related procedures, functions, variables and other Package Contents What are Database Triggers and Stored Procedures? Database Triggers: Database Triggers are Procedures that are automatically executed as a result of insert in, update to, or delete from table. Database triggers have the values old and new to denote the old value in the table before it is deleted and the new indicated the new value that will be used. DT are useful for implementing complex business rules which cannot be

79

80

81

enforced using the integrity rules. We can have the trigger as Before trigger or After Trigger and at Statement or Row level. e.g.:: operations insert, update ,delete 3 before ,after 3*2 A total of 6 combinations At statement level(once for the trigger) or row level( for every execution ) 6 * 2 A total of 12. Thus a total of 12 combinations are there and the restriction of usage of 12 triggers has been lifted from Oracle 7.3 Onwards. Stored Procedures: Stored Procedures are Procedures that are stored in compiled form in the database. The advantage of using the stored procedures is that many users can use the same procedure in compiled and ready to use format. How many Integrity Rules are there and what are they There are Three Integrity Rules. They are as follows :: a) Entity Integrity Rule :: The Entity Integrity Rule enforces that the Primary key cannot be Null b) Foreign Key Integrity Rule :: The FKIR denotes that the relationship between the foreign key and the primary key has to be enforced. When there is data in Child Tables the Master tables cannot be deleted. c) Business Integrity Rules :: The Third Integrity rule is about the complex business processes which cannot be implemented by the above 2 rules. What are the Various Master and Detail Relation ships. The various Master and Detail Relationship are a) NonIsolated :: The Master cannot be deleted when a child is existing. b) Isolated :: The Master can be deleted when the child is existing c) Cascading :: The child gets deleted when the Master is deleted. How do u implement the If statement in the Select Statement We can implement the if statement in the select statement by using the Decode statement. e.g. select DECODE (EMP_CAT,'1','First','2','Second'Null); Here the Null is the else statement where null is done . How many types of Exceptions are there There are 2 types of exceptions. They are a) System Exceptions e.g. When no_data_found, When too_many_rows, Dup_Val_on_index, Value_Error,Others b) User Defined Exceptions e.g. My_exception exception When My_exception then What is 3rd normal form?
All items are atomic, all tables have a primary key, every row is determined by its primary key, there are no duplicate rows, every column is dependent on ONLY the primary key. No nonkey column depends on another nonkey column. What is 1st normal form? Each cell must be one and only one value, and that value must be atomic: there can be no repeating groups in a table that satisfies first normal form.

82

83

84

85

86

87

88 89

What is 2nd normal form? Every nonkey column must depend on the entire primary key. What is 4th normal form? Fourth normal form forbids independent one-to-many relationships between primary key columns and nonkey columns. What is 5th normal form? Fifth normal form breaks tables into the smallest possible pieces in order to eliminate all redundancy within a table. Tables normalized to this extent consist of little more than the primary key. What are cascading triggers? Executing one trigger may cause another trigger to also be executed. What are snapshots? Snapshots are copies of remote data, based upon queries. In their simplest form, they can be thought of as a table created by a command such as: create table t as select * from z; What Oracle package allows you to schedule one-off or recurring jobs in your database? DBMS_JOB What packages has Oracle provided for use by developers? The DBMS_ series of packages, i.e. DBMS_JOB, DBMS_OUTPUT, DBMS_UTILITY, UTL_FILE, UTL_HTTP, UTL_SMTP, UTL_TCP, DBMS_SQL, DBMS_PIPE, DBMS_TRANSACTION, DBMS_LOCK, DBMS_ALERT, DBMS_DDL. What are some methods for transferring a table from one schema to another? Export-Import, Create table as .. Select .., Copy What happens if a tablespace clause is left off a primary key constraint? This results in the index automatically generated being placed in the users' default tablespace, which is usually the same tablespace as where the table is being created which can cause performance problems. Where is most tuning done? 80-90 percent at application level, 10-20 percent at database level What is a mutating table? A mutating table is a table that is in the process of being modified by an UDPATE, DELETE or INSERT statement. For example, if your trigger contains a select statement or an update statement referencing the table it is triggering off of you will receive the error. What is a bind variable and why is it important? A bind variable is a placeholder in a query. The way the Oracle shared pool (a very important shared memory data structure) operates is predicated on developers using bind variables. How are reads and writes handled in Oracle that is different than almost every other database? Reads are not blocked by writes. Why should you care about the NLS_DATE_FORMAT? Because its' value (dd-mon-yy or dd-mon-rr) determines the results of your date arithmetic when you are dealing with years of 99 and 00..nn.

90

91 92

93 94

95 96

97 98

99

100

101

102 103

What is the purpose of the SUBSTR string function? To return a specified substring from a string. What's the difference between an equijoin and a self-join? An equijoin does an equality test between two fields in two different tables; a self join does the same thing on a copy of the same table. In a Select statement, what is the difference between a & and &&? Both pass in values at runtime, but if the && is used the user will not be bothered with a second prompt for the value. What is Oracle*Alert? Oracle*Alert is licensed as an Application but it functions as an extension of AOL in that it supplements the features of all the Applications. Oracle Alert is an end-user tool, and so individual alerts enjoy support from Oracle at the same level as, for instance, FSG reports in Oracle General Ledger. What is the TRANSLATE function? TRANSLATE is a simple function that does an orderly character-by-character substitution in a string. The format is TRANSLATE(string,if,then). Example: select TRANSLATE (7671234,234567890,'BCDEFGHIJ') from DUAL; The result would be: GFG1BCD. I have found this useful during some data migrations where special characters needed to be translated. What are PL/SQL Tables (or Arrays)? This is dependent upon your Oracle version. PL/SQL Tables have only one dimension, but after PLSQL 2.3 that dimension could be a record. Their main advantage is that when relatively small tables must be constantly consulted, if they can be put in memory via a PL/SQL table, performance can be enhanced. What's the most important 'Best Practice' guideline you follow? Ask for Help if you find yourself spending more than 30 minutes to solve a problem. I follow this advice when at a client site; when I'm at home, I act like the Duracell bunny and just keep going and going. What's another Best Practice? Make code reviews a regular part of your development process. Describe the PL/SQL Block structure. Declare Begin Exception End Describe a nested PL/SQL Block. Declare Begin Begin End; Begin End; End; What is %TYPE used for? v_min_bal sales.balance%TYPE := 10.00; - the var v_min_bal takes on the Type of sales.balance and the value of 10.00. What is %ROWTYPE used for? Similar to %TYPE but for a record, not just a field. What is an anonymous block? A stored procedure without a name. Is PL/SQL truly compiled when stored in the database or is it interpreted? PL/SQL on the server is run in much the same fashion as Java is run anywhere. PL/SQL is compiled into PCode and the PCode is interpreted at runtime.

104

105

106

107

108

109 110 111 112

113 114 115

116

What is the purpose of the PL/SQL FETCH command? The FETCH command retrieves values returned by the cursor from the active set into the local variables. What does truncating a table do? It deletes the data from the table. What else may truncating a table do? It can reset the high water mark for a table if the REUSE STORAGE clause is not used. Why is the high water mark important? The high water mark is used in association with each individual table and tells Oracle 1. where to start loading data during a SQL*Loader process 2. how far to scan a table's information when doing a full-table scan. What does the TO_NUMBER function do? It converts VARCHAR2 values to numbers. What is the default length of the CHAR column? 1. What is the purpose of a referential integrity constraint? Enforce the rule that a child foreign key must have a valid parent primary key. What is the purpose of the SQL*Plus command GET? Get the contents of a previously saved operating system file into the buffer. What is the order of the stages of the system development cycle? 1. Strategy and analysis 2. Design 3. Build and document 4. Transition 5. Production. In a SELECT statement, which character is used to pass in a value at runtime? The '&' character or the '&&' characters. What is DNS? What does it stand for and why do we care that it exists? Dynamic Name Server is what allows us to type in names instead of IP addresses to get to Web servers, use Telnet, FTO, etc. What are realms? Application security in Oracle Applications is maintained and managed by assigning responsibilities, excluding attributes, and securing attributes to users. Internet Procurement 11i uses a security realm as an additional layer for application security. A security realm is a list of objects (item source or a category) to which a user is granted access. What occurs during the production phase of the system development cycle? Perform normal routine maintenance. A database trigger is fired automatically when what is executed? a DML statement In a PL/SQL block, what needs to be followed with a semicolon? All SQL statements, all PL/SQL statements and the END clause What character do you type to execute an anonymous block?

117 118 119

120 121 122 123 124

125 126

127

128 129 130 131

132 133 134 135 136 137 138

The / character. What data type is used to store large binary objects outside the database? The BFILE data type Which variable type accepts only character strings of a specified length? CHAR Which variable type accepts any length of character up to 32767 bytes? VARCHAR2 What operator is used to assign a value to a variable that doesn't have a typical value? := What keyword is used to assign a value to a variable that has a typical value? DEFAULT How frequently are block declared variables initialized? Every time a block is executed With which symbol do you prefix a bind variable when you reference it in PL/SQL? : What are two statements that are true about the INTO clause? 1. You have to specify the same number of variables in the INTO clause as the values returned by the SELECT statement. 2. The data types of the variables specified in the INTO clause need to correspond with the values returned by the SELECT statement. What keyword is used when you populate a host variable from the SQL prompt? The VARIABLE keyword How do you end each SQL statement in a PL/SQL block? With a ; Can you have more than one transaction in a PL/SQL block? Yes What is common among these cursor attributes; SQL%FOUND, SQL%NOTFOUND, SQL %ISOPEN? They are all Boolean attributes. What does it mean when the cursor attribute SQL%FOUND returns the result TRUE? The most recent SQL statement issued affects one or more rows. What are two true statements concerning the index in a FOR loop? 1. You can't reference it outside the loop. 2. You can use an expression to reference its existing value within the loop. How do you begin defining a record type? TYPE emp_record_type IS RECORD Do PL/SQL records have a predefined data type? No. Give an example of the correct syntax to reference a row in a PL/SQL table. Dept_table(15)

139

140 141 142 143

144 145

146 147 148

149 150 151

The primary key of a PL/SQL table must be of what data type? Scalar What is the term used for the rows produced by a query? Active set Name three things that are true about explicit cursors. 1. They are manipulated through specific statements in the block's executable actions. 2. They individually process each row returned by a multi row SELECT statement. 3. They need to be declared and named before they can be used. Name two things true about cursor FOR loops. 1. They process rows in an explicit cursor. 2. They automate processing as the cursor is automatically opened and the rows fetched for each iteration in the loop, and the cursor is closed when all the rows have been processed. What are four attributes that provide status information about a cursor? 1. %ISOPEN 2. %NOTFOUND 3. %FOUND 4. %ROWCOUNT Describe at least one way explicit cursor attributes are used. You can use the explicit cursor attributes to test the success of each fetch before any further references are made to the cursor. What clause do you use to apply updates and deletes to the row currently being addressed, without having to explicitly reference the ROWID? How long does the Oracle server wait if it cannot acquire the locks on the rows it needs in a SELECT FOR UPDATE? Indefinitely Name three things about using cursors with parameters. 1. You can use parameters to pass values to a cursor when it is open. 2. Parameters are used in a query when it executes. 3. In the OPEN statement, each formal parameter in the cursor declaration must have a corresponding real parameter. Name three things true about trapping exceptions. 1. when an exception occurs, PL/SQL processes only one handler before leaving the block. 2. If you use the OTHERS clause, it should be placed last of all the exception-handling clauses. 3. Exceptions cannot appear in assignment statements or SQL statements. Describe two aspects about exceptions. 1. Once an Oracle error occurs, the associated exception is raised automatically. 2. You can raise an exception explicitly by issuing the RAISE statement within the block. What exception occurs when the conversion of a character string to a number fails? INVALID_NUMBER Name three things about user-defined exceptions. 1. When defining your own exceptions, you need to declare them in the DECLARE section of a PL/SQL block.

152

153

154

155 156

157

158

159

160 161

162

2. They are raised explicitly with RAISE statements. 3. You need to reference your declared exception within the corresponding exception-handling routine. What's another Best Practice? Set standards and guidelines for your application before anyone starts writing code. 1. Selection of development tools 2. How SQL is written in PL/SQL code. 3. How the exception handling architecture is designed. 4. Processes for code review and testing. Explain the relationship between a Conceptual Data Model (CDM) and a Physical Data Model (PDM). Most of the objects in the logical model correspond to a related object in the physical model, e.g. the logical model contains entities, attributes, and key groups, which are represented in the physical model as tables, columns, and indexes, respectively. The CDM allows the designer to concentrate solely on defining the objects in the information system and the relationships between them, without having to consider the numerous parameters associated with the physical implementation such as data integrity constraints, data access speed and data storage efficiency. The CDM thus provides a clear and succinct picture of the information system, which is independent of the targeted DBMS. A single CDM may therefore be associated with a number of PDMs targeting different DBMSs. The conceptual level schema, should present to the user a simple, physical implementation-independent clear view of the format of the data sets and their descriptions. A Conceptual Data Model lays the foundation for building shared databases and re-engineering the business. Elaborating on 163, describe conceptual vs logical vs physical designs. Conceptual database design is the process of building a model of the essential part of the enterprise business process and the used information, independent of all physical considerations. Logical database design - The process of constructing a model of information used in an enterprise based on a specific data model, using natural objects of information and natural associations between them. The model of information is independent of a particular implementation and other physical consideration. Physical database design - The process of producing a description of the implementation of the database on secondary storage. It describes the storage structures and access methods used to achieve efficient access to the data. What is a pseudo-column? A pseudo-column is a "column" that yields a value when selected, but which is not an actual column of the table. What are the more common pseudo-columns? sequence.CurrVal, sequence.NextVal, RowID, RowNum, SysDate, UID, User What is the difference between VARCHAR and VARCHAR2? The VARCHAR data type is currently synonymous with the VARCHAR2 data type. It is recommended that you use VARCHAR2 rather than VARCHAR. In a future version of Oracle, VARCHAR might be a separate data type used for variable length character strings compared with different comparison semantics. Give an example of overloaded Built-in functions. date_string := TO_CHAR (SYSDATE, 'MMDDYY'); number_string := TO_CHAR (10000); If overloading was not supported in PL/SQL (TO_CHAR is a function in the STANDARD package), then two different functions would be required to support conversions to character format. What is the difference between call and execute sqlplus commands.? The CALL statement is SQL(and only understands SQL types). EXEC is really shorthand for begin/end;. How can I check for duplicates?

163

164

165

166 167

168

169

170

171 172 173

select count(*), job from emp group by job having count(*) > 0; 4 CLERK 4 SALESMAN 3 MANAGER 2 ANALYST 1 PRESIDENT What is another name for ref cursors? cursor variables What data type column can not be used with INTERSECT? LONG When is the MINUS keyword used? To remove those rows which are retrieved by one SELECT from those retrieved by another SELECT statement. Give an example of the MINUS keyword. List the numbers of all managers who do not hold advanced degrees. SELECT MGRNO FROM DEPT WHERE MGRNO IS NOT NULL MINUS SELECT EMPNO FROM EMP WHERE EDLEVEL >= 18; When is the INTERSECT keyword used? To return only those rows that are the result of two or more SELECT statements. Give an example of the INTERSECT keyword. List the numbers of all managers who do not hold advanced degrees. SELECT MGRNO FROM DEPT WHERE MGRNO IS NOT NULL INTERSECT SELECT EMPNO FROM EMP WHERE EDLEVEL < 18; Write a query to find the duplicate record(s) of column a, b and c in a table of columns a..z. SELECT count(*), a, b, c FROM t GROUP BY a, b, c HAVING COUNT(*) > 1; Give an example of the NOT keyword. SELECT c FROM t WHERE c != 'x'; SELECT c FROM t WHERE NOT c = 'x'; Give an example of the LIKE keyword. SELECT c FROM t WHERE c LIKE '_EU%L'; ie the first character can be any character, the next two must be EU and the last must be L. Any number of chararcters or numbers could be between the U and L. What is SQLCODE? A predefined symbol that contains the Oracle error status of the previously executed PL/SQL statement. If a SQL statement executes without errors, SQLCODE is equal to 0. What is SQLERRM? A PL/SQL symbol that contains the error message associated with SQLCODE. If a SQL statement executes successfully, SQLCODE is equal to 0 and SQLERRM contains the string ORA-0000: normal, successful completion What is ROWNUM? A pseudocolumn that indicates the order of the retrieved row. The ROWNUM for the first returned row is 1, ROWNUM can limit the number of rows that are returned by a query. What are the benefits of using the PLS_INTEGER Datatype in PL/SQL? If you have a whole-number counter, for example in a loop or record counter, consider using a datatype of PLS_INTEGER instead of INTEGER or NUMBER. When declaring an integer variable, PLS_INTEGER is the most efficient numeric datatype because its values require less storage than INTEGER or NUMBER values, which are represented

174

175 176

177

178 179

180

181

182

183

184

internally as 22-byte Oracle numbers. Also, PLS_INTEGER operations use machine arithmetic, so they are faster than BINARY_INTEGER, INTEGER, or NUMBER operations, which use library arithmetic. Jayanta Sengupta Lowell, Massachusetts Explain the difference between NVL and NVL2. NVL(expr1,expr2); NVL2(expr1,expr2,expr3); NVL - If expr1 is null then return expr2 else return expr1. NVL2 - If expr1 is not null then the function will return expr2. Otherwise, the function will return expr3. The expr1 can have any datatype and arguments expr2 and expr3 can be of any datatype other than LONG. The datatype of the return value is that of expr2. Describe RTRIM. RTRIM(string [,'set']) RTRIM is the opposite of RPAD and similar to LTRIM. The function removes characters from the right-hand portion of a string. The string passed as the first parameter is returned with all characters contained in the string passed as the second parameter removed from the right of the last character not found in the remove string. The second parameter is optional and defaults to a single space. rtrim('ORACLE UPDATE ') --> 'ORACLE UPDATE' rtrim('ORACLE UPDATE','EDATPU') --> 'ORACLE ' rtrim('ORACLE UPDATE',' EDATPU') --> 'ORACL' Describe UNION and UNION ALL. UNION returns distinct rows selected by both queries while UNION ALL returns all the rows. Therefore, if the table has duplicates, UNION will remove them. If the table has no duplicates, UNION will force a sort and cause performance degradation as compared to UNION ALL. What does pragma mean to Oracle? A pragma is simply a compiler directive, a method to instruct the compiler to perform some compilation option. What is a Latch? A Latch is a low level serialization mechanism that (released as quickly as it is acquired) protects shared data structures. A process acquires and holds the latch as long as the data structure is in use. The basic idea is to prevent concurrent access to shared data structures in the SGA. In case the process dies without releasing the latch, the PMON process will clean up the lock on the data structure and release the latch. If a process is not able to obtain a latch, it must wait for the latch to be freed up by the process holding it. This causes additional spinning (looking for availability at fixed intervals of time ) of the process, thereby causing extra load on the CPU. This process will spin until the latch is available. A dba has to monitor the latches for contention and make sure that CPU cycles are not being burnt on process spinning. Does ROLLUP work with multiple columns? The ROLLUP feature can in fact be applied to multiple columns. The result is multiple levels of rollup, as illustrated here: select deptno, job, count(*), grouping(deptno), grouping(job) from emp group by rollup(deptno, job); DEPTNO JOB COUNT(*) GROUPING(DEPTNO) GROUPING(JOB) ---- ---- ---- ---- ---- 10 CLERK 1 0 0 10 MANAGER 1 0 0 10 PRESIDENT 1 0 0 10 3 0 1 20 ANALYST 2 0 0 20 CLERK 2 0 0 20 MANAGER 1 0 0 20 5 0 1 30 CLERK 1 0 0 30 MANAGER 1 0 0 30 SALESMAN 4 0 0 30 6 0 1 14 1 1 As shown in this example, we're able to count the employees by 1) department and job; 2) department; and 3) grand total. What is an inline view? A subquery in the from clause of your main query. Give an example of an inline view and Top-N Query. SELECT ename, job, sal, rownum FROM (SELECT ename, job, sal FROM emp ORDER BY sal) WHERE rownum <= 3; SMITH CLERK 800 1 JAMES CLERK 950 2 ADAMS CLERK

185

186

187

188

189

190 191

192

1100 3 What SQL*Plus command is useful for determining whether the "N rows selected" message will appear? Feedback What SQL*Plus keyword is used for defining formats for how SQL*Plus displays column information? Set This phrase describes a query that feeds one row of results to a parent query for the purpose of selection when the exact where clause criteria is not known? Single-row subquery. Use of what command requires that you first run the plustrce.sql script? Autotrace The database for an international athletic competition consists of one table, ATHLETES, containing contestant name, age, and represented country. To determine the youngest athlete representing each country, how do you write the code? scott@PO816> SELECT name, country, age FROM athletes WHERE ( country, age ) IN ( SELECT country, min(age) FROM athletes GROUP BY country); What is a single-row subquery? The main query expects the subquery to return only one value. What is an inline view? A subquery in a from clause used for defining an intermediate result set to query from. What does AUTOTRACE do? Allows us to see the execution plan of the queries we've executed and the resources they used, without having to use the EXPLAIN PLAN command. What does SQL_TRACE do? Enables logging of all application SQL, performance stats and query plan used. What does TKPROF do? Formats the raw trace files into a readable report. What are the two main index types that Oracle uses? B*Tree and Bitmap When are Bitmap indexes appropriate? In situations of low cardinality data, i.e. data with few distinct values. What is a top-n query? select * from ( select ename from emp order by sal ) where rownum <= 3; In general it refers to getting the top-n rows from a result set. What is PostgreSQL? PostgreSQL is a sophisticated Object-Relational DBMS, supporting almost all SQL constructs, including subselects, transactions, and user-defined types and functions. It is the most advanced open-source database available anywhere. Commercial Support is also available. What are the three main reasons for partitioning a database? 1. To increase availability (derived from the fact that partitions are independent entities). 2. To ease administration burdens (derived from the fact that performing operations on small objects is inherently easier, faster, and less resource intensive than performing

193

194

195

196 197 198

199 200 201 202 203

204

205

206

the same operation on a large object). 3. To enhance DML and query performance (potential to perform parallel DML). Does the order of stored procedures in a package matter? It does if one procedure calls another; if that happens, the calling procedure must be the earlier of the two.

Вам также может понравиться