Sunday, June 7, 2009

Oracle SQL interview questions-1

Oracle Basic Interview Questions:

1, deleting the duplicate records from the table

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

2)

delete from vasu where

rowid in(

select rid

from

(

select rowid rid,

row_number() over (partition by name order by rowid desc) top

from vasu )

where top<>1

)

Test Case 1 - Basic Delete

delete from artist_test

where SECOND_COLL='JAVA CLASS';



Test Case 2 - Delete with PLSQL and forall loop, committing only once

DECLARE

TYPE artist_value IS TABLE OF VARCHAR2(1000) INDEX BY BINARY_INTEGER;

del_value artist_value;

rowkey PLS_INTEGER;

BEGIN

SELECT rowid BULK COLLECT INTO del_value FROM artist_test WHERE SECOND_COLL='JAVA CLASS';

IF del_value IS NOT NULL THEN

FORALL rowkey IN del_value.FIRST..del_value.LAST

DELETE artist_test WHERE rowid = del_value(rowkey);

commit;

END IF;

END;

/

Test Case 3 - Delete using anonymous PL/SQL block, looping through the cursor, and deleting one tow at a time. Loop has counter, programmed to trigger commit after each 1000 records.

SQL> declare

rec_read number(6) := 0;

rec_rest number(6) := 0;

vc_var_out varchar2(41) := 'Delete Archive Data';

cursor rec_sql is select SECOND_COLL,rowid from artist_test

where SECOND_COLL='JAVA CLASS' order by SECOND_COLL,rowid;

begin

for rec_sql_run in rec_sql loop

rec_read := rec_read + 1 ;

rec_rest := rec_rest + 1 ;

delete from artist_test A where A.rowid = rec_sql_run.rowid ;

if rec_rest > 1000 THEN

COMMIT;

rec_rest := 1;

dbms_output.put_line('COMMIT AT..'|| rec_read);

END IF;

end loop;

end;

/

Test Case 4
a.) Deleting using PL/SQL stored procedure, commit each 1000 records. ( exec delete_table(1000))
b.) Deleting using PL/SQL stored procedure, commit only once ( exec delete_table(100000))

CREATE OR REPLACE PROCEDURE delete_table (commit_size in number default 1000) is

sel_id INTEGER;

del_id INTEGER;

exec_sel INTEGER;

exec_del INTEGER;

cur_stmt VARCHAR2(2000);

del_rowid ROWID;

BEGIN

cur_stmt := 'SELECT rowid FROM artist_test where SECOND_COLL=''JAVA CLASS''';

sel_id := DBMS_SQL.OPEN_CURSOR;

DBMS_SQL.PARSE(sel_id,cur_stmt,dbms_sql.v7);

DBMS_SQL.DEFINE_COLUMN_ROWID(sel_id,1,del_rowid);

exec_sel := DBMS_SQL.EXECUTE(sel_id);

del_id := DBMS_SQL.OPEN_CURSOR;

DBMS_SQL.PARSE(del_id,'delete from artist_test where rowid = :del_rowid',dbms_sql.v7);

LOOP

IF DBMS_SQL.FETCH_ROWS(sel_id) >0 THEN

DBMS_SQL.COLUMN_VALUE(sel_id,1,del_rowid);

DBMS_SQL.BIND_VARIABLE(del_id,'del_rowid',del_rowid);

exec_del := DBMS_SQL.EXECUTE(del_id);

if mod(dbms_sql.last_row_count,commit_size) = 0

then

COMMIT;

end if;

ELSE

exit;

END IF;

END LOOP;

COMMIT;

DBMS_SQL.CLOSE_CURSOR(sel_id);

DBMS_SQL.CLOSE_CURSOR(del_id);

END;

/

Test Case 5 - Delete using standard anonymous PL/SQL block, using execute immediate function and committing only once.

SQL > declare

proc_rows number := 0;

begin

execute immediate 'begin

delete from artist_test where SECOND_COLL=''JAVA CLASS'';

:x :=sql%rowcount;

commit;

end;'

using OUT proc_rows;

dbms_output.put_line('Records processed........'|| proc_rows);

end;

/

Multiple Insert Statement :

insert all

into vasu values ('vasumathi',28)

into vasu values ('vasumathi',34)

into vasu values ('murugesh',32)

into vasu values ('murugesh',34)

select * from dual;

insert into tableX (F1, F2)

5 select 'A', 2 from dual

6 union all

7 select 'B', 2 from dual

8 union all

9 select 'C', 2 from dual;

10 commit;

2. Difference between Union and Union all statement

Union and union all are the set operators and union will eliminate the duplicate records and Union all display all the records

3. What is Index & there types and which is used

Index

Oracle9i uses indexes to avoid the need for large-table, full-table scans and disk sorts, which are required when the SQL optimizer cannot find an efficient way to service the SQL query.

