Friday, July 22, 2016

Pl/Sql Interview Questions Level 2

What is PL/SQL? Describe the block structure of PL/SQL? Advantages of pl/sql ?
PL/SQL is a procedural language designed specifically to embrace SQL statements within its syntax. PL/SQL program units are compiled by the Oracle Database server and are stored inside the database. And at run-time, both PL/SQL and SQL run within the same server process, bringing optimal efficiency. PL/SQL automatically inherits the robustness, security, and portability of the Oracle Database.
PL/SQL is a block-structured language. A PL/SQL block is defined by the keywords DECLARE, BEGIN, EXCEPTION, and END, which break up the block into three sections.

PL/SQL is a completely portable, high-performance transaction processing language that offers the following advantages:
  • Support for SQL
  • Support for object-oriented programming
  • Better performance
  • Higher productivity
  • Full portability
  • Tight integration with Oracle
  • Tight security

What is an anonymous block ?
The PL/SQL anonymous block statement is an executable statement that can contain PL/SQL control statements and SQL statements. The anonymous block statement, which does not persist in the database, can consist of up to three sections: an optional declaration section, a mandatory executable section, and an optional exception section.

Is there a limit on the size of a PL/SQL block ?
Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and the maximum code size is 100K.You can run the following select statement to query the size of an existing package or procedure. SQL> select * from dba_object_size where name = 'procedure_name'

Which Datatypes are available in PL/SQL ?
There are mainly two main Datatypes available in PL/SQL which are further sub-divided into many datatypes and these are:
1. Composite Datatypes: Record, Table, etc.
2. Scalar Datatypes: Date,Number, Boolean, Varchar, Long, Varchar2, etc.

What is the difference between CHAR and VARCHAR2 ?
CHAR is used for storing fixed length string and unused bytes is padded with blank space. While VARCHAR2 is used to store variable length string and consume only used bytes and so it is memory efficient. During comparison of string CHAR type variable need to be trimed using TRIM to remove blank space.
VARCHAR is reserved for future by Oracle.

What are % TYPE and % ROWTYPE ? What are the advantages of using these over datatypes ?
%TYPE provide datatype of a column of a table to a variable while %ROWTYPE provide record datatype that represent a row of a table or view or selected columns of a cursor.
The advantages are: first, no need to know the column datatype while declaring variable and second if the database definition of a column in a table changes, the data type of a variable changes accordingly.

Can we declare a column having number data type and its scale is larger than precision ex: column_name NUMBER(10,100), column_name NUMBAER(10,-84) ?
Yes

What is difference between single row functions and group functions ?
Single-row functions return a single result row for every row of a queried table or view. These functions can appear in select lists, WHERE clauses, START WITH and CONNECT BY clauses, and HAVING clauses. Commonly used single-row function are :
  • Numeric function : ABS, CEIL, FLOOR, LN, LOG, MOD, POWER, REMAINDER, SQRT
  • Characeter function : CHR, CONCAT, LOWER, UPPER, LPAD, RPAD, TRIM, LTRIM, RTRIM, REGEXP_REPLACE, REGEXP_SUBSTR, REGEXP_INSTR, REPLACE, INSTR, SUBSTR, TRANSLATE, ASCII, LENGTH
  • Datetime function : ADD_MONTHS, CURRENT_DATE, CURRENT_TIMESTAMP, MONTHS_BETWEEN, NEW_TIME, NEXT_DAY
  • Conversion function : TO_CHAR, TO_DATE, CAST
  • Collection function : CARDINALITY, COLLECT, POWERMULTISET, POWERMULTISET_BY_CARDINALITY, SET
  • Some miscellaneous function : NVL, DECODE, GREATEST, LEAST

Group functions return a single result row based on groups of rows, rather than on single row. Aggregate Functions like AVG, MIN, MAX, COUNT, SUM, FIRST, LAST and Analytic Functions like LEAD, LAG, RANK, DENSE_RANK are group fucntions.

What is an aggregate function ?
Aggregate functions return a single result row based on groups of rows, rather than on single rows. Aggregate functions can appear in select lists and in ORDER BY and HAVING clauses. They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle Database divides the rows of a queried table or view into groups.

How do you convert a date to a string ?
using TO_CHAR function.

How to convert RAW datatype into TEXT ?
UTL_RAW.cast_to_varchar2 ();

What is difference between SUBSTR and INSTR ?
SUBSTR used to get sub string from a given string while INSTR used to find index or location of a string in a given string.

