informatica

Embed Size (px)

DESCRIPTION

informatica

Citation preview

  • Solution for Informatica

    problems

    >> Scenario based solutions

    Classic

    Flipcard

    Magazine

    Mosaic

    Sidebar

    Snapshot

    Timeslide

    1.

    DEC

    3

    Diff between Primary key and unique key

    Scenario: Diff between Primary key and unique key Solution:

  • Unique key display the unique values which can have one null value where Primary key has unique values without null. Whenever you create the primary key constraints, Oracle by default create a unique index with not null.

    Posted 3rd December 2012 by Prafull Dangore

    0

    Add a comment 2.

    3.

    JUN

    15

    SQL Transformation with examples =============================================================================================

    SQL Transformation with examples

    Use: SQL Transformation is a connected transformation used to process SQL queries in the midstream of a pipeline. We can insert, update, delete and retrieve rows from the database at run

    time using the SQL transformation. Use SQL transformation in script mode to run DDL (data definition language) statements like creating or dropping the tables. The following SQL statements can be used in the SQL transformation.

    Data Definition Statements (CREATE, ALTER, DROP, TRUNCATE, RENAME) DATA MANIPULATION statements (INSERT, UPDATE, DELETE, MERGE) DATA Retrieval Statement (SELECT) DATA Control Language Statements (GRANT, REVOKE) Transaction Control Statements (COMMIT, ROLLBACK)

    Scenario: Lets say we want to create a temporary table in mapping while workflow is running for some intermediate calculation. We can use SQL transformation in script mode to achieve the same. Below we will see how to create sql transformation in script mode with an example where we will

    create a table in mapping and will insert some rows in the same table. Solution: Step 1: Create two text files in the $PMSourceFileDir directory with some sql queries.

    1. sql_script.txt File contains the below Sql queries (you can have multiple sql queries in file separated by semicolon) create table create_emp_table

    (emp_id number,emp_name varchar2(100))

    2. sql_script2.txt File contains the below Sql queries (you can have multiple sql queries in file separated by semicolon)

  • insert into create_emp_table values (1,'abc') These are the script files to be executed by SQL transformation on database server. Step 2: We need a source which contains the above script file names with a complete path. So, I created another file in the $PMSourceFileDir directory to store these script file names

    as Sql_script_input.txt. File contains the list of files with their complete path: E:\softs\Informatica\server\infa_shared\SrcFiles\sql_script.txt E:\softs\Informatica\server\infa_shared\SrcFiles\sql_script2.txt Step 3: Now we will create a mapping to execute the script files using the SQL transformation. Go to the mapping designer tool, source analyzer and Import from file =>then creates source definition by selecting a file Sql_script_input.txt Located at

    E:\softs\Informatica\server\infa_shared\SrcFiles. Source definition will look like

    Similarly create a target definition, go to target designer and create a target flat file with result and error ports. This is shown in the below image

    Step 4:

    Go to the mapping designer and create a new mapping. Drag the flat file into the mapping designer. Go to the Transformation in the toolbar, Create, select the SQL transformation, enter a name and click

    on create. Now select the SQL transformation options as script mode and DB type as Oracle and click ok.

  • The SQL transformation is created with the default ports. Now connect the source qualifier transformation ports to the SQL transformation input port. Drag the target flat file into the mapping and connect the SQL transformation output ports to the

    target. Save the mapping. The mapping flow image is shown in the below picture.

    Go to the workflow manager; create a new workflow and session. Edit the session. For source, enter the source & target file directory. For the SQL transformation, enter the oracle database relational connection as shown below.

    Save the workflow and run it. Open the target file, you will find the below data.

    "PASSED"; "PASSED";

    "PASSED"; -: for sql_script.txt, where it will crate the table and "PASSED"; -: For sql_scriptw.txt, where it will insert rows in to the table

    Fire a select query on the database to check whether table is created or not.

    =============================================================================

    Posted 15th June 2012 by Prafull Dangore

    0

  • Add a comment

    4.

    JUN

    7

    Efficient SQL Statements : SQL Tunning Tips

    Efficient SQL Statements This is an extremely brief look at some of the factors that may effect the efficiency

    of your SQL and PL/SQL code. It is not intended as a thorough discussion of the area and should not be used as such.

    Check Your Stats Why Indexes Aren't Used Caching Tables EXISTS vs. IN Presence Checking Inequalities When Things Look Bad! Driving Tables (RBO Only) Improving Parse Speed Packages Procedures and Functions

    Check Your Stats

    The Cost Based Optimizer (CBO) uses statistics to decide which execution plan to

    use. If these statistics are incorrect the decision made by the CBO may be incorrect. For this reason it is important to make sure that these statistics are

    refreshed regularly. The following article will help you achieve this aim.

    Cost Based Optimizer (CBO) and Database Statistics

    Why Indexes Aren't Used

    The presence of an index on a column does not guarantee it will be used. The following is a small list of factors that will prevent an index from being used.

    The optimizer decides it would be more efficient not to use the index. If your query is returning the majority of the data in a table, then a full table scan is probably

    going to be the most efficient way to access the table. You perform a function on the indexed column i.e. WHERE UPPER(name) = 'JONES'.

    The solution to this is to use a Function-Based Index. You perform mathematical operations on the indexed column i.e. WHERE salary + 1

    = 10001 You concatenate a column i.e. WHERE firstname || ' ' || lastname = 'JOHN JONES'

  • You do not include the first column of a concatenated index in the WHERE clause of your statement. For the index to be used in a partial match, the first column

    (leading-edge) must be used. Index Skip Scanning in Oracle 9i and above allow indexes to be used even when the leading edge is not referenced.

    The use of 'OR' statements confuses the Cost Based Optimizer (CBO). It will rarely choose to use an index on column referenced using an OR statement. It will even

    ignore optimizer hints in this situation. The only way of guaranteeing the use of indexes in these situations is to use an INDEX hint.

    EXISTS vs. IN

    The EXISTS function searches for the presence of a single row meeting the stated criteria as opposed to the IN statement which looks for all occurrences.

    TABLE1 - 1000 rows TABLE2 - 1000 rows (A)

    SELECT t1.id FROM table1 t1

    WHERE t1.code IN (SELECT t2.code FROM table2 t2); (B)

    SELECT t1.id FROM table1 t1

    WHERE EXISTS (SELECT '1' FROM table2 t2

    WHERE t2.code = t1.code) For query A, all rows in TABLE2 will be read for every row in TABLE1. The effect will be 1,000,000 rows read from items. In the case of query B, a maximum of 1 row

    from TABLE2 will be read for each row of TABLE1, thus reducing the processing overhead of the statement.

    Rule of thumb:

    If the majority of the filtering criteria are in the subquery then the IN variation may be more performant.

    If the majority of the filtering criteria are in the top query then the EXISTS variation

    may be more performant. I would suggest they you should try both variants and see which works the best.

    Note. In later versions of Oracle there is little difference between EXISTS and IN operations.

    Presence Checking

    The first question you should ask yourself is, "Do I need to check for the presence of a record?" Alternatives to presence checking include:

    Use the MERGE statement if you are not sure if data is already present.

    Perform an insert and trap failure because a row is already present using theDUP_VAL_ON_INDEX exception handler.

    Perform an update and test for no rows updated using SQL%ROWCOUNT.

  • If none of these options are right for you and processing is conditional on the presence of certain records in a table, you may decide to code something like the

    following. SELECT Count(*)

    INTO v_count FROM items WHERE item_size = 'SMALL';

    IF v_count = 0 THEN

    -- Do processing related to no small items present END IF; If there are many small items, time and processing will be lost retrieving multiple

    records which are not needed. This would be better written like one of the following.

    SELECT COUNT(*) INTO v_count FROM items

    WHERE item_size = 'SMALL' AND rownum = 1;

    IF v_count = 0 THEN

    -- Do processing related to no small items present END IF; OR

    SELECT COUNT(*) INTO v_count

    FROM dual WHERE EXISTS (SELECT 1 FROM items

    WHERE item_size = 'SMALL');

    IF v_count = 0 THEN -- Do processing related to no small items present END IF;

    In these examples only single a record is retrieved in the presence/absence check.

    Inequalities

    If a query uses inequalities (item_no > 100) the optimizer must estimate the number of rows returned before it can decide the best way to retrieve the data. This estimation is prone to errors. If you are aware of the data and it's distribution

    you can use optimizer hints to encourage or discourage full table scans to improve performance.

    If an index is being used for a range scan on the column in question, the performance can be improved by substituting >= for >. In this case, item_no > 100 becomes item_no >= 101. In the first case, a full scan of the index will occur.

    In the second case, Oracle jumps straight to the first index entry with an item_no of 101 and range scans from this point. For large indexes this may significantly

    reduce the number of blocks read.

  • When Things Look Bad!

    If you have a process/script that shows poor performance you should do the

    following:

    Write sensible queries in the first place! Identify the specific statement(s) that are causing a problem. The simplest way to

    do this is to use SQL Trace, but you can try running the individual statements using SQL*Plus and timing them (SET TIMING ON)

    Use EXPLAIN to look at the execution plan of the statement. Look for any full table accesses that look dubious. Remember, a full table scan of a small table is often more efficient than access by index.

    Check to see if there are any indexes that may help performance. Try adding new indexes to the system to reduce excessive full table scans.

    Typically, foreign key columns should be indexed as these are regularly used in join conditions. On occasion it may be necessary to add composite (concatenated) indexes that will only aid individual queries. Remember, excessive indexing can

    reduce INSERT, UPDATE and DELETE performance.

    Driving Tables (RBO Only)

    The structure of the FROM and WHERE clauses of DML statements can be tailored to improve the performance of the statement. The rules vary depending on whether the database engine is using the Rule or Cost based optimizer. The situation is

    further complicated by the fact that the engine may perform a Merge Join or a Nested Loop join to retrieve the data. Despite this, there are a few rules you can

    use to improve the performance of your SQL. Oracle processes result sets a table at a time. It starts by retrieving all the data for

    the first (driving) table. Once this data is retrieved it is used to limit the number of rows processed for subsequent (driven) tables. In the case of multiple table joins, the driving table limits the rows processed for the first driven table. Once

    processed, this combined set of data is the driving set for the second driven table etc. Roughly translated into English, this means that it is best to process tables that

    will retrieve a small number of rows first. The optimizer will do this to the best of it's ability regardless of the structure of the DML, but the following factors may help.

    Both the Rule and Cost based optimizers select a driving table for each query. If a decision cannot be made, the order of processing is from the end of the FROM

    clause to the start. Therefore, you should always place your driving table at the end of the FROM clause. Subsequent driven tables should be placed in order so that those retrieving the most rows are nearer to the start of the FROM clause.

    Confusingly, the WHERE clause should be writen in the opposite order, with the driving tables conditions first and the final driven table last. ie.

    FROM d, c, b, a WHERE a.join_column = 12345 AND a.join_column = b.join_column

    AND b.join_column = c.join_column AND c.join_column = d.join_column;

  • If we now want to limit the rows brought back from the "D" table we may write the following.

    FROM d, c, b, a WHERE a.join_column = 12345

    AND a.join_column = b.join_column AND b.join_column = c.join_column AND c.join_column = d.join_column

    AND d.name = 'JONES'; Depending on the number of rows and the presence of indexes, Oracle my now pick

    "D" as the driving table. Since "D" now has two limiting factors (join_column and name), it may be a better candidate as a driving table so the statement may be better written as follows.

    FROM c, b, a, d WHERE d.name = 'JONES'

    AND d.join_column = 12345 AND d.join_column = a.join_column AND a.join_column = b.join_column

    AND b.join_column = c.join_column This grouping of limiting factors will guide the optimizer more efficiently making

    table "D" return relatively few rows, and so make it a more efficient driving table. Remember, the order of the items in both the FROM and WHERE clause will not

    force the optimizer to pick a specific table as a driving table, but it may influence it's decision. The grouping of limiting conditions onto a single table will reduce the number of rows returned from that table, and will therefore make it a stronger

    candidate for becoming the driving table.

    Caching Tables

    Queries will execute much faster if the data they reference is already cached. For small frequently used tables performance may be improved by caching tables. Normally, when full table scans occur, the cached data is placed on the Least

    Recently Used (LRU) end of the buffer cache. This means that it is the first data to be paged out when more buffer space is required. If the table is cached (ALTER

    TABLE employees CACHE;) the data is placed on the Most Recently Used (MRU) end of the buffer, and so is less likely to be paged out before it is re-queried. Caching tables may alter the CBO's path through the data and should not be used without

    careful consideration.

    Improving Parse Speed

    Execution plans for SELECT statements are cached by the server, but unless the exact same statement is repeated the stored execution plan details will not be reused. Even differing spaces in the statement will cause this lookup to fail. Use of

    bind variables allows you to repeatedly use the same statements whilst changing the WHERE clause criteria. Assuming the statement does not have a cached

    execution plan it must be parsed before execution. The parse phase for statements can be decreased by efficient use of aliasing. If an alias is not present, the engine must resolve which tables own the specified columns. The following is an example.

    Bad Statement Good Statement

  • SELECT first_name,

    last_name, country FROM employee,

    countries WHERE country_id = id

    AND lastname = 'HALL';

    SELECT e.first_name, e.last_name, c.country

    FROM employee e, countries c

    WHERE e.country_id = c.id AND e.last_name =

    'HALL';

    Packages Procedures and Functions

    When an SQL statement, or anonymous block, is passed to the server it is

    processed in three phases.

    Phase Actions

    Parse Syntax Check and Object Resolution

    Execution Necessary Reads and Writes performed

    Fetch Resultant rows are Retrieved, Assembled, Sorted and Returned

    The Parse phase is the most time and resource intensive. This phase can be

    avoided if all anonymous blocks are stored as Database Procedures, Functions, Packages or Views. Being database objects their SQL text and compiled code is

    stored in Data Dictionary and the executable copies reside in the Shared Pool.

    Posted 7th June 2012 by Prafull Dangore

    0

    Add a comment

    5.

    JUN

    7

    Function : NVL2 and COALESCE

    NVL2

    The NVL2 function accepts three parameters. If the first parameter value is not null it returns the value in the second parameter. If the first parameter value is null, it returns the third parameter.

    The following query shows NVL2 in action. SQL> SELECT * FROM null_test_tab ORDER BY id;

    ID COL1 COL2 COL3 COL4

    ---------- ---------- ---------- ---------- ---------- 1 ONE TWO THREE FOUR

    2 TWO THREE FOUR

  • 3 THREE FOUR

    4 THREE THREE

    4 rows selected.

    SQL> SELECT id, NVL2(col1, col2, col3) AS output FROM null_test_tab ORDER BY id;

    ID OUTPUT

    ---------- ---------- 1 TWO

    2 THREE 3 THREE

    4 THREE

    4 rows selected.

    SQL>

    COALESCE

    The COALESCE function was introduced in Oracle 9i. It accepts two or more parameters and returns the first non-null value in a list. If all parameters contain null values, it returns null. SQL> SELECT id, COALESCE(col1, col2, col3) AS output FROM null_test_tab ORDER BY id;

    ID OUTPUT ---------- ----------

    1 ONE 2 TWO

    3 THREE

    4 THREE

    4 rows selected.

    SQL>

    Posted 7th June 2012 by Prafull Dangore

    0

    Add a comment 6.

    7.

    FEB

    8

    Load the session statistics such as Session Start & End Time, Success Rows, Failed Rows and Rejected Rows etc. into a database

    table for audit/log purpose.

  • Scenario:

    Load the session statistics such as Session Start & End Time, Success Rows, Failed Rows and Rejected Rows etc. into a database table for audit/log purpose.

    Solution:

    After performing the below solution steps your end workflow will look as follows: START => SESSION1 => ASSIGNMENT TASK => SESSION2

    SOLUTION STEPS SESSION1 This session is used to achieve your actual business logic. Meaning this session will perform your actual data load. It can be anything File Table.File or TableTable, File WORKFLOW VARIABLES Create the following workflow variables. => $$Workflowname => $$SessionStartTime => $$SessionEndTime => $$TargetSuccessrows => $$TargetFailedRows ASSIGNMENT TASK Use the Expression tab in the Assignment Task and assign as follows: $$workflowname = $PMWorkflowName $$sessionStartTime = $ SESSION1.StartTime $$SessionEndTime = $ SESSION1.Endtime $$ TargetSuccessrows = $ SESSION1. TgtSuccessRows $$ TargetFailedRows = $ SESSION1. TgtFailedRows SESSION2 This session is used to load the session statistics into a database table. => This should call a mapping say m_sessionLog => This mapping m_sessionLog should have mapping variables for the above defined workflow variables such as $$wfname, $$Stime, $$Etime, $$TSRows and $$TFRows. => This mapping m_sessionLog should use a dummy source and it must have a expression transformation and a target => database Audit table) => Inside the expression you must assign the mapping variables to the output ports

  • workflowname=$$wfname starttime=$$Stime endtime=$$Etime SucessRows=$$TSRows FailedRows=$$TFRows => Create a target database table with the following columns Workflowname, start time, end time, success rows and failed rows. => Connect all the required output ports to the target which is nothing but your audit table. PRE-Session Variable => Session 2: In the Pre-session variable assignment tab assign the mapping variable = workflow variable => In our case $$wfname=$$workflowname $$Stime=$$sessionStartTime $$Etime=$$sessionEndTime $$TSRows=$$TargetSuccessrows $$TFRows=$$TargetFailedrows Workflow Execution

    Posted 8th February 2012 by Prafull Dangore

    0

    Add a comment

    8.

    DEC

    30

    Use Target File Path in Parameter File

    Scenario:

    I want to use mapping parameter to store target file path. My question is can define file path in parameter file? If possible can anyone explain how to assign target file path as parameter?

    Solution: You can define the file path in parameter file. $OutputFileName=your file path here Give the above mentioned parameter in your parameter file.

    Posted 30th December 2011 by Prafull Dangore

    0

    Add a comment

  • 9.

    DEC

    27

    Insert and reject records using update strategy.

    Scenario:

    Insert and reject records using update strategy.

    There is an emp table and from that table insert the data to targt where sal

  • 1 11/11/2010 2 09/09/2009

    Solution:

    1. Connect SQF to an expression. 2. In expression make hire_date as input only and make another port hire_date1 as o/p port with date

    data type. 3. In o/p port of hire_date write condition like as below

    TO_DATE(TO_CHAR(hire_date),YYYYMMDD)

    Posted 27th December 2011 by Prafull Dangore

    1

    View comments

    2.

    DEC

    26

    How to change a string to decimal with 2 decimal places in informatica?

    Scenario: How to change a string to decimal with 2 decimal places in informatica? Eg:: input data 12345678 I want output as 123456.78

    Solution:

    output = to_decimal(to_integer(input)/100,2)

    OR

    SUBSTR(INPUT_FIELD, 1, LENGTH(INPUT_FIELD) - 2) || '.' || SUBSTR(INPUT_FIELD, -2)

    Posted 26th December 2011 by Prafull Dangore

    0

    Add a comment

    3.

    DEC

    26

  • Append the data in a flat file for a daily run

    Scenario:

    I have the flat file in our server location; I want to append the data in a flat file for a daily run. Solution: We have an option in Informatica "Append if exists" in target session properties.

    Posted 26th December 2011 by Prafull Dangore

    0

    Add a comment 4.

    5.

    DEC

    22

    Convert Day No. to corresponding month and date of year

    Scenario: Suppose you have a source is like this Source E_NO YEAR DAYNO ------ --------- - --------- 1 01-JAN-07 301 2 01-JAN-08 200 Year column is a date and dayno is numeric that represents a day ( as in 365 for 31-Dec-Year). Convert the Dayno to corresponding year's month and date and then send to target. Target E_NO YEAR_MONTH_DAY ------ --------- ---------- 1 29-OCT-07 2 19-JUL-08 Solution: Use below date format in exp transformation

    Add_to_date(YEAR,DD,DAYNO)

    Posted 22nd December 2011 by Prafull Dangore

  • 0

    Add a comment

    6.

    DEC

    22

    How to delete duplicate rows in a table?

    Scenario: How to delete duplicate rows in a table?

    Solution:

    delete from emp a where rowid != (select max(rowid) from emp b where a.empno=b.empno); OR delete from emp a where rowid != (select min(rowid) from emp b where a.empno=b.empno);

    Posted 22nd December 2011 by Prafull Dangore

    0

    Add a comment

    7.

    DEC

    22

    How to get nth max salaries ?

    Scenario: How to get nth max salaries ?

    Solution: select distinct hiredate from emp a where &n = (select count(distinct sal) from emp b where a.sal >= b.sal);

    Posted 22nd December 2011 by Prafull Dangore

    0

    Add a comment 8.

    9.

    DEC

  • 22

    How to get 3 Max & Min salaries?

    Scenario: How to get 3 Max & Min salaries?

    Solution:

    Max - select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where a.sal = (select count(distinct sal) from emp b where a.sal >= b.sal);

    Posted 22nd December 2011 by Prafull Dangore

    0

    Add a comment

    10.

    DEC

    22

    Find FIRST & LAST n records from a table.

    Scenario: Find FIRST & LAST n records from a table.

    Solution: First - select * from emp where rownum

  • Find the 3rd MAX & MIN salary in the emp table

    Scenario: Find the 3rd MAX & MIN salary in the emp table

    Solution:

    Max - select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where e1.sal = e2.sal);

    Posted 22nd December 2011 by Prafull Dangore

    0

    Add a comment 12.

    13.

    DEC

    22

    Sql query to find EVEN & ODD NUMBERED records from a table.

    Scenario: Sql query to find EVEN & ODD NUMBERED records from a table.

    Solution:

    Even - select * from emp where rowid in (select decode(mod(rownum,2),0,rowid, null) from emp);

    Odd - select * from emp where rowid in (select decode(mod(rownum,2),0,null ,rowid) from emp);

    Posted 22nd December 2011 by Prafull Dangore

    0

    Add a comment

    14.

    DEC

  • 22

    SQL questions which are the most frequently asked in interviews.

    Complex Queries in SQL ( Oracle )

    To fetch ALTERNATE records from a table. (EVEN NUMBERED) select * from emp where rowid in (select decode(mod(rownum,2),0,rowid, null) from emp); To select ALTERNATE records from a table. (ODD NUMBERED) select * from emp where rowid in (select decode(mod(rownum,2),0,null ,rowid) from emp); Find the 3rd MAX salary in the emp table. select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where e1.sal = e2.sal); Select FIRST n records from a table. select * from emp where rownum = b.sal); How to get nth max salaries ? select distinct hiredate from emp a where &n = (select count(distinct sal) from emp b where a.sal >= b.sal); Select DISTINCT RECORDS from emp table. select * from emp a where rowid = (select max(rowid) from emp b where a.empno=b.empno); How to delete duplicate rows in a table? delete from emp a where rowid != (select max(rowid) from emp b where a.empno=b.empno); Count of number of employees in department wise. select count(EMPNO), b.deptno, dname from emp a, dept b where a.deptno(+)=b.deptno group by b.deptno,dname; Suppose there is annual salary information provided by emp table. How to fetch monthly salary of each and every employee?

  • select ename,sal/12 as monthlysal from emp; Select all record from emp table where deptno =10 or 40. select * from emp where deptno=30 or deptno=10; Select all record from emp table where deptno=30 and sal>1500. select * from emp where deptno=30 and sal>1500; Select all record from emp where job not in SALESMAN or CLERK. select * from emp where job not in ('SALESMAN','CLERK'); Select all record from emp where ename in 'BLAKE','SCOTT','KING'and'FORD'. select * from emp where ename in('JONES','BLAKE','SCOTT','KING','FORD'); Select all records where ename starts with S and its lenth is 6 char. select * from emp where ename like'S____'; Select all records where ename may be any no of character but it should end with R. select * from emp where ename like'%R'; Count MGR and their salary in emp table. select count(MGR),count(sal) from emp; In emp table add comm+sal as total sal . select ename,(sal+nvl(comm,0)) as totalsal from emp; Select any salary any(select sal from emp where sal
  • 22

    Complex Queries in SQL ( Oracle )

    Complex Queries in SQL ( Oracle )

    To fetch ALTERNATE records from a table. (EVEN NUMBERED) select * from emp where rowid in (select decode(mod(rownum,2),0,rowid, null) from emp); To select ALTERNATE records from a table. (ODD NUMBERED) select * from emp where rowid in (select decode(mod(rownum,2),0,null ,rowid) from emp); Find the 3rd MAX salary in the emp table. select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where e1.sal = e2.sal); Select FIRST n records from a table. select * from emp where rownum = b.sal); How to get nth max salaries ? select distinct hiredate from emp a where &n = (select count(distinct sal) from emp b where a.sal >= b.sal); Select DISTINCT RECORDS from emp table. select * from emp a where rowid = (select max(rowid) from emp b where a.empno=b.empno); How to delete duplicate rows in a table? delete from emp a where rowid != (select max(rowid) from emp b where a.empno=b.empno); Count of number of employees in department wise. select count(EMPNO), b.deptno, dname from emp a, dept b where a.deptno(+)=b.deptno group by b.deptno,dname; Suppose there is annual salary information provided by emp table. How to fetch monthly salary of each and every employee?

  • select ename,sal/12 as monthlysal from emp; Select all record from emp table where deptno =10 or 40. select * from emp where deptno=30 or deptno=10; Select all record from emp table where deptno=30 and sal>1500. select * from emp where deptno=30 and sal>1500; Select all record from emp where job not in SALESMAN or CLERK. select * from emp where job not in ('SALESMAN','CLERK'); Select all record from emp where ename in 'BLAKE','SCOTT','KING'and'FORD'. select * from emp where ename in('JONES','BLAKE','SCOTT','KING','FORD'); Select all records where ename starts with S and its lenth is 6 char. select * from emp where ename like'S____'; Select all records where ename may be any no of character but it should end with R. select * from emp where ename like'%R'; Count MGR and their salary in emp table. select count(MGR),count(sal) from emp; In emp table add comm+sal as total sal . select ename,(sal+nvl(comm,0)) as totalsal from emp; Select any salary any(select sal from emp where sal
  • DEC

    22

    Informatica Quiz: Set 2

    Quiz: Informatica Set 2 A lookup transformation is used to look up data in

    Explanation: flat file Relational table view synonyms All of the above (correct)

    Which value returned by NewLookupRow port says that Integration Service does not update or insert the row in the cache?

    Explanation: 3 (wrong) 2 1 0

    Which one need a common key to join?

    Explanation: source qualifier joiner (correct) look up

    Which one support hetrogeneous join?

    Explanation: source qualifier joiner (correct) look up

    What is the use of target loader?

    Explanation: Target load order is first the data is load in dimension table and then fact table. Target load order is first the data is load in fact table and then dimensional table. Load the data from different target at same time. (wrong)

    Which one is not tracing level?

    Explanation: terse verbose

  • initialization verbose initialization terse initialization (correct)

    Which output file is not created during session running?

    Explanation: Session log workflow log Error log Bad files cache files (correct)

    Is Fact table is normalised ?

    Explanation: yes no (correct)

    Which value returned by NewLookupRow port says that Integration Service inserts the row into the cache?

    Explanation: 0 (wrong) 1 2 3

    Which transformation only works on relational source?

    Explanation: lookup Union joiner Sql (correct)

    Which are both connected and unconnected?

    Explanation: External Store Procedure (omitted) Stote Procedure (correct) Lookup (correct) Advanced External Procedure Transformation

    Can we generate alpha-numeric value in sequence generator?

    Explanation: yes no (correct)

    Which transformation is used by cobol source?

  • Explanation: Advanced External Procedure Transformation Cobol Transformation Unstructured Data Transformation Normalizer (correct)

    What is VSAM normalizer transformation?

    Explanation: The VSAM normalizer transformation is the source qualifier transformation for a COBOL source

    definition. The VSAM normalizer transformation is the source qualifier transformation for a flat file source

    definition. The VSAM normalizer transformation is the source qualifier transformation for a xml source

    definition. (wrong)

    Non of these What is VSAM normalizer transformation?

    Explanation: The VSAM normalizer transformation is the source qualifier transformation for a COBOL source

    definition. The VSAM normalizer transformation is the source qualifier transformation for a flat file source

    definition. The VSAM normalizer transformation is the source qualifier transformation for a xml source

    definition. (wrong) Non of these

    Posted 22nd December 2011 by Prafull Dangore

    0

    Add a comment

    18.

    DEC

    22

    Informatica Quiz: Set 1

    Quiz: Informatica Set 1 Which one is not correct about filter transformation? Explanation: Filter generally parses single condition. For multiple condition we can use router

    Act as a 'where' condition Can't passes multiple conditions Act like 'Case' in pl/sql (wrong) If one record does not match condition, the record is blocked

    Can we calculate in aggrigator ?

  • Explanation: No Yes (correct)

    Which one is not a type of fact? Explanation:

    Semi-aditive Additive Confirm fact Not additive (wrong)

    Which one is not a type of dimension ? Explanation:

    Conformed dimension Rapidly changing dimension (correct) Junk dimension Degenerated dimension

    Which of these not correct about Code Page? Explanation:

    A code page contains encoding to specify characters in a set of one or more languages A code page contains decoding to specify characters in a set of one or more languages In this way application stores, receives, and sends character data. Non of these (wrong)

    What is a mapplet? Explanation:

    Combination of reusable transformation. Combination of reusable mapping Set of transformations and it allows us to reuse (correct) Non of these

    What does reusable transformation mean? Explanation:

    It can be re-used across repositories I can only be used in mapplet. It can use in multiple mapping only once It can use in multiple mapping multiple times (correct)

    Which one is not an option in update strategy? Explanation:

    dd_reject 4 (correct) 2 dd_delete

    Can we update records without using update strategy? Explanation:

    Yes (correct) No

    How to select distinct records form Source Qualifier? Explanation:

  • Choose 'non duplicate' option Choose 'select distinct' option (correct) Choose 'Select non duplicate'

    What type of repository is no available in Informatica Repository Manager? Explanation:

    Standalone Repository Local Repository User Defined Versioned Repository Manual Repository (wrong)

    Joiner does not support flat file. Explanation:

    False (correct)

    True How to execute PL/SQL script from Informatica mapping? Explanation:

    Lookup Store Procdure (correct) Expression Non of these

    NetSal= bassic+hra. In which transformation we can achive this? Explanation:

    Aggrigator Lookup Filter Expression (correct)

    Which one is not an active transformation?

    Explanation: Sequence generator Normalizer Sql Store Procedure (wrong)

    Posted 22nd December 2011 by Prafull Dangore

    0

    Add a comment

    19.

    DEC

    22

    How large is the database,used and free space?

  • Scenario: How large is the database,used and free space?

    Solution:

    select round(sum(used.bytes) / 1024 / 1024 / 1024 ) || ' GB' "Database Size" , round(sum(used.bytes) / 1024 / 1024 / 1024 ) - round(free.p / 1024 / 1024 / 1024) || ' GB' "Used space" , round(free.p / 1024 / 1024 / 1024) || ' GB' "Free space" from (select bytes from v$datafile union all select bytes from v$tempfile union all select bytes from v$log) used , (select sum(bytes) as p from dba_free_space) free group by free.p

    Posted 22nd December 2011 by Prafull Dangore

    0

    Add a comment 20.

    21.

    DEC

    20

    Batch File to Append Date to file name

    Scenario: Batch File to Append Date to file name

    Solution: @echo off REM Create a log file with the current date and time in the filename REM the ~4 in the Date skips the first four characters of the echoed date stamp and writes the remainder and so on set LOG_FILE_NAME=Example_File_Name.%date:~4,2%%date:~7,2%%date:~10,4%.%time:~0,2%%time:~3,2%%time:~6,2%.txt Echo This is much easier in UNIX > c: emp\%LOG_FILE_NAME% :exit

  • OR @echo off for /F "tokens=2,3,4 delims=/ " %%i in ('date/t') do set y=%%k for /F "tokens=2,3,4 delims=/ " %%i in ('date/t') do set d=%%k%%i%%j for /F "tokens=5-8 delims=:. " %%i in ('echo.^| time ^| find "current" ') do set t=%%i%%j set t=%t%_ if "%t:~3,1%"=="_" set t=0%t% set t=%t:~0,4% set "theFilename=%d%%t%" echo %theFilename%

    Posted 20th December 2011 by Prafull Dangore

    0

    Add a comment

    22.

    DEC

    19

    PL/SQL Interview Questions 1. What is PL/SQL ?

    PL/SQL is Oracle's Procedural Language extension to SQL. PL/SQL's language syntax, structure and datatypes are similar to that of ADA. The language includes object oriented programming techniques such as encapsulation, function overloading, information hiding (all but inheritance), and so, brings state-of-the-art programming to the Oracle database server and a variety of Oracle tools. PL SQL is a block structured programming language. It combines data manipulation & data

    processing power. It supports all SQL data types. Also has its own data types i,e BOOLEAN,BINARY INTEGER

    2. What is the basic structure of PL/SQL ? A PL/SQL block has three parts: a declarative part, an executable part, and an exception-handling part. First comes the declarative part, in which items can be declared. Once declared, items can be manipulated in the executable part. Exceptions raised during execution can be dealt with in the exception-handling part. 3. What are the components of a PL/SQL block ? PL/SQL Block contains : Declare : optional Variable declaration Begin : Manadatory Procedural statements.

  • Exception : Optional any errors to be trapped End : Mandatory 5. What are the datatypes a available in PL/SQL ? Following are the datatype supported in oracle PLSQL Scalar Types BINARY_INTEGER DEC DECIMAL DOUBLE PRECISION FLOAT INT INTEGER NATURAL NATURALN NUMBER NUMERIC PLS_INTEGER POSITIVE POSITIVEN REAL SIGNTYPE SMALLINT CHAR CHARACTER LONG LONG RAW NCHAR NVARCHAR2 RAW ROWID STRING UROWID VARCHAR VARCHAR2 DATE INTERVAL DAY TO SECOND INTERVAL YEAR TO MONTH TIMESTAMP TIMESTAMP WITH LOCAL TIME ZONE TIMESTAMP WITH TIME ZONE BOOLEAN Composite Types RECORD TABLE VARRAY LOB Types BFILE BLOB CLOB

  • NCLOB Reference Types REF CURSOR REF object_type

    6. What are % TYPE and % ROWTYPE ? What are the advantages of using these over datatypes?% TYPE provides the data type of a variable or a database column to that variable. % ROWTYPE provides the record type that represents a entire row of a table or view or columns selected in the cursor. The advantages are : I. Need not know about variable's data type ii. If the database definition of a column in a table changes, the data type of a variable changes accordingly. Advantage is, if one change the type or size of the column in the table, it will be reflected in our program unit without making any change. %type is used to refer the column's datatype where as %rowtype is used to refer the whole record in a table. 7. What is difference between % ROWTYPE and TYPE RECORD ? % ROWTYPE is to be used whenever query returns a entire row of a table or view. TYPE rec RECORD is to be used whenever query returns columns of different table or views and variables. E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename

    %type); e_rec emp% ROWTYPE cursor c1 is select empno,deptno from emp; e_rec c1 %ROWTYPE. 8. What is PL/SQL table ? A PL/SQL table is a one-dimensional, unbounded, sparse collection of homogenous elements, indexed by integers

    One-dimensional A PL/SQL table can have only one column. It is, in this way, similar to a one-dimensional array.

    Unbounded or Unconstrained There is no predefined limit to the number of rows in a PL/SQL table. The PL/SQL table grows dynamically as you add more rows to the table. The PL/SQL table is, in this way, very different from an array.

    Related to this definition, no rows for PL/SQL tables are allocated for this structure when it is defined.

    Sparse In a PL/SQL table, a row exists in the table only when a value is assigned to that row. Rows do not have to be defined sequentially. Instead you can assign a value to any row in the table. So row 15 could have a value of `Fox' and row 15446 a value of `Red', with no other rows defined in between.

    Homogeneous elements Because a PL/SQL table can have only a single column, all rows in a PL/SQL table contain values of the same datatype. It is, therefore, homogeneous.

    With PL/SQL Release 2.3, you can have PL/SQL tables of records. The resulting table is still, however, homogeneous. Each row simply contains the same set of columns.

    Indexed by integers PL/SQL tables currently support a single indexing mode: by BINARY_INTEGER. This number acts as the "primary key" of the PL/SQL table. The range of a BINARY_INTEGER is from -231-1 to 231-1, so you have an awful lot of rows with which to work

    9. What is a cursor ? Why Cursor is required ? Cursor is a named private SQL area from where information can be accessed. Cursors are required to process rows individually for queries returning multiple rows. 10. Explain the two type of Cursors ? implicit cursor: implicit cursor is a type of cursor which is automatically maintained by the Oracle server itself.implicit cursor returns only one row.

  • Explicit Cursor: Explicit Cursor is defined by the Proframmer,and it has for phases:declare,open,fetch and close.explicit Cursor returns more than one row. 11. What are the PL/SQL Statements used in cursor processing ? DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO or Record types,

    CLOSE cursor name. 12. What are the cursor attributes used in PL/SQL ? %ISOPEN - to check whether cursor is open or not % ROWCOUNT - number of rows fetched/updated/deleted. % FOUND - to check whether cursor has fetched any row. True if rows are fetched. % NOT FOUND - to check whether cursor has fetched any row. True if no rows are featched. These attributes are proceeded with SQL for Implicit Cursors and with Cursor name for Explicit Cursors 13. What is a cursor for loop ? Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor, fetches rows of values from active set into fields in the record and closes when all the records have been processed. eg. FOR emp_rec IN C1 LOOP salary_total := salary_total +emp_rec sal; END LOOP; cursor for loop is use for automatically open ,fetch,close 15. Explain the usage of WHERE CURRENT OF clause in cursors ? PL/SQL provides the WHERE CURRENT OF clause for both UPDATE and DELETE statements inside a cursor in order to allow you to easily make changes to the most recently fetched row of data.

    The general format for the WHERE CURRENT OF clause is as follows:

    UPDATE table_name SET set_clause WHERE CURRENT OF cursor_name;DELETE FROM table_name WHERE CURRENT OF cursor_name;

    Notice that the WHERE CURRENT OF clause references the cursor and not the record into which the next fetched row is deposited.

    The most important advantage to using WHERE CURRENT OF where you need to change the row

    fetched last is that you do not have to code in two (or more) places the criteria used to uniquely identify a row in a table. Without WHERE CURRENT OF, you would need to repeat the WHERE clause of your cursor in the WHERE clause of the associated UPDATEs and DELETEs. As a result, if the table structure changes in a way that affects the construction of the primary key, you have to make sure that each SQL statement is upgraded to support this change. If you use WHERE CURRENT OF, on the other hand, you only have to modify the WHERE clause of the SELECT statement.

    This might seem like a relatively minor issue, but it is one of many areas in your code where you can leverage subtle features in PL/SQL to minimize code redundancies. Utilization of WHERE CURRENT OF,

    %TYPE, and %ROWTYPE declaration attributes, cursor FOR loops, local modularization, and other PL/SQL language constructs can have a big impact on reducing the pain you may experience when you maintain your Oracle-based applications.

    Let's see how this clause would improve the previous example. In the jobs cursor FOR loop above, I want to UPDATE the record that was currently FETCHed by the cursor. I do this in the UPDATE statement by repeating the same WHERE used in the cursor because (task, year) makes up the primary key of this table:

    WHERE task = job_rec.task AND year = TO_CHAR (SYSDATE, 'YYYY');

    This is a less than ideal situation, as explained above: I have coded the same logic in two places, and this code must be kept synchronized. It would be so much more convenient and natural to be able to code the equivalent of the following statements:

    Delete the record I just fetched.

    or:

    Update these columns in that row I just fetched.

  • A perfect fit for WHERE CURRENT OF! The next version of my winterization program below uses this

    clause. I have also switched to a simple loop from FOR loop because I want to exit conditionally from the loop:

    DECLARE CURSOR fall_jobs_cur IS SELECT ... same as before ... ; job_rec

    fall_jobs_cur%ROWTYPE;BEGIN OPEN fall_jobs_cur; LOOP FETCH

    fall_jobs_cur INTO job_rec; IF

    fall_jobs_cur%NOTFOUND THEN EXIT; ELSIF

    job_rec.do_it_yourself_flag = 'YOUCANDOIT' THEN UPDATE winterize

    SET responsible = 'STEVEN' WHERE CURRENT OF

    fall_jobs_cur; COMMIT; EXIT; END IF; END

    LOOP; CLOSE fall_jobs_cur;END;

    16. What is a database trigger ? Name some usages of database trigger ? A database trigger is a stored procedure that is invoked automatically when a predefined event occurs. Database triggers enable DBA's (Data Base Administrators) to create additional relationships between separate databases. For example, the modification of a record in one database could trigger the modification of a record in a second database. 17. How many types of database triggers can be specified on a table ? What are they ?

    Insert Update Delete Before Row o.k. o.k. o.k. After Row o.k. o.k. o.k. Before Statement o.k. o.k. o.k. After Statement o.k. o.k. o.k. If FOR EACH ROW clause is specified, then the trigger for each Row affected by the statement. If WHEN clause is specified, the trigger fires according to the returned Boolean value. the different types of triggers: * Row Triggers and Statement Triggers * BEFORE and AFTER Triggers * INSTEAD OF Triggers * Triggers on System Events and User Events 18. What are two virtual tables available during database trigger execution ? The table columns are referred as OLD.column_name and NEW.column_name. For triggers related to INSERT only NEW.column_name values only available. For triggers related to UPDATE only OLD.column_name NEW.column_name values only available. For triggers related to DELETE only OLD.column_name values only available. The two virtual table available are old and new. 19.What happens if a procedure that updates a column of table X is called in a database trigger of the same table ?

    To avoid the mutation table error ,the procedure should be declared as an AUTONOMOUS TRANSACTION. By this the procedure will be treated as an separate identity. 20. Write the order of precedence for validation of a column in a table ? I. done using Database triggers. ii. done using Integarity Constraints. 21. What is an Exception ? What are types of Exception ?

    Predefined

    Do not declare and allow the Oracle server to raise implicitly NO_DATA_FOUND TOO_MANY_ROWS

  • INVALID_CURSOR ZERO_DIVIDE INVALID_CURSOR WHEN EXCEPTION THEN

    Non predefined

    Declare within the declarative section and allow allow Oracle server to raise implicitly

    o SQLCODE Returns the numeric value for the seeor code

    o SQLERRM Returns the message associated with error number

    DECLARE -- PRAGMA EXCEPTION_INIT (exception, error_number) RAISE WHEN EXCEPTION_NAME THEN

    User defined

    Declare within the declarative section and raise explicitly. IF confidition the RAISE EXCEPTION or RAISE_APPLICATION_ERROR 22. What is Pragma EXECPTION_INIT ? Explain the usage ? Pragma exception_init Allow you to handle the Oracle predefined message by you'r own message. means you can instruct compiler toassociatethe specific message to oracle predefined message at compile time.This way you Improve the Readbility of your program,and handle it accoding to your own way. It should be declare at the DECLARE section. example declare salary number; FOUND_NOTHING exception; Pragma exception_init(FOUND_NOTHING ,100); begin select sal in to salaryfrom emp where ename ='ANURAG'; dbms_output.put_line(salary); exception WHEN FOUND_NOTHING THEN dbms_output.put_line(SQLERRM); end; 23. What is Raise_application_error ? Raise_application_error is used to create your own error messages which can be more descriptive than named exceptions. Syntax is:- Raise_application_error (error_number,error_messages); where error_number is between -20000 to -20999.. 24. What are the return values of functions SQLCODE and SQLERRM ? Pl / Sql Provides Error Information via two Built-in functions, SQLCODE & SQLERRM. SQLCODE Returns the Current Error Code. Returns 1. SQLERRM Returns the Current Error Message Text. Returns " User Defined Exception " 25. Where the Pre_defined_exceptions are stored ?

    PL/SQL declares predefined exceptions in the STANDARD package.

  • 26. What is a stored procedure ? Stored Procedure is the PlSQL subprgram stored in the databasse . Stored Procedure

    A program running in the database that can take complex actions based on the inputs you send it. Using a stored procedure is faster than doing the same work on a client, because the program runs right inside the databaseserver. Stored procedures are nomally written in PL/SQL or Java. advantages fo Stored Procedure Extensibility,Modularity, Reusability, Maintainability and one time compilation. 28. What are the modes of parameters that can be passed to a procedure ? 1.in: in parameter mode is used to pass values to subprogram when invoked. 2.out: out is used to return values to callers of subprograms 3.in out: it is used to define in and out 29. What are the two parts of a procedure ? PROCEDURE name (parameter list.....) is local variable declarations BEGIN Executable statements. Exception. exception handlers end; 31. Give the structure of the function ? FUNCTION name (argument list .....) Return datatype is local variable declarations Begin executable statements Exception execution handlers End; 32. Explain how procedures and functions are called in a PL/SQL block ? Procedure can be called in the following ways a) CALL direc b) EXCECUTE from calling environment c) from other procedures or functions or packages Functions can be called in the following ways a) EXCECUTE from calling environment. Always use a variable to get the return value. b) As part of an SQL/PL SQL Expression 33. What are two parts of package ? The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY. Package Specification contains declarations that are global to the packages and local to the schema. Package Body contains actual procedures and local declaration of the procedures and cursor declarations.

  • 33.What is difference between a Cursor declared in a procedure and Cursor declared in a package specification ? A cursor declared in a package specification is global and can be accessed by other procedures or

    procedures in a package. A cursor declared in a procedure is local to the procedure that can not be accessed by other procedures. The scope of A cursor declared in a procedure is limited to that procedure only. The Scope of cursor declared in a package specification is global . Example: create or replace package curpack is cursor c1 is select * from emp; end curpack; This will create a package Now You can use this cursor any where. Like: set serveroutput on begin for r1 in curpack.c1 loop dbms_output.put_line(r1.empno||' '||r1.ename); end loop; end; this will dispaly all empno and enames. It will be better to use ref cursor in packages 35. How packaged procedures and functions are called from the following? a. Stored procedure or anonymous block b. an application program such a PRC *C, PRO* COBOL c. SQL *PLUS a. PACKAGE NAME.PROCEDURE NAME (parameters); variable := PACKAGE NAME.FUNCTION NAME (arguments); EXEC SQL EXECUTE b. BEGIN PACKAGE NAME.PROCEDURE NAME (parameters) variable := PACKAGE NAME.FUNCTION NAME (arguments); END; END EXEC; c. EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have any out/in-out parameters. A function can not be called. 36.Name the tables where characteristics of Package, procedure and functions are stored ? The Data dictionary tables/ Views where the characteristics of subprograms and Packages are stored are mentioned below a) USER_OBJECTS, ALL_OBJECTS, DBA_OBJECTS b) USER_SOURCE, ALL_SOURCE, DBA_SOURCE

    c) USER_DEPENCENCIES d) USER_ERRORS, ALL_ERRORS, DBA_ERRORS 37. What is Overloading of procedures ? Overloading procs are 2 or more procs with the same name but different arguments. Arguments needs to be different by class it self. ie char and Varchar2 are from same class. Packages - The main advantages of packages are - 1- Since packages has specification and body separate so, whenever any ddl is run and if any proc/func(inside pack) is dependent on that, only body gets invalidated and not the spec. So any other proc/func dependent on package does not gets invalidated.

  • 2- Whenever any func/proc from package is called, whole package is loaded into memory and hence all objects of pack is availaible in memory which means faster execution if any is called. And since we put all related proc/func in one package this feature is useful as we may need to run most of the objects. 3- we can declare global variables in the package 38.Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger ? Why ? Autonomous Transaction is a feature of oracle 8i which maintains the state of its transactions and save it , to affect with the commit or rollback of the surrounding transactions.

    Here is the simple example to understand this :-

    ora816 SamSQL :> declare

    2 Procedure InsertInTest_Table_B 3 is

    4 BEGIN 5 INSERT into Test_Table_B(x) values (1); 6 Commit;

    7 END ; 8 BEGIN 9 INSERT INTO Test_Table_A(x) values (123);

    10 InsertInTest_Table_B;

    11 Rollback; 12 END; 13 / PL/SQL procedure successfully completed.

    ora816 SamSQL :> Select * from Test_Table_A; X---------- 123 ora816 SamSQL :> Select * from Test_Table_B; X---------- 1

    Notice in above pl/sql COMMIT at line no 6 , commits the transaction at

    line-no 5 and line-no 9. The Rollback at line-no 11 actually did nothing.

    Commit/ROLLBACK at nested transactions will commit/rollback all other DML transaction before that. PRAGMA AUTONOMOUS_TRANSACTION override this behavior. Let us the see the following example with PRAGMA AUTONOMOUS_TRANSACTION.

    39. What is difference between a PROCEDURE & FUNCTION ? A function always return a values while procedure can return one or more values through Parameters. A function can call directly by sql statement like select "func_name" from dual while procedure cannot. 40. What is Data Concarency and Consistency?

    Concurrency

  • How well can multiple sessions access the same data simultaneously

    Consistency

    How consistent is the view of the data between and within multiple sessions, transactions or statements 41. Talk about "Exception Handling" in PL/SQL? the exception are written to handle the exceptions thrown by programs. we have user defined and system exception. user defined exception are the exception name given by user (explicitly decalred and used) and they are raised to handle the specific behaviour of program. system exceptions are raised due to invalid data(you dont have to deaclre these). few examples are when no_data_found, when others etc. 44. Can we use commit or rollback command in the exception part of PL/SQL block? Yes, we can use the TCL commands(commit/rollback) in the exception block of a stored procedure/function. The code in this part of the program gets executed like those in the body without any restriction. You can include any business functionality whenever a condition in main block(body of

    a proc/func) fails and requires a follow-thru process to terminate the execution gracefully! DECALRE .. BEGIN . EXCEPTION

    WHEN NO_DATA_FOUND THEN INSERT INTO err_log( err_code, code_desc)

    VALUES(1403, No data found) COMMIT; RAISE; END 46. What is bulk binding please explain me in brief ? Bulk Binds (BULK COLLECT , FORALL ) are a PL/SQL technique where, instead of multiple individual SELECT, INSERT, UPDATE or DELETE statements are executed to retrieve from, or store data in, at table, all of the operations are carried out at once, in bulk. This avoids the context-switching you get when the PL/SQL engine has to pass over to the SQL engine, then back to the PL/SQL engine, and so on, when you individually access rows one at a time. To do bulk binds with Insert, Update and Delete statements, you enclose the SQL statement within a PL/SQL FORALL statement. To do bulk binds with Select statements, you include the Bulk Collect INTO a collection clause in the SELECT Statement instead of using Simply into . Collections, BULK COLLECT and FORALL are the new features in Oracle 8i, 9i and 10g PL/SQL that can really make a different to you PL/SQL performance Bulk Binding is used for avoiding the context switching between the sql engine and pl/sql engine. If we use simple For loop in pl/sql block it will do context switching between sql and pl/sql engine for each row processing that degrades the performance of pl/sql bloack. So that for avoiding the context switching betn two engine we user FORALL keyword by using the collection pl/sql tables for DML. forall is pl/sql keyword. It will provides good result and performance increase. 47.Why Functions are used in oracle ?Can Functions Return more than 1 values?Why Procedures are used in oracle ?What are the Disadvantages of packages?What are the Global Variables in Packages? The functions are used where we can't used the procedure.i.e we can use a function the in select statments,in the where clause of delete/update statments.But the procedure can't used like that. It is true that function can return only one value, but a function can be used to return more than one value,by using out parameters and also by using ref cursors.

  • There is no harm in using the out parameter,when functins are used in the DML statements we can't used the out parameter(as per rules). 49. What are the restrictions on Functions ? Function cannot have DML statemets and we can use select statement in function If you create function with DML statements we get message function will be created But if we use in select statement we get error 50. What happens when a package is initialized ? when a package is initialised that is called for the first time the entire package is loaded into SGA and any variable declared in the package is initialises. 52. What is PL/SQL table? Pl/Sql table is a type of datatype in procedural language Extension.It has two columns.One for the index,say Binary index And another column for the datas,which might further extend to any number of rows (not columns)in future. PL/SQL table is nothing but one dimensional array. It is used to hold similar type of data for temporary storage. Its is indexed by binary integer. 3. can i write plsql block inside expection Yes you can write PL/SQL block inside exception section. Suppose you want to insert the exception detail into your error log table, that time you can write insert into statement in exception part. To handle the exception which may be raised in your exception part, you can write the PL/SQL code in

    exception part. 54. Can e truncate some of the rows from the table instead of truncating the full table. You can truncate few rows from a table if the table is partitioned. You can truncate a single partition and keep remaining. CREATE TABLE parttab ( state VARCHAR2(2), sales NUMBER(10,2)) PARTITION BY LIST (state) ( PARTITION northwest VALUES ('OR', 'WA') TABLESPACE uwdata, PARTITION southwest VALUES ('AZ', 'CA') TABLESPACE uwdata); INSERT INTO parttab VALUES ('OR', 100000); INSERT INTO parttab VALUES ('WA', 200000); INSERT INTO parttab VALUES ('AZ', 300000); INSERT INTO parttab VALUES ('CA', 400000); COMMIT; SELECT * FROM parttab; ALTER TABLE parttab TRUNCATE PARTITION southwest; SELECT * FROM parttab; 56. What is the difference between a reference cursor and normal cursor ? REF cursors are different than your typical, standard cursors. With standard cursors, you know the cursor's query ahead of time. With REF cursors, you do not have to know the query ahead of time. With REF Cursors, you can build the cursor on the fly Normal Cursor is a Static Cursor. Refernce Cursor is used to create dynamic cursor. There are two types of Ref Cursors: 1. Weak cursor and 2.Strong cursor Type ref_name is Ref cursor [return type] [return type] means %Rowtype if Return type is mentioned then it is Strong cursor else weak cursor

  • The Reference cursor does not support For update clause. Normal cursor is used to process more than one record in plsql. Refcusor is a type which is going to hold set of records which can be sent out through the procedure or function out variables. we can use Ref cursor as an IN OUT parameter . 58. Based on what conditions can we decide whether to use a table or a view or a materialized view ? Table is the basic entity in any RDBMS , so for storing data you need table . for view - if you have complex query from which you want to extract data again and again , moreover it is a standard data which is required by many other user also for REPORTS generation then create view . Avoid to insert / update / delete through view unless it is essential. keep view as read only (FOR SHOWING REPORTS) for materialized view - this view ia mainly used in datawarehousing . if you have two databases and you want a view in both databases , remember in datawarehousing we deal in GB or TB datasize . So create a summary table in a database and make the replica(materialized view) in other database. when to create materialized view- [1] if data is in bulk and you need same data in more than one database then create summary table at one database and replica in other databases [2] if you have summary columns in projection list of query. main advatages of materialized view over simple view are - [1] it save data in database whether simple view's definition is saved in database [2] can create parition or index on materialize view to enhance the performance of view , but cannot on simple view. 59. What is the difference between all_ and user_ tables ? An ALL_ view displays all the information accessible to the current user, including information from

    the current user's schema as well as information from objects in other schemas, if the current user has access to those objects by way of grants of privileges or roles. While

    A USER_ view displays all the information from the schema of the current user. No special

    privileges are required to query these views. User_tables data dictionary contains all the tables created by the users under that schema. whereas All_tables stores all the tables created in different schema. If any user id have the Grants for access table of diff. schema then he can see that table through this dictionary. 61. what is p-code and sourcecode ? P-code is Pre-complied code stored in Public cache memory of System Global Area after the Oracle instance is started, whereas sourcecode is a simple code of sp, package, trigger, functions etc which are stored in Oracle system defined data dictionary. Every session of oracle access the p-code which have the Execute permission on that objects. Source code stored in user_objects data dictinary for user defined Store proc, Trigger, Package, Function. DBA_object stores all the db objects in sp. DB. ALL_objects stores all the db objects in sp. schema. Source code: The code say a PLSQL block that the user types for the exectionP-Code: The source code after -Syntax check, Parse tree generation, Symantic check, and further execution of the parse tree..giving the final P-code ready for data fetch or manipulation ... 63. Is there any limitation on no. of triggers that can be created on a table? There is no limit on number of triggers on one table. you can write as many u want for insert,update or delte by diff names. if table has got n columns. we can create n triggers based on each column. 64.What happens when DML Statement fails?A.User level rollbackB.Statement Level RollbackC.Sustem evel Rollback When a DML statement executes (fails/sucess) an automatic Commit is executed. Eg : Create a

    table t1. Insert a record in t1. Then again to create the same object t1.

  • 65.What steps should a programmer should follow for better tunning of the PL/SQL blocks? SQL Queries Best Practices

    1. Always use the where clause in your select statement to narrow the number of rows returned.

    If we dont use a where clause, the Oracle performs a full table scan on our table and returns all of the rows.

    2. Use EXISTS clause instead of IN clause as it is more efficient than IN and performs faster. Ex: Replace SELECT * FROM DEPT WHERE DEPTNO IN (SELECT DEPTNO FROM EMP E)

    With SELECT * FROM DEPT D WHERE EXISTS

    (SELECT 1 FROM EMP E WHERE D.DEPTNO = E.DEPTNO) Note: IN checks all rows. Only use IN if the table in the sub-query is extremely small.

    3. When you have a choice of using the IN or the BETWEEN clauses in your SQL, use the BETWEEN clause as it is much more efficient than IN.

    Depending on the range of numbers in a BETWEEN, the optimizer will choose to do a full table scan or use the index.

    4. Avoid WHERE clauses that are non-sargable. Non-sargable search arguments in the WHERE clause,

    such as "IS NULL", "OR", "", "!=", "!>", "!

  • SELECT * FROM EMP WHERE SUBSTR (ENAME, 1, 3) = KES Use the LIKE function instead of SUBSTR ()

    13. If you want the index used, dont perform an operation on the field.

    Replace SELECT * FROM EMPLOYEE WHERE SALARY +1000 = :NEWSALARY With SELECT * FROM EMPLOYEE WHERE SALARY = :NEWSALARY 1000

    14. All SQL statements will be in mixed lower and lower case. All reserve words will be capitalized and all

    user-supplied objects will be lower case. (Standard)

    15. Minimize the use of DISTINCT because it forces a sort operation. 16. Try joins rather than sub-queries which result in implicit joins Replace SELECT * FROM A WHERE A.CITY IN (SELECT B.CITY FROM B) With SELECT A.* FROM A, B WHERE A.CITY = B.CITY

    17. Replace Outer Join with Union if both join columns have a unique index: Replace SELECT A.CITY, B.CITY FROM A, B WHERE A.STATE=B.STATE (+) With SELECT A.CITY, B.CITY FROM A, B WHERE A.STATE=B.STATE UNION SELECT NULL, B.CITY FROM B WHERE NOT EXISTS (SELECT 'X' FROM A.STATE=B.STATE) 18. Use bind variables in queries passed from the application (PL/SQL) so that the same query can be reused. This avoids parsing. 19. Use Parallel Query and Parallel DML if your system has more than 1 CPU. 20. Match SQL where possible. Applications should use the same SQL statements wherever possible to take advantage of Oracle's Shared SQL Area. The SQL must match exactly to take advantage of this. 21. No matter how many indexes are created, how much optimization is done to queries or how many caches and buffers are tweaked and tuned if the design of a database is faulty, the performance of the overall system suffers. A good application starts with a good design. 22. The following operations always require a sort: SELECT DISTINCT SELECT UNIQUE SELECT ....ORDER BY... SELECT....GROUP BY... CREATE INDEX CREATE TABLE.... AS SELECT with primary key specification

  • Use of INTERSECT, MINUS, and UNION set operators Unindexed table joins Some correlated sub-queries Also the order in which the conditions are given in the 'WHERE' cluase are very important while performing a 'Select' query. The Performance Difference is unnoticed ifother wise the query is run on a Massive Database. For example for a select statement, SELECT Emp_id FROM Emp_table WHERE Last_Name = 'Smith' AND Middle_Initial = 'K' AND Gender = 'Female'; The look up for matches in the table is performed by taking the conditions in the WHERE cluase in the reverse order i.e., first all the rows that match the criteria Gender = 'Female' are returned and in these returned rows, the conditon Last_Name = 'Smith' is looked up. There fore, the order of the conditions in the WHERE clause must be in such a way that the last condition gives minimum collection of potential match rows and the next condition must pass on even little and so on. So, if we fine tune the above query, it should look like, SELECT Emp_id FROM Emp_table WHERE Gender = 'Female' AND Middle_Initial = 'K' AND Last_Name = 'Smith' ; as Last_Name Smith would return far more less number of rows than Gender = 'Female' as in the former case. 66.what is difference between varray and nested table.can u explain in brief and clear my these concepts.also give a small and sweet example of both these. Varry and Nestead table both are belongs to CollectionsThe Main difference is Varray has Upper bound, where as Nestead table doesn't. It's size is unconstrained like any other database tableNestead table can be stored in DatabaseSyntax of Nestead TableTYPE nes_tabtype IS TABLE OF emp.empno%type;nes_tab nes_tabtype;Syntax of VarryTYPE List_ints_t IS VARRAY(8) OF NUMBER(2);aList List_ints_t:=List_ints_t(2,3,5,1,5,4); Nested table can be indexed where as VArray can't. 69. What is PL/Sql tables?Is cursor variable store in PL/SQL table? pl/sql table is temparary table which is used to store records temrparaily in PL/SQL Block, whenever block completes execution, table is also finished. 71. What is the DATATYPE of PRIMARY KEY Binary Integer 72.What is the difference between User-level, Statement-level and System-level Rollback? Can you please give me example of each? 1. System - level or transaction level Rollback the current transaction entirely on errors. This was the unique behavior of old drivers becauase PG has no savepoint functionality until 8.0. 2. Statement Rollback the current (ODBC) statement on errors (in case of 8.0 or later version servers). The driver calls a SAVEPOINT command just before starting each (ODBC) statement and automatically ROLLBACK to the savepoint on errors or RELEASE it on success. If you expect Oracle-like automatic per statement rollback, please use this level. 3. User Level You can(have to) call some SAVEPOINT commands and rollback to a savepoint on errors by yourself. Please note you have to rollback the current transcation or ROLLBACK to a savepoint on errors (by yourself) to continue the application 74. Details about FORCE VIEW why and we can use Generally we are not supposed to create a view without base table. If you want to create any view

  • without base table that is called as Force View or invalid view. Syntax: CREATE FORCE VIEW AS < SELECT STATMENT >; That View will be created with the message View created with compilation errors Once you create the table that invalid view will become as valid one. 75. 1) Why it is recommonded to use INOUT instead of OUT parameter type in a procedure? 2) What happen if we will not assign anything in OUT parameter type in a procedure? Hi,OUT parameter will be useful for returning the value from subprogram, value can be assigned only once and this variable cannot be assigned to another variable.IN OUT parameter will be used to pass the value to subprogram and as well as it can be used to return the value to caller of subprogram. It acts as explicitly declared variable. Therefore it can be assigned value and its value can be assigned to another variable.So IN OUT will be useful than OUT parameter.

    1) IN OUT and OUT selection criteria depends upon the program need.if u want to retain the value that is being passed then use seperate (IN and OUT)otherwise u can go for IN OUT.2)If nothing is assigned to a out parameter in a procedure then NULL will be returned for that parameter. 78. What is autonomous Transaction? Where are they used? Autonomous transaction is the transaction which acts independantly from the calling part and could commit the process done. example using prgma autonomous incase of mutation problem happens in a trigger. 79. How can I speed up the execution of query when number of rows in the tables increased Standard practice is - 1. Indexed the columns (Primary key) 2. Use the indexed / Primary key columns in the where clause 3. check the explain paln for the query and avoid for the nested loops / full table scan (depending on the size of data retrieved and / or master table with few rows) 80. What is the purpose of FORCE while creating a VIEW usually the views are created from the basetable if only the basetable exists. The purpose of FORCE keyword is to create a view if the underlying base table doesnot exists. ex : create or replace FORCE view as while using the above syntax to create a view the table used in the query statement doesnot necessary to exists in the database 83. What is Mutation of a trigger? why and when does it oocur? A table is said to be a Mutating table under the following three circumstances 1) When u try to do delete, update, insert into a table through a trigger and at the same time u r trying to select the same table. 2) The same applies for a view 3) Apart from that, if u r deleting (delete cascade),update,insert on the parent table and doing a select in the child tableAll these happen only in a row level trigger 90. How to handle exception in Bulk collector? During bulk collect you can save the exception and then you can process the exception. Look at the below given example: DECLARE TYPE NumList IS TABLE OF NUMBER;

    num_tab NumList := NumList(10,0,11,12,30,0,20,199,2,0,9,1);

    errors NUMBER;

    BEGIN FORALL i IN num_tab.FIRST..num_tab.LAST

    SAVE EXCEPTIONS

    DELETE * FROM emp WHERE sal > 500000/num_tab(i);

    EXCEPTION WHEN OTHERS THEN -- this is not in the doco, thanks to JL for

    pointing this out

    errors := SQL%BULK_EXCEPTIONS.COUNT;

    dbms_output.put_line('Number of errors is ' || errors);

  • FOR i IN 1..errors LOOP -- Iteration is

    SQL%BULK_EXCEPTIONS(i).ERROR_INDEX; -- Error code is

    SQL%BULK_EXCEPTIONS(i).ERROR_CODE;

    END LOOP;END;

    91.#1 What are the advantages and disadvantages of using PL/SQL or JAVA as the primary programming tool for database automation. #2 Will JAVA replace PL/SQL? Internally the Oracle database supports two procedural languages, namely PL/SQL and Java. This leads to questions like "Which of the two is the best?" and "Will Oracle ever desupport PL/SQL in favour of Java?". Many Oracle applications are based on PL/SQL and it would be difficult of Oracle to ever desupport PL/SQL. In fact, all indications are that PL/SQL still has a bright future ahead of it. Many enhancements are still being made to PL/SQL. For example, Oracle 9iDB supports native compilation of Pl/SQL code to binaries.

    PL/SQL and Java appeal to different people in different job roles. The following table briefly describes the difference between these two language environments:

    PL/SQL:

    Data centric and tightly integrated into the database Proprietary to Oracle and difficult to port to other database systems Data manipulation is slightly faster in PL/SQL than in Java Easier to use than Java (depending on your background) Java:

    Open standard, not proprietary to Oracle Incurs some data conversion overhead between the Database and Java type systems Java is more difficult to use (depending on your background) 110. 1.What is bulk collect? 2.What is instead trigger 3.What is the difference between Oracle table & PL/SQL table? 4.What R built in Packages in Oracle? 5.what is the difference between row migration & row changing?

    1.What is bulk collect? Bulk collect is part of PLSQL collection where data is stored/ poped up into a variable. example: declare type sal_rec is table of number; v_sal sal_rec; begin select sal bulk collect into v_sal from emp; for r in 1.. v_sal.count loop dbms_output.put_line(v_sal(r)); end loop; end; 2.What is instead trigger instead triggers are used for views. 3.What is the difference between Oracle table & PL/SQL table? Table is logical entity which holds the data in dat file permanently . where as scope of plsql table is limited to the particular block / procedure . refer above example sal_rec table will hold data only till programme is reaching to end; 4.What R built in Packages in Oracle?

  • There R more then 1000 oracle builtin packges like: Dbms_output, dbms_utility dbms_pipe ............. 5.what is the difference between row migration & row changing? Migration: The data is stored in blocks whic use Pctfree 40% and pctused 60% ( normally). The 40% space is used for update and delete statements . when a condition may arise that update/delete statement takes more then pctfree then it takes the space from anther block. this is called migration. RowChaining: while inserting the data if data of one row takes more then one block then this row is stored in two blocks and rows are chained. insted of triggers: They provide a transparent way of modifying view that can't be modified directly through SQL,DML statement. 111.Can anyone tell me the difference between instead of trigger, database trigger, and schema trigger? INSTEAD OF Trigger control operation on view , not table. They can be used to make non-updateable views updateable and to override the behvior of view that are updateable. Database triggers fire whenever the database startup or is shutdown, whenever a user logs on or log off, and whenever an oracle error occurs. these tigger provide a means of tracking activity in the database if we have created a view that is based on join codition then its not possibe to apply dml operations like insert, update and delete on that view. So what we can do is we can create instead off trigger and perform dml operations on the view. 131. HI,What is Flashback query in Oracle9i...? Flahsback is used to take your database at old state like a system restore in windows. No DDL and DML is allowed when database is in flashback condition. user should have execute permission on dbms_flashback package for example: at 1030 am from scott user : delete from emp; commit; at 1040 am I want all my data from emp table then ? declare cursor c1 is select * from emp; emp_cur emp%rowtype; begin dbms_flashback.enable_at_time(sysdate - 15/1440); open c1; dbms_flashback.disable; loop fetch c1 into emp_cur; exit when c1%notfound; insert into emp values(emp_cur.empno, emp_cur.ename, emp_cur.job, emp_cur.mgr,emp_cur.hiredate, emp_cur.sal, emp_cur.comm, emp_cur.deptno); end loop; commit; end; / select * from emp; 14 rows selected

  • 132. what is the difference between database server and data dictionary Database server is collection of all objects of oracle Data Dictionary contains the information of for all the objects like when created, who created etc. Database server is a server on which the instance of oracle as server runs..whereas datadictionary is the collection of information about all those objects like tables indexes views triggers etc in a database.. 134. Mention the differences between aggregate functions and analytical functions clearly with examples? Aggregate functions are sum(), count(), avg(), max(), min() like: select sum(sal) , count(*) , avg(sal) , max(sal) , min(sal) from emp; analytical fuction differ from aggregate function some of examples: SELECT ename "Ename", deptno "Deptno", sal "Sal", SUM(sal) OVER (ORDER BY deptno, ename) "Running Total", SUM(SAL) OVER (PARTITION BY deptno ORDER BY ename) "Dept Total", ROW_NUMBER() OVER (PARTITION BY deptno ORDER BY ENAME) "Seq" FROM emp ORDER BY deptno, ename SELECT * FROM ( SELECT deptno, ename, sal, ROW_NUMBER() OVER ( PARTITION BY deptno ORDER BY sal DESC ) Top3 FROM emp ) WHERE Top3
  • With the new NOCOPY option, OUT and IN OUT parameters are passed by reference, which avoids

    copy overhead. However, parameter set copy is not created and, in case of an exception rollback, cannot be performed and the original values of parameters cannot be restored.

    Here is an example of using the NOCOPY parameter option:

    TYPE Note IS RECORD( Title VARCHAR2(15), Created_By

    VARCHAR2(20), Created_When DATE, Memo VARCHAR2(2000));TYPE Notebook IS VARRAY(2000) OF Note;CREATE OR REPLACE PROCEDURE Update_Notes(Customer_Notes

    IN OUT NOCOPY Notebook) ISBEGIN ...END;

    NOCOPY is a hint given to the compiler, indicating that the parameter is passed as a reference and hence actual value should not be copied in to the block and vice versa. The processing will be done accessing data from the original variable. (Which other wise, oracle copies the data from the parameter variable into the block and then copies it back to the variable after processing. This would put extra burdon on the server if the parameters are of large collections/sizes) For better understanding of NOCOPY parameter, I will suggest u to run the following code and see the result. DECLARE n NUMBER := 10; PROCEDURE do_something ( n1 IN NUMBER, n2 IN OUT NUMBER, n3 IN OUT NOCOPY NUMBER) IS BEGIN n2 := 20; DBMS_OUTPUT.PUT_LINE(n1); -- prints 10 n3 := 30; DBMS_OUTPUT.PUT_LINE(n1); --