Types of Indexes:

1. normal/B-Tree (balanced/ binary tree) indexes;

2. Bitmap indexes (which literally use a map of bits to represent the whole index and are most often used in data warehouses);

3. function-based indexes (which are based
on the value of an expression instead of the value of a column);

4. Partitioned indexes (tables and indexes may be partitioned separately) and

Local Index

Global Index

5. Domain indexes (application-specific indexes created on complex data types such as spatial data). This article only discusses bitmap and normal (b-tree) indexes.

4. Referential Integrity and their purpose:

Referential integrity (RI) rules ensure that one-to-many and many-to-many relationships are enforced within the relational schema

This is the foreign key constraint as implemented by Oracle. References constraint is only applied at SQL insert and delete times. For example, assume a one-to-many relationship between the Consumer_account_cur EMPLOYEE and consumer_account_prods_cur DEPENDENT tables; each consumer employee may have many products dependents, yet each product dependent belongs to only one consumer employee. The references constraint tells Oracle at insert time that the value in DEPENDENT.emp_num must match the EMPLOYEE.emp_num in the employee row, thereby ensuring that a valid consumer employee exists before the product dependent row is added. At SQL delete time, the references constraint can be used to ensure that an consumer employee is not deleted, if rows still exist in the product DEPENDENT table

This foreign key column establishes a direct relationship with a primary key or unique key column (referenced key) usually in another table. The table containing the foreign key is referred to as the child, and the table containing the referenced key is the parent table. The foreign key and referenced key can be in the same table (parent and child are the same table); otherwise, the parent and child tables must be in the same database.

5. What is merge statement? Where it’s used?

Use the MERGE statement to select rows from one or more sources for update or insertion into a table or view. You can specify conditions to determine whether to update or insert into the target table or view.

This statement is a convenient way to combine multiple operations. It lets you avoid multiple INSERT, UPDATE, and DELETE DML statements.

Optional and conditional

MERGE INTO test1 a

USING all_objects b

ON (a.object_id = b.object_id)

WHEN MATCHED THEN

UPDATE SET a.status = b.status

WHEN NOT MATCHED THEN

INSERT (object_id, status)

VALUES (b.object_id, b.status);

MERGE INTO test1 a

USING all_objects b

ON (a.object_id = b.object_id)

WHEN MATCHED THEN

UPDATE SET a.status = b.status

WHERE b.status != 'VALID'

WHEN NOT MATCHED THEN

INSERT (object_id, status)

VALUES (b.object_id, b.status)

WHERE b.status != 'VALID';

MERGE INTO test1 a

USING all_objects b

ON (a.object_id = b.object_id)

WHEN MATCHED THEN

UPDATE SET a.status = b.status

WHERE b.status != 'VALID'

DELETE WHERE (b.status = 'VALID');

6. Partition and their concepts

Oracle can partition along multiple dimensions, such as partitioning by date

along one dimension, and by region along another dimension. Oracle provides

several other partitioning schemes, to accommodate all types of business

scenarios.

Oracle database capabilities. For example, in addition to storing older data on less

expensive storage, the older data could also be compressed thus further reducing

storage costs. The newer data (in separate partitions) remains uncompressed to

optimize access and updates

7. Difference between Oracle 9i & 10g and 11g

1.Simplified and improved automatic memory management
2.New fault diagnosability infrastructure to prevent, detect, diagnose, and help
resolve critical database errors
3.Invisible Indexes
4.Virtual columns
5.Enhanced security for password-based authentication by enabling use of mixed
case in passwords.
6.Tablespace-level encryption
7.Ability to online redefine tables that have materialized view logs

8. How to execute the SQL in Unix

To execute sqlplus via Unix shell scripts the following parameters need to be initialized.

(1.) ORACLE_HOME

export ORACLE_HOME Path to

(2.) ORACLE_SID

export ORACLE_SID Actual ORACLE_SID

After these initializations have been done use sqlplus -v to login into the database non interactively and execute the SQL or PL/SQL Code.

sqlplus -v ${USERNAME}/${PASSWORD}@${ORACLE_SID} << EOF
@mysqlfile.sql
EOF

9. What are the Analytical Functions do u used?

Function(arg1,..., argn) OVER ( [PARTITION BY <...>] [ORDER BY <....>] [] )

ROW_NUMBER, RANK and DENSE_RANK