What is the difference between TRANSLATE and REPLACE ?
REPLACE function replace a string with other string in a given string.
E.g. : REPLACE('IPHONE OR IPHONE','HONE','AD') will produce IPAD OR IPAD
TRANSLATE replaces a sequence of characters in a string with another set of characters. The replacement is done single character at a time.
E.g. : TRANSLATE('IPHONE OR IPHONE','HONE','AD') will produce IPAD DR IPAD

What is the dual table ?
The DUAL table is a special one-row, one-column named DUMMY of type VARCHAR2(1) with value 'X' table present by default. It is usefull for selecting values from some system function like sysdate, TO_DATE etc.

Name few pseduocolumns in oracle ?
rownum, currval, nextval

What is the difference between rowid and rownum ?
rowid is unique hexadecimal code for each row of a table. rownum is pseduo column that represent a number indicating the order in which Oracle selects the row from a table or set of joined rows.

What is difference between DECODE and TRANSLATE ?
TRANSLATE is a character function which replaces a sequence of characters in a string with another set of characters. The replacement is done single character at a time.
DECODE function compares expr to each search value one by one. If expr is equal to a search, then Oracle Database returns the corresponding result. If no match is found, then Oracle returns default. If default is omitted, then Oracle returns null.

What is difference between DECODE and CASE ?
CASE can work with logical operators other than ‘=’
CASE can work with predicates and searchable subqueries
CASE can work as a PL/SQL construct
CASE handles NULL differently
CASE expects datatype consistency, DECODE does not
CASE is ANSI SQL-compliant
Readability: DECODE is shorter and easier to understand than CASE.

What will you use in Query : IN or EXISTS and Why ?
Lets first understand how they are processed.

Select * from T1 where x in ( select y from T2 )

is typically processed as:

select *
from t1, ( select distinct y from t2 ) t2
where t1.x = t2.y;

The subquery is evaluated, distinct'ed, indexed (or hashed or sorted) and then joined to the original table -- typically.


As opposed to

select * from t1 where exists ( select null from t2 where y = x )

That is processed more like:


