Google News
logo
Oracle Interview Questions
Oracle is a company. Oracle is also a database server, which manages data in a very structured way. It allows users to store and retrieve related data in a multi-user environment so that the users can concurrently access the same data. All this is accomplished while delivering high performance. A database server also prevents unauthorized access and provides efficient solutions for failure recovery. A standby database is a database replica created by taking a backup of a primary database.
Oracle provides software to create and manage the Oracle Database. The database consists of physical and logical structures in which system, user, and control information are stored. The software that manages the database is called the Oracle Database server. Collectively, the software that runs Oracle and the physical database is called the Oracle Database system.
 
A database buffer cache stores the data in memory for quicker access. The redo logs track and store all the changes made to the database. A Data Guard ensures data protection and high availability of data, and a control file records the physical structure of the database.
Both Varchar & Varchar2 are the Oracle data types which are used to store character strings of variable length. To point out the major differences between these,

Varchar : 
* Can store characters up to 2000 bytes.
* It will hold the space for characters defined during declaration even if all of them are not used

Varchar2 :
* Can store characters up to 4000 bytes.
* It will release the unused space
The components of the logical database structure in Oracle database are :
 
Tablespaces : A database mainly contains the Logical Storage Unit called tablespaces. This tablespace is a set of related logical structures. To be precise, tablespace groups are related to logical structures together.
 
Database schema objects : A schema is a collection of database objects owned by a specific user. The objects include tables, indexes, views, stored procedures, etc. And in Oracle, the user is the account and the schema is the object. It is also possible in the database platforms to have a schema without a user specified.
A table is a basic unit of data storage in the Oracle database. A table basically contains all the accessible information of a user in rows and columns.
 
To create a new table in the database, use the “CREATE TABLE” statement. First, you have to name that table and define its columns and datatype for each column.
CREATE TABLE table_name
(
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
…
column_n datatype [ NULL | NOT NULL ]
);
Here,
 
* table_name : This specifies the name of the table that you want to create.

* column..n : It specifies the number of columns which you want to add in the table. Here, every column must have a datatype and should either be defined as “NULL” or “NOT NULL”. If in case, the value is left blank, it is treated as “NULL” as default.
The different components of the physical database structure of an Oracle database are listed down below :
 
* Greater than equal to two redo log files.
* Greater than equal to one data file.
* Greater than equal to one control file.
An index is an optional structure associated with a table to have direct access to rows that can be created to increase the performance of data retrieval. An index can be created on one or more columns of a table.
There are many databases available in the market. The commonly used databases are Oracle, IBM db2, Microsoft SQL Server, Microsoft Access, MySQL and SQLite, PostgreSQL, MariaDB.
Below 5 are the physical components of Oracle Database :
 
* Data files
* Control files
* Redo log files
* Password files
* Parameter files
A DBA has the authority to create new users, remove the existing users, or modify any of the environment variables or privileges assigned to other users.
 
* Manage database storage
* Administer users and security
* Manage schema objects
* Perform backup and recovery
* Schedule and automate jobs
* Monitor and manage database performance
* Tables
* Views
* Indexes
* Synonyms
* Sequences
* Tablespaces
A database contains Logical Storage Unit called tablespaces. A tablespace is a set of related logical structures. Actually a tablespace groups related logical structures together.
Bulk copy or BCP in Oracle, is used to import or export data from tables and views but it does not copy structure of same data.
 
The main advantage of BCP is fast mechanism for coping data and you can also take the backup of data easily.
An Oracle database contains one or more logical storage units called tablespaces. These tablespaces collectively store whole data of databases and each tablespace in Oracle database consists of one or more files called datafiles. These datafiles are physical structure that confirm with the operating system in which Oracle is running.
A snapshot is a replica of a target master table from a single point-in-time. In simple words you can say, snapshot is a copy of a table on a remote database.
Hot backup (Online Backup) : A hot backup is also known as online backup because it is done while the database is active. Some sites can not shut down their database while making a backup copy, they are used for 24 hour a day, 7 days a week.
 
Cold backup (Offline Backup) : A cold backup is also known as offline backup because it is done while the database has been shutdown using the SHUTDOWN normal command. If the database is suddenly shutdown with a uncertain condition it should be restarted with RESTRICT mode and then shutdown with NORMAL option.
 
For a complete cold backup the following files must be backed up.
 
All datafiles, All control files, All online redo log files(optional) and the init.ora file (you can recreate it manually).
Save points are used to divide a transaction into smaller parts. It allows rolling back of a transaction. Maximum five save points are allowed. It is used to save our data, whenever you encounter an error you can roll back from the point where you save your SAVEPOINT.
Hash cluster is a technique to store a data in hash table and improve the performance of data retrieval. Hash function is applied on table row's cluster key value and store in hash cluster.
* Tables : This is a set of elements organized in vertical and horizontal fashion.
 