10. What are constraints?

  • Oracle "Check" Constraint: This constraint validates incoming columns at row insert time. For example, rather than having an application verify that all occurrences of region are North, South, East, or West, an Oracle check constraint can be added to the table definition to ensure the validity of the region column.
  • Not Null Constraint: This Oracle constraint is used to specify that a column may never contain a NULL value. This is enforced at SQL insert and update time.
  • Primary Key Constraint: This Oracle constraint is used to identify the primary key for a table. This operation requires that the primary columns are unique, and this Oracle constraint will create a unique index on the target primary key.
  • References Constraint: This is the foreign key constraint as implemented by Oracle. A references constraint is only applied at SQL insert and delete times. At SQL delete time, the references Oracle constraint can be used to ensure that an employee is not deleted, if rows still exist in the DEPENDENT table.
  • Unique Constraint: This Oracle constraint is used to ensure that all column values within a table never contain a duplicate entry.

11. Difference between primary key and unique key?

  • Primary Key Constraint: This Oracle constraint is used to identify the primary key for a table. This operation requires that the primary columns are unique, and this Oracle constraint will create a unique index on the target primary key.
  • Unique Constraint: This Oracle constraint is used to ensure that all column values within a table never contain a duplicate entry.

12. What is temporary table?

Private to a session

Retain data only for the duration or session

No DML Locks

No redo generation

CREATE GLOBAL TEMPORARY TABLE emp_temp

AS SELECT * FROM emp;

ON COMMIT {PRESERVE|DELETE} ROWS;

13. What is Clustered Table?

Clustered Table

Group of tables sharing common columns

Cluster key is used to identify the rows needed to store together

Cluster key is independent of primary key

14. What is decode statement and when it’s used?

SELECT supplier_name,

decode(supplier_id,

10000,

'IBM',

10001,

'Microsoft',

10002,

'Hewlett Packard',

'Gateway') result

FROM suppliers;

IF supplier_id = 10000 THEN
result := 'IBM';

ELSIF supplier_id = 10001 THEN
result := 'Microsoft';

ELSIF supplier_id = 10002 THEN
result := 'Hewlett Packard';

ELSE
result := 'Gateway';

END IF;

14. What is the difference between count (*) and count (1)?

There is difference, Count(*) is slower than count(1) query. using Count(1) improves performance and its substantial in case of tables > 20K rows

15. Difference between Truncate and Delete?

[1] DELETE - is a DML Command & TRUNCATE - is a DDL Command

[2] After DELETE - can rollback the Records & After TRUNATE - cannot rollback the records

[3] In DELETE Command you can give the conditions in WHERE Clause & In TRUNCATE you cannot give conditions

[4] After using DELETE Command The memory will be occupied till the user does not give ROLLBACK or COMMIT & After using TRUNCATE Command The memory realeased immediately

16. What is a pseudo column? Give some examples?

pseudo column is a column that
is not present in the database.
it is used for unique identification of rows like
ROWNUM,ROWID,LEVEL,NEXTVAL,CURVAL,NULL etc.

17. What is analyze and their purpose?

18.How do u insert multiple inserts?

19. Flat file loading process?

20. What is transaction statement?

A transaction is a sequence of SQL statements that Oracle treats as a single unit of work. Once the transaction begins, every SQL DML (Data Manipulation Language) statement you issue subsequently becomes a part of this transaction. A transaction ends when you disconnect from the database, or when you issue a COMMIT or ROLLBACK command.

COMMIT makes permanent any database changes you made during the current transaction. Until you commit your changes, other users cannot see them. ROLLBACK ends the current transaction and undoes any changes made since the transaction began

A database transaction is a group of SQL statements that are a logical unit of work. You can think of a transaction as an inseparable set of SQL statements that should be made permanent in the database (or undone) as a whole. An example would be a transfer of money between bank accounts: One UPDATE statement would subtract from the total amount of money from one account, and another UPDATE would add money to the other account. Both the subtraction and the addition must either be permanently recorded in the database, or they both must be undoneotherwise money will be lost. This simple example uses only two UPDATE statements, but a more realistic transaction may consist of many INSERT, UPDATE, and DELETE statements.

To permanently record the results of the SQL statements in a transaction, you perform a commit with the COMMIT statement. To undo the results of the SQL statements, you perform a rollback with the ROLLBACK statement, which resets all the rows back to what they were originally. Any changes you make prior to performing a rollback will be undone, as long as you haven't disconnected from the database beforehand. You can also set a savepoint that may be used to rollback a transaction to a specific point, while leaving the other statements in the transaction intact.

21. What is dead lock and how do u overcome this?

deadlock refers to a specific condition when two or more processes are each waiting for each other to release a resource, or more than two processes are waiting for resources in a circular chain (see Necessary conditions). Deadlock is a common problem in multiprocessing where many processes share a specific type of mutually exclusive resource known as a software, or soft, lock.

we can avoid deadlock by avoiding the following conditions:

1. Mutual Exclusion

2. Hold and wait.

3. No preemption.

4. Circular wait.

22. What is the difference between rownum,rowid

rowid has a physical significance i.e you can read a row if you know rowid. It is complete physical address of a row.

While rownum is temporary serial number allocated to each returned row during query execution.