for x in ( select * from t1 )
loop
if ( exists ( select null from t2 where y = x.x )
then
OUTPUT THE RECORD
end if
end loop

It always results in a full scan of T1 whereas the first query can make use of an index on T1(x).


So, when is where exists appropriate and in appropriate?

Lets say the result of the subquery
( select y from T2 )

is "huge" and takes a long time. But the table T1 is relatively small and executing ( select null from t2 where y = x.x ) is very very fast (nice index on t2(y)). Then the exists will be faster as the time to full scan T1 and do the index probe into T2 could be less then the time to simply full scan T2 to build the subquery we need to distinct on.


Lets say the result of the subquery is small -- then IN is typicaly more appropriate.


If both the subquery and the outer table are huge -- either might work as well as the other -- depends on the indexes and other factors.


What is Sequence ?
Sequence is a database object from which multiple users may generate unique integers. It is used to automatically generate primary key values.

Write the order of precedence for validation of a column in a table ? i. done using Database triggers. ii. done using Integarity Constraints.
If it is before trigger then the trigger will run first before the constriants check in the table. If it is after trigger, contraints are checked first and then trigger will run.

What rules are to be taken care of when doing comparisons using NULL ?
1. A NULL should never be TRUE or FALSE.
2. If a value in an expression is NULL, then the expression itself evaluates to NULL except for Concatenation Operator.
3. A NULL is never equal or unequal to other values.
4. NULL is not a value, it represents absence of data. So NULL is something UNIQUE


What operators deal with NULL ?
NVL converts NULL to another specified value.
e.g.: var:=NVL(var2,'Hi');
IS NULL and IS NOT NULL can be used to check specifically to see whether the value of a variable is NULL or not.

What is set serveroutput function used for in PL/SQL ?
To produce the Output on the console using dbms_output.put_line() function, we need to first set the server output to ON state. For this, the command is: set serveroutput on;

What is the difference between GRANT and REVOKE command ?
A Grant command provide privileges to users & roles or a role to users & roles whereas a Revoke command remove privileges from users & roles or a role to users & roles.

What are Global Temporary tables ?
Global Temporary tables are database tables which store data temporarily as the data is available only to the current session or current transaction. They are called as Global because the table definition is available to all sessions.

e.g.: Create global temporary TempData(
                                              id number(10),
                                              name varchar2(20) 
                                          ) on commit delete rows /*OR on commit PRESERVE rows*/;

commit delete rows : data should be deleted at the end of the transaction, or the end of the session.
commit PRESERVE rows : rows should persist beyond the end of the transaction and will only be removed at the end of the session.


What is dynamic SQL in oracle ?
Dynamic SQL is a programming methodology for generating and running SQL statements at run time. It is useful when writing general-purpose and flexible programs like ad hoc query systems, when writing programs that must run database definition language (DDL) statements, or when you do not know at compilation time the full text of a SQL statement or the number or data types of its input and output variables.

PL/SQL provides two ways for writing it:
First, by using EXECUTE IMMEDEATE and second, by using DBMS_SQL package.


Which of the following is not a schema object : Index, table, public synonym, trigger and package ?

Public synonym

Friday, July 15, 2016

Pl/Sql Interview Questions Level 1

What are the types of SQL Statement ?
SQL statements are divided into five different categories:
Data definition language (DDL) : CREATE, ALTER, DROP, TRUNCATE, RENAME
Data manipulation language (DML) : SELECT, INSERT, UPDATE, DELETE, MERGE
Data Control Language (DCL) : GRANT, REVOKE, ANALYZE, AUDIT, COMMENT
Transaction Control Statement : COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION
Session Control Statements (SCS) : ALTER SESSION, SET ROLE


Difference between DDL & DML ?
DML require commit but DDL do not require it.

What is Key and Significance of keys ?
A key is the column or set of columns included in the definition of certain types of integrity constraints. Key allow us to define rules at the column or object level that restrict values in the database.

What is the difference between primary key and unique key ?
A primary key is a column or combination of columns that uniquely defines a row. None of the columns that are part of the primary key can contain a null value. A table can have only one primary key.
A unique key is a column or combination of columns that uniquely defines a row. Some of the columns that are part of the unique key can contain null values as long as the combination of values is unique. A table can have more than one unique key.
Oracle does not permit you to create both a primary key and unique constraint with the same columns.

What is referential integrity ?
Oracle Database can enforce the relationship between the two tables through a foreign key constraint, also called a referential integrity constraint. The constraint requires that for each value in the column on which the constraint is defined, the value in the other specified other table and column must match.

Can we have null in a foreign key ? If yes, how many in a table.


What is delete CASCADE ?
When delete CASCADE used then if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted.

What is the use of CASCADE CONSTRAINTS ?
When this clause is used with DROP command, it first deletes all foreign keys that reference the table to be dropped, then drops the table. It is useful when a table need to be dropped even when a child table exists.

What is Union, Intersect, Minus ?
These are Set operators which combine the results of two component queries into a single result.

UNION : All distinct rows selected by either query
INTERSECT : All distinct rows selected by both queries
MINUS : All distinct rows selected by the first query but not the second

What is the difference between UNION and UNION ALL ?
UNION eliminates duplicate rows while UNION ALL include duplicate rows. UNION ALL is faster than UNION.

What are the uses of MERGE ?
MERGE is used to combine multiple DML statements into one.

Syntax : merge into tablename

using(query)

on(join condition)

when not matched then

[insert/update/delete] command

when matched then

[insert/update/delete] command


What is join ? Explain the different types of joins ?
A join is a query that combines rows from two or more tables, views, or materialized views with at least one join condition, either in the FROM clause or in the WHERE clause.
Types of joins are :
  • Cartesian Products
  • Equijoins
  • Self Joins
  • Inner Join
  • Outer Joins : Left, Right, Full
  • Antijoins
  • Semijoins


What are the various types of queries ?
Nested subquery
Correlated subquery
Hierarchical Queries
Distributed Queries

What is the difference between nested subquery and correlated Subquery ?
A subquery is nested when you are having a subquery in the where or having clause of another subquery. The innermost subquery will be executed first and then based on its result the next subquery will be executed and based on that result the outer query will be executed.

A Correlated Subquery is one that is executed after the outer query is executed.
The correlated subquery execution is as follows:

-The outer query receives a row.
-For each candidate row of the outer query, the subquery (the correlated subquery) is executed once.
-The results of the correlated subquery are used to determine whether the candidate row should be part of the result set.
-The process is repeated for all rows.

What is the difference between a "where" clause and a "having" clause ?
  • WHERE clause can be used with SELECT,UPDATE and DELETE but HAVING clause can only be used with SELECT query.
  • condition specified in WHERE clause is applied on each rows of a table to get filtered data and on the other hand HAVING clause applied later to filter grouped data.
  • WHERE clause will perform index scan on table and HAVING will not.

What is the difference between ANY and ALL conditions ?
ANY use OR operator to compare each condition while ALL use AND operator.

What is the difference between delete, drop and truncate operation on a table ?

  • Delete removes rows from a table. WHERE condition can be given with delete. Commit or Rollback required after delete. DML operation. Delete Trigger will execute.
  • Truncate removes all rows. No WHERE condition. DDL operation so No Commit or Rollback required. No trigger execute. Faster than Delete.
  • Drop removes table from database. DDL operation.
What is the order of Query Execution in SQL ?
1) From Clause
2) Where Clause
3) Group By Clause
4) Having Clause
5) Select
6) Order By Clause