* Tablespaces : This is a logical storage unit in Oracle.
 
* Views : It is virtual table derived from one or more tables.
 
* Indexes : This is a performance tuning method to process the records.
 
* Synonyms : This is a name for tables.
A pre-query trigger fire before the query executes and fire once while you try to query. With the help of this trigger you can modify the where clause part dynamically.
 
Pre-select query fires during the execute query and count query processing after Oracle forms construct the select statement to be issued, but before the statement is actually issued.
 
Pre-query trigger fires before Pre-select trigger.
A synonym which is also known as an alias is an identifier that can be used to reference another database object in a SQL statement. A table, view, sequence are the types of database objects that can be created for a synonym.
There are two types of Synonyms which are- Public and Private.
 
A public synonym isn’t part of any schema. A public synonym is one that can be used by any database user.
 
A private synonym does belong to a specific schema. In other words, when only the owner can access it, it is called a private synonym.
Database users’ passwords are stored in the database’s data dictionary. When a user attempts to log into the database, the user’s usernames and passwords are compared to the values contained in the database. The user is given database access only if the username and password match.  The data dictionary is stored in the database and can be accessed as long as the database is available. The dictionary also contains the passwords for the administrators.
 
The data dictionary would be unavailable until the database is locked. Since starting up a down database is one of the administrator’s jobs, there needs to be a way for them to log in even if the database is locked. That’s where the password file comes into the picture. A password file is an operating system file that is held on a separate disc from the database. It stores the username and password for users with the SYSDBA or SYSOPER privileges. And when the database is down,  administrators with certain privileges are authenticated using the password files.
Character functions : accept character input and return both character and number values. Types of character function are :
 
Case-Manipulation Functions : LOWER, UPPER, INITCAP

Character-Manipulation Functions : CONCAT, SUBSTR, LENGTH, INSTR, LPAD/RPAD, TRIM, REPLACE

Number Functions : accept Numeric input and return numeric values. Number Functions are: ROUND, TRUNC, and MOD
 