Rownum is numeric and rowid is 16 bit hexadecimal no.

23. What is synapshot?

A snapshot is a read-only copy of a master table / output of a query

based on multiple tables located on a remote location.Once these are read only so can not have DML statments. Yes they can be refeshed periodically based the condition defined while creating the snapshot. Advance version of snapshot is materialized views.

A snapshot is a read-only copy of a master table located on a remote node. Snapshots can be queried but not updated; only the master table can be updated. Snapshots are periodically refreshed to reflect changes made to the master table.

24. Write a query that displays the difference between the highest and lowest salaries. Label the column

select max(sal)-min(sal) difference from emp;

25.What are various joins used while writing SUBQUERIES

Self join-Its a join foreign key of a table references the same table.
Outer JoinIts a join condition used where One can query all the rows of one of the tables in the join condition even though they dont satisfy the join condition.
Equi-joinIts a join condition that retrieves rows from one or more tables in which one or more columns in one table are equal to one or more columns in the second table.

26. What are various constraints used in SQL

NULL
NOT NULL
CHECK
DEFAULT

What is a CO-RELATED SUBQUERY

A CO-RELATED SUBQUERY is one that has a correlation name as table or view designator in the FROM clause of the outer query and the same correlation name as a qualifier of a search condition in the WHERE clause of the subquery.
2. eg
3. SELECT field1 from table1 X
4. WHERE field2>(select avg(field2) from table1 Y
5. where
field1=X.field1);
(The subquery in a correlated subquery is revaluated for every row of the table or view named in the outer query.)

What are various joins used while writing SUBQUERIES

Self join-Its a join foreign key of a table references the same table.
Outer JoinIts a join condition used where One can query all the rows of one of the tables in the join condition even though they dont satisfy the join condition.
Equi-joinIts a join condition that retrieves rows from one or more tables in which one or more columns in one table are equal to one or more columns in the second table.

What are various constraints used in SQL

NULL
NOT NULL
CHECK
DEFAULT

What are different Oracle database objects

TABLES
VIEWS
INDEXES
SYNONYMS
SEQUENCES
TABLESPACES etc

What is difference between Rename and Alias

Rename is a permanent name given to a table or column whereas Alias is a temporary name given to a table or column which do not exist once the SQL statement is executed.

What is a view

A view is stored procedure based on one or more tables, its a virtual table.

What are various privileges that a user can grant to another user

SELECT
CONNECT
RESOURCE

What is difference between UNIQUE and PRIMARY KEY constraints

A table can have only one PRIMARY KEY whereas there can be any number of UNIQUE keys. The columns that compose PK are automatically define NOT NULL, whereas a column that compose a UNIQUE is not automatically defined to be mandatory must also specify the column is NOT NULL.

Can a primary key contain more than one columns

Yes

How you will avoid duplicating records in a query

By using DISTINCT

What is difference between SQL and SQL*PLUS

SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and reporting tool. Its a command line tool that allows user to type SQL commands to be executed directly against an Oracle database. SQL is a language used to query the relational database(DML,DCL,DDL). SQL*PLUS commands are used to format query result, Set options, Edit SQL commands and PL/SQL.

Which datatype is used for storing graphics and images

LONG RAW data type is used for storing BLOBs (binary large objects).

How will you delete duplicating rows from a base table

CREATE TABLE new_table AS SELECT DISTINCT * FROM old_table;
DROP old_table RENAME new_table TO old_table

DELETE FROM table_name A WHERE rowid NOT IN (SELECT MAX(ROWID) FROM table_name GROUP BY column_name)

What is difference between SUBSTR and INSTR

SUBSTR returns a specified portion of a string eg SUBSTR(BCDEF,4) output BCDE INSTR provides character position in which a pattern is found in a string. eg INSTR(ABC-DC-F,'-,2) output 7 (2nd occurence of - )

1 comment:

  1. Hi Buddy,


    Fully agree on #topic. We’re seeing a lot of projects tackle big complex problems but few seem to have taken into consideration and in particular reasons to adopt.

    I have below kind of data

    Transaction | Debit | Credit | Begening Balance | Ending balance
    INV1 | 100 | | 300 | 400
    INV2 | | 200 | |
    INV3 | 130 | | |
    INV4 | | 150 | |

    This is above data , and we need to calculate begening balance and ending balance.
    Begening balance of INV2 will be ending balance of INV1, and begening balance of INV3
    will be ending balance of INV2, … goes on..
    And ending balance will be calculated as begening balance + debit_amount or begening_balance - credit_amount. but how can i put ending balance of current row to begening_balance of next row.
    Note - First row of begening balance and ending balance will come through gl_balances itself, but need to calculated values from 2nd row.

    Very useful post !everyone should learn and use it during their learning path.


    MuchasGracias,

    ReplyDelete