Friday, July 8, 2016

Inside Oracle Database

Explain oracle database architecture?
Refer below figure to understand the oracle database architecture. For detail of each component, refer my last post.




What is the difference between Oracle 9i and Oracle 10g ?
Each release of Oracle has many differences, and Oracle 10g is a major re-write of the Oracle kernel from Oracle 9i. While there are several hundred new features and other differences between 9i and 10g, here are the major differences between Oracle9i and Oracle10g:

  • Major changes to SQL optimizer internals
  • Oracle Grid computing
  • AWR and ASH tables incorporated into Oracle Performance Pack and Diagnostic Pack options
  • Automated Session History (ASH) materializes the Oracle Wait Interface over time
  • Data Pump replaces imp utility with impdp
  • Automatic Database Diagnostic Monitor (ADDM)
  • SQLTuning Advisor
  • SQLAccess Advisor
  • Rolling database upgrades (using Oracle10g RAC)
  • dbms_scheduler package replaces dbms_job for scheduling

What is data dictionary ?
Metadata is data about data, or data that defines other data. The Oracle data dictionary is metadata about the database.The data dictionary is full of 'Metadata', information about what is going-on inside your database. The data dictionary is presented to us in the form of a number of views. The dictionary views come in two primary forms: DBA, ALL or USER views

There are hundreds of views in the data dictionary. Few views that store data about Oracle tables are : dba_all_tables, dba_indexes, dba_tables, dba_tab_cols, dba_tab_columns.

What are the properties of a Database?
The properties of a Database are also known as ACID Properties. These are Atomicity, Consistency, Isolation and Durability.
  • Atomicity requires that each transaction is "all or nothing": if one part of the transaction fails, the entire transaction fails, and the database state is left unchanged.
  • The consistency property ensures that any transaction will bring the database from one valid state to another. Any data written to the database must be valid according to all defined rules.
  • Isolation requires that multiple transactions occurring at the same time not impact each other’s execution.
  • Durability means that once a transaction has been committed, it will remain so, even in the event of power loss, crashes, or errors

What is normalization? what is the advantage of normalization?
Normalization is a process of organizing the data in database to avoid data redundancy, insertion anomaly, update anomaly & deletion anomaly.
mostly used nromal forms are:
First normal form (1NF) : an attribute (column) of a table cannot hold multiple values. It should hold only atomic values.
Second normal form (2NF) : Table is in 1NF and no non-prime attribute is dependent on the proper subset of any candidate key of table (An attribute that is not part of any candidate key is known as non-prime attribute).
Third Normal form (3NF) : Table design is in 3NF if it is in 2NF and there is no transitive functional dependency of non-prime attribute on any super key.

Some of the benefits of normalization are: Data integrity (because there is no redundant, neglected data). Optimized queries (because normalized tables produce rapid, efficient joins). Faster index creation and sorting (because the tables have fewer columns).

What are database links used for ?
Database links are created in order to form communication between various databases. A database link is a schema object in one database that enables you to access objects on another database. The other database need not be an Oracle Database system. However, to access non-Oracle systems you must use Oracle Heterogeneous Services.

CREATE [PUBLIC] DATABASE LINK <Link_Name> CONNECT TO &src_user identified by &src_password using '(DESCRIPTION =(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=&src_host)(PORT=&src_port)))(CONNECT_DATA=(sid=&src_database)) )' ;

What is Context Area in PL/SQL ?
Oracle process an SQL statement in a separate memory zone called as Context Area which is part of the program global area (PGA) allocated on the server. It contains information regarding SQL Query, number of rows accessed by it, information retrieved from database tables/records and many more.

What is the process of PL/SQL compilation ?
When a user sends a PL/SQL block from a client to the database server, the PL/SQL compiler check syntax, check semantics and security, resolve names and then generate (and optimize) bytecode (or MCode). Once the SQL compiler is done, it hands the execution plan over to the SQL engine to fulfil the request. Meanwhile the PVM (PL/SQL vitual machine) interprets the PL/SQL bytecode and, once the SQL engine has come up with the results, returns the status (success/failure) to the client session.

What is Native Compilation ?
By default, PL/SQL code is compiled and stored in the form of byte code ready for execution. During the execution process, this byte code is interpreted, a process which requires time and resources.
The process of native compilation converts PL/SQL stored procedures to native code shared libraries which are linked into the kernel resulting in performance increases for the procedural code. The extent of the performance increase depends on the content of the PL/SQL. The compilation process does not affect the speed of database calls, only the procedural logic around them such as loops and calculations.