Date Functions : operates on values of the Date data type. (All date functions return a value of DATE data type except the MONTHS_BETWEEN Function, which returns a number. Date Functions are MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY, ROUND, TRUNC. 
Conversion Functions convert a value from one data type to another. Conversion functions are of two types:
 
Implicit Data type conversion :
 
* VARCHAR2 or CHAR To NUMBER, DATE
* NUMBER To VARCHAR2
* DATE To VARCHAR2

Explicit data type conversion :
 
* TO_NUMBER
* TO_CHAR
* TO_DATE

TO_NUMBER function is used to convert a Character string to Number format. TO_NUMBER function use fx modifier. Format: TO_NUMBER ( char[, ‘ format_model’] ). fx modifier specifies the exact matching for the character argument and number format model of the TO_NUMBER function.
 
TO_CHAR function is used to convert NUMBER or DATE data type to CHARACTER format. TO_CHAR Function uses fm element to remove padded blanks or suppress leading zeros. TO_CHAR Function formats : TO_CHAR (date, ‘format_model’).The format model must be enclosed in single quotation marks and is case sensitive.
 
Ex : Select TO_CHAR (hire date, ‘MM/YY’) from the employee.
 
TO_DATE function is used to convert a Character string to date format. TO_DATE function use fx modifier which specifies the exact matching for the character argument and date format model of TO_DATE function. TO_DATE function format: TO_DATE ( char[, ‘ format_model’] ).
 
Ex : Select TO_DATE (‘May 24, 2007’,’ mon dd RR’) from dual;
* When two processes are waiting to update the rows of a table which are locked by another process, the situation is called a deadlock.

The reasons for it to happen are :

* lack of proper row lock commands.
* Poor design of front-end application
* It reduces the performance of the server severely.
* These locks get automatically released automatically when a commit/rollback operation is performed or any process is killed externally.
The default tablespaces of Oracle are as follows :
 
The SYSTEM and SYSAUX tablespaces : These store system-generated objects such as data dictionary tables in them. One should not store any object in these tablespaces.

The USERS tablespace : It is used for ad-hoc users.

The UNDOTBS1 tablespace : Is used for holding the undo data.

The TEMP tablespace : It is the temporary tablespace that is used for storing intermediate results of sorting, hashing, and large object processing operations.
 
To switch from an init.ora file to a spfile, we should create spfile from pfile command then shutdown instance and startup once again
A binary file that records the physical structure of the database and is required to start and run the database.
 
A control file contains information such as
 
* Data file
* Database name
* Redo file name
* Locations of associated data files and redo files.
* Timestamp of database creation.
* Current log sequence number
* Checkpoint information
Steps to recover a lost control file are :
 
* Start the database in the NOMOUNT mode
* Create the control file from the control file backup with CREATE CONTROLFILE statement, and place it in the correct location.
* Mount the database
* Recover the database
* Open the database
The recovery catalog is a database scheme that contains the metadata that RMAN manages for data restoration and recovery processes. The metadata used by RMAN for reinstallation and healing process is stored in a recovery catalog. The RMAN metadata is still present in the recovery catalogue even if the target control file and all backups are lost.
ANALYZE command is used to perform various functions on index, table, or cluster. The following list specifies the usage of ANALYZE command in Oracle :
 
* It is used to validate the structure of the object.
* It is used to identify migrated and chained rows of the table or cluster.
* It helps in collecting the statistics about object used by the optimizer. They are then stored in the data dictionary.
* It helps in deleting statistics used by object from the data dictionary.
The most common types of modules in Oracle forms are as follows :
 
* Form module
* Menu module
* Pl/SQL Library module
* Object Library module
The BLOB data type in the Oracle database has a varying length binary string. It is used to store two gigabytes of memory and for it, the length needs to be specified in bytes. An example to illustrate the usage of the BLOB data type is given below :
 
Creating a table :
create table photos(name varchar(32) not null primary key, picture blob(10M));

Querying for all logotype pictures :
select name,length(picture) from photos where name like '%logo%';
Mirroring is a process of having a copy of Redo log files. It is done by creating group of log files together. This ensures that LGWR automatically writes them to all the members of the current on-line redo log group. If the group fails, the database automatically switches over to the next group. It diminishes the performance.
A Join is used to compare and combine, this means literally join and return specific rows of data from two or more tables in a database.
 
There are three types of joins in SQL that are used to write the subqueries.
 
Self Join : This is a join in which a table is joined with itself, especially when the table has a foreign key which references its own primary key.

Outer Join : An outer join helps to find and returns matching data and some dissimilar data from tables.

Equi-join : An equijoin is a join with a join condition containing an equality operator. An equijoin returns only the rows that have equivalent values for the specified columns.
The RAW datatype in Oracle is used to store variable-length binary data or byte string values. The maximum size for a raw in a given table in 32767 bytes.
 
You might get confused as to when to use RAW, varchar, and varchar2. Let me point out the major differences between them. PL/SQL does not recognize the data type and hence, it cannot have any conversions when RAW data is transferred to different systems. This data type can only be queried or can be inserted in a table.
An aggregate function in Oracle is a function where values of multiple rows or records are joined together to get a single value output. It performs the summary operations on a set of values in order to provide a single value. There are several aggregate functions that you can use in your code to perform calculations.

The common Aggregate functions are :

* Sum
* Count
* Average
 
Merge statement is used to merge the data from two tables subsequently. It selects the data from the source table and then inserts/updates it in the other table based on the condition provided in the query. It is also useful in data warehousing applications.
The Dual table is basically a one-column table that is present in the Oracle database. This table has a single Varchar2(1) column called Dummy which has a value of ‘X’.
Oracle mainly provides these following temporal data types :
 
Date Data Type : Different formats of Dates.
TimeStamp Data Type : Has different formats of Time Stamp.
Interval Data Type : Interval between dates and time.
A view is a logical table based on one or more tables or views. A View is also referred as a user-defined database object that is used to store the results of a SQL query, that can be referenced later in the course of time. Views do not store the data physically but as a virtual table, hence it can be referred as a logical table. The corresponding tables upon which the views are signified are called Base Tables and this doesn’t contain data.
It is possible to store pictures on to the database by using Long Raw Data type. This data type is used to store binary data of length 2GB. Although, the table can have only on Long Raw data type.
$Oracle_base is the main or root directory of Oracle whereas $Oracle_Home is located beneath the base folder in which all Oracle products reside.
The main limitation of CHECK constraint is that the condition must be a Boolean expression evaluated using the values in the row being inserted or updated and can't contain sub queries.
The to_char() function is used to convert date to character. You can also specify the format in which you want output.
 
SELECT to_char ( to_date ('12-12-2012', 'DD-MM-YYYY') , 'YYYY-MM-DD') FROM dual;  

Or,
 
SELECT to_char ( to_date ('12-12-2012', 'DD-MM-YYYY') , 'DD-MM-YYYY') FROM dual;
Actual Parameters : Actual parameters are the variables or expressions referenced in the parameter list of a subprogram.
 
Let's see a procedure call which lists two actual parameters named empno and amt :
 
raise_sal(empno, amt);
  
Formal Parameters : Formal parameters are variables declared in a subprogram specification and referenced in the subprogram body.
 
Following procedure declares two formal parameters named empid and amt:
 
PROCEDURE raise_sal(empid INTEGER, amt REAL) IS current_salary REAL;
48 .
Data Manipulation Language (DML) is used to access and manipulate data in the existing objects.  DML statements are insert, select, update and delete and it won’t implicitly commit the current transaction.
Translate is used for character by character substitution and Replace is used substitute a single character with a word.
The USING clause is used to specify with the column to test for equality when two tables are joined.
 
[sql]Select * from employee join salary using employee ID[/sql]
 
Employee tables join with the Salary tables with the Employee ID.
VArray is an oracle data type used to have columns containing multivalued attributes and it can hold bounded array of values.
Attributes of Cursor are :
 
%FOUND :
* Returns NULL if cursor is open and fetch has not been executed
* Returns TRUE if the fetch of cursor is executed successfully.
* Returns False if no rows are returned.
 
%NOT FOUND :
* Returns NULL if cursor is open and fetch has not been executed
* Returns False if fetch has been executed
* Returns True if no row was returned
 
%ISOPEN :
* Returns true if the cursor is open
* Returns false if the cursor is closed
 
%ROWCOUNT :
* Returns the number of rows fetched. It has to be iterated through entire cursor to give exact real count.
Display row numbers with the records numbers :
 
Select rownum, <fieldnames> from table;

This query will display row numbers and the field values from the given table.
Last record can be added to a table and this can be done by :
 
Select * from (select * from employees order by rownum desc) where rownum<2;
The SYSDATE() function is used in Oracle to find the current date and time of operating system on which the database is running.
 
SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "Current_Date" FROM DUAL;
Actual parameters are defined as the variables or expressions referenced in the parameter list of a subprogram. An example of a procedure call that lists two actual parameters named empNumber and amount is as follows :
 
updateSalary(empNumber,amount);

Formal parameters can be defined as variables declared in a subprogram specification and referenced in the subprogram body. An example of a procedure that declares two formal parameters named empID and amount: is as follows :
 
PROCEDURE updateSalary(empID INTEGER, amount REAL) IS currentSalary REAL;
A query to find the average salary of employees from the Emp Oracle Table is given below :
 
SELECT AVG(SALARY) FROM EMP GROUP BY SALARY;
Written below is a query to list the duplicate values in an Oracle table :
 
SELECT NAME, COUNT (NAME) FROM EMPLOYEE GROUP BY NAME HAVING COUNT (NAME) > 1;

In ORDBMS, the objects can be stored as they are. The language of the DBMS can be integrated with an object-oriented programming language. The language may even be exactly the same as that used in the application, which does not force the programmer to have two representations of his objects.
As an Oracle DBA, we have to carry out the following tasks :
 
* Installing Oracle software
* Creating Oracle databases
* Performing upgrades of the database and software to new release levels
* Starting up and shutting down the database
* Managing the database’s storage structures
* Managing users and security
* Managing schema objects, such as tables, indexes, and views
* Making database backups and performing recovery when necessary
* Proactively monitoring the database’s health and taking preventive or corrective actions as required
* Monitoring and tuning performance

In a small-to-midsize database environment, a single DBA might be the sole person performing all these tasks. In large enterprise environments, the whole job is often divided among several DBAs titled as Database Security Administrator or Database Tuning Expert, each with his/her own area of specialties.
There are no differences between the join. Cartesian and Cross joins are same. Cross join gives cartesian product of two tables – Rows from first table is multiplied with another table which is called cartesian product.
 
Cross join without where clause gives Cartesian product.
This can be done by this query :
 
Select * from employee where salary>(select avg(salary) from dept, employee where dept.deptno = employee.deptno);

You can start up a database using three tools :
 
SQL *Plus : To startup an Oracle database instance, you can use the SQL *Plus startup command.

Oracle Enterprise Manager : It is a system management tool, you can startup the Oracle database with Oracle enterprise manager also. It provides an integrated solution for managing your heterogeneous environment. Even if the database is stopped you can still log in to OEM. It will present you with the Startup button by detecting the status of the down database.

Recovery Manager : RMAN is also known as the RMAN repository that is connected with the TARGET keyword which is also a database on which RMAN performs backup and recovery operations in the control file of the database.
These are the few commands that  can be used to view in oracle
 
* V$Parameter
* V$Database
* V$Instance
* V$Datafiles
* V$controlfiles
* V$logfiles
Multiple database context processes are possible. In the operating system, they are referred to as “DBWn”. This method is in charge of storing “dirty” buffers on disc. When a server process has to update a data block, it first reads it from disc into the buffer cache if it isn’t already there, and then updates the cache copy. So, a “dirty” block refers to a modified database block in the buffer cache.