Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 119

Oracle Training

(1) Oracle Tutorial


1. Oracle Tutorial
2. What is Oracle

(2) Oracle Tables


1. Create Table
2. Create Table As
3. Alter Table
4. Drop Table
5. Global Temp Tables
6. Local Temp Tables

(3) Oracle Views


1. Create View

(4) Oracle Query


1. Oracle Queries
2. Oracle Select
3. Oracle Insert
4. Oracle Insert All
5. Oracle Update
6. Oracle Delete
7. TruncateTable
(5) Oracle Clauses
1. Oracle DISTINCT
2. Oracle FROM
3. Oracle ORDER BY
4. Oracle GROUP BY
5. Oracle HAVING

(6) Oracle Operators


1. Oracle Union
2. Oracle Union All
3. Oracle Intersect
4. Oracle Minus

(7) Oracle Joins


1. Oracle Joins
2. Inner Join
3. Outer Join
4. Equi Join
5. Self Join
6. Cross Join
7. Anti Join
8. Semi Join

(8) Oracle Advance


1. Oracle Procedure
2. Oracle Function
3. Oracle Cursor
4. Oracle Trigger
5. Oracle BEFORE Trigger
6. Oracle AFTER Trigger
7. Oracle DROP Trigger
8. Oracle DISABLE Trigger
9. Oracle ENABLE Trigger

(9) Interview Questions


1. Oracle Interview
2. SQL Interview
3. PL/SQL Interview

Oracle Tutorial
Oracle tutorial provides basic and advanced concepts of Oracle. Our Oracle tutorial is
designed for beginners and professionals.

Oracle is a relational database management system. It is widely used in enterprise


applications.

Our Oracle tutorial includes all topics of Oracle database such as insert record, update
record, delete record, select record, create table, drop table etc. There are also given Oracle
interview questions to help you better understand the Oracle database.

Prerequisite
Before learning Oracle, you must have the basic knowledge of computer fundamentals.

Audience
Our Oracle tutorial is designed to help beginners and professionals.

Problem
We assure that you will not find any problem in this Oracle tutorial. But if there is any
mistake, please post the problem in contact form.

What is Oracle
Oracle database is a relational database management system. It is known as Oracle
database, OracleDB or simply Oracle. It is produced and marketed by Oracle Corporation.
Oracle database is the first database designed for enterprise grid computing. The enterprise
grid computing provides the most flexible and cost effective way to manage information and
applications.

Different editions of Oracle database


Following are the four editions of the Oracle database.

o Enterprise Edition: It is the most robust and secure edition. It offers all features,
including superior performance and security.
o Standard Edition: It provides the base functionality for users that do not require
Enterprise Edition's robust package.
o Express Edition (XE): It is the lightweight, free and limited Windows and Linux
edition.
o Oracle Lite: It is designed for mobile devices.

The Oracle Corporation


Oracle Corporation is the largest software company in the field of database business. Its
relational database was the first to support SQL which has since become the industry
standard.

Oracle database is one of the most trusted and widely used relational database engines. The
biggest rival of Oracle database is Microsoft's SQL Server.

History of Oracle
Oracle was originally developed by Lawrence Ellison (Larry Ellision) and his two friends and
former co-worker in 1977. Oracle DB runs on the most major platforms like Windows, UNIX,
Linux and Mac OS.

Oracle TABLES
Oracle CREATE TABLE
In Oracle, CREATE TABLE statement is used to create a new table in the database.

To create a table, you have to name that table and define its columns and datatype for each
column.

Syntax:
1. CREATE TABLE table_name  
2. (   
3.   column1 datatype [ NULL | NOT NULL ],  
4.   column2 datatype [ NULL | NOT NULL ],  
5.   ...  
6.   column_n datatype [ NULL | NOT NULL ]  
7. );  

Parameters used in syntax


o table_name: It specifies the name of the table which you want to create.

o column1, column2, ... column n: It specifies the columns which you want to add
in the table. Every column must have a datatype. Every column should either be
defined as "NULL" or "NOT NULL". In the case, the value is left blank; it is treated as
"NULL" as default.

Oracle CREATE TABLE Example


Here we are creating a table named customers. This table doesn't have any primary key.

CREATE TABLE customers  
( customer_id number(10) NOT NULL,  
  customer_name varchar2(50) NOT NULL,  
  city varchar2(50)  
);  

This table contains three columns

o customer_id: It is the first column created as a number datatype (maximum 10


digits in length) and cannot contain null values.
o customer_name: it is the second column created as a varchar2 datatype (50
maximum characters in length) and cannot contain null values.
o city: This is the third column created as a varchar2 datatype. It can contain null
values.

Oracle CREATE TABLE Example with primary key


CREATE TABLE customers  
( customer_id number(10) NOT NULL,  
  customer_name varchar2(50) NOT NULL,  
  city varchar2(50),  
  CONSTRAINT customers_pk PRIMARY KEY (customer_id)  
);  

What is Primary key


A primary key is a single field or combination of fields that contains a unique record. It must
be filled. None of the field of primary key can contain a null value. A table can have only one
primary key.

CREATE TABLE AS Statement


The CREATE TABLE AS statement is used to create a table from an existing table by copying
the columns of existing table.

Note: If you create the table in this way, the new table will contain records from the existing
table.

Syntax:

1. CREATE TABLE new_table  
2. AS (SELECT * FROM old_table);   

Create Table Example: copying all columns of another


table
In this example, we are creating a "newcustomers" table by copying all the columns from
the already existing table "Customers".

1. CREATE TABLE newcustomers  
2. AS (SELECT *   FROM customers  WHERE customer_id < 5000);  
Table created.

This table is named as "newcustomers" and having the same columns of "customers" table.
Create Table Example: copying selected columns of
another table
Syntax:

1. CREATE TABLE new_table  
2.   AS (SELECT column_1, column2, ... column_n  
3.       FROM old_table);  

Let's take an example:

1. CREATE TABLE newcustomers2  
2. AS (SELECT customer_id, customer_name  
3.     FROM customers  
4.     WHERE customer_id < 5000);  

The above example will create a new table called "newcustomers2". This table includes the
specified columns customer_id and customer_name from the customers table.

Create Table Example: copying selected columns from


multiple tables
Syntax:

1. CREATE TABLE new_table  
2. AS (SELECT column_1, column2, ... column_n  
3.     FROM old_table_1, old_table_2, ... old_table_n);   

Let's take an example: Consider that you have already created two tables
"regularcustomers" and "irregularcustomers".

The table "regularcustomers" has three columns rcustomer_id, rcustomer_name and


rc_city.

1. CREATE TABLE  "regularcustomers"   
2.    (    "RCUSTOMER_ID" NUMBER(10,0) NOT NULL ENABLE,   
3.     "RCUSTOMER_NAME" VARCHAR2(50) NOT NULL ENABLE,   
4.     "RC_CITY" VARCHAR2(50)  
5.    )  
6. /  
The second table "irregularcustomers" has also three columns ircustomer_id,
ircustomer_name and irc_city.

1. CREATE TABLE  "irregularcustomers"   
2.    (    "IRCUSTOMER_ID" NUMBER(10,0) NOT NULL ENABLE,   
3.     "IRCUSTOMER_NAME" VARCHAR2(50) NOT NULL ENABLE,   
4.     "IRC_CITY" VARCHAR2(50)  
5.    )  
6. /  

In the following example, we will create a table name "newcustomers3" form copying
columns from both tables.

Example:

1. CREATE TABLE newcustomers3  
2.   AS (SELECT regularcustomers.rcustomer_id, regularcustomers.rc_city, irregularcus
tomers.ircustomer_name  
3.       FROM regularcustomers, irregularcustomers  
4.       WHERE regularcustomers.rcustomer_id = irregularcustomers.ircustomer_id  
5.       AND regularcustomers.rcustomer_id < 5000);

Oracle ALTER TABLE Statement


In Oracle, ALTER TABLE statement specifies how to add, modify, drop or delete columns in a
table. It is also used to rename a table.

How to add column in a table


Syntax:

1. ALTER TABLE table_name  
2.   ADD column_name column-definition;   

Example:

Consider that already existing table customers. Now, add a new column customer_age into
the table customers.

1. ALTER TABLE customers  
2.   ADD customer_age varchar2(50);  
Now, a new column "customer_age" will be added in customers table.

How to add multiple columns in the existing table


Syntax:

1. ALTER TABLE table_name  
2.   ADD (column_1 column-definition,  
3.        column_2 column-definition,  
4.        ...  
5.        column_n column_definition);  

Example

1. ALTER TABLE customers  
2.   ADD (customer_type varchar2(50),  
3.        customer_address varchar2(50));  
Now, two columns customer_type and customer_address will be added in the table
customers.

How to modify column of a table


Syntax:

1. ALTER TABLE table_name  
2.   MODIFY column_name column_type;   

Example:

1. ALTER TABLE customers  
2.   MODIFY customer_name varchar2(100) not null;  
Now the column column_name in the customers table is modified
to varchar2 (100) and forced the column to not allow null values.

How to modify multiple columns of a table


Syntax:

1. ALTER TABLE table_name  
2.   MODIFY (column_1 column_type,  
3.           column_2 column_type,  
4.           ...  
5.           column_n column_type);  

Example:

1. ALTER TABLE customers  
2.   MODIFY (customer_name varchar2(100) not null,  
3.           city varchar2(100));  
This will modify both the customer_name and city columns in the table.

How to drop column of a table


Syntax:

1. ALTER TABLE table_name  
2.   DROP COLUMN column_name;  

Example:

1. ALTER TABLE customers  
2.   DROP COLUMN customer_name;  
This will drop the customer_name column from the table.

How to rename column of a table


Syntax:

1. ALTER TABLE table_name  
2.   RENAME COLUMN old_name to new_name;  

Example:

1. ALTER TABLE customers  
2.  RENAME COLUMN customer_name to cname;  
This will rename the column customer_name into cname.

How to rename table


Syntax:

1. ALTER TABLE table_name  
2.   RENAME TO new_table_name;   

Example:

1. ALTER TABLE customers  
2. RENAME TO retailers;  
This will rename the customer table into "retailers" table.

Oracle DROP TABLE Statement


Oracle DROP TABLE statement is used to remove or delete a table from the Oracle
database.

Syntax

1. DROP [schema_name].TABLE table_name  
2. [ CASCADE CONSTRAINTS ]  
3. [ PURGE ];   

Parameters
schema_name: It specifies the name of the schema that owns the table.

table_name: It specifies the name of the table which you want to remove from the Oracle
database.

CASCADE CONSTRAINTS: It is optional. If specified, it will drop all referential integrity


constraints as well.

PURGE: It is also optional. If specified, the table and its dependent objects are placed in
the recycle bin and can?t be recovered.
If there are referential integrity constraints on table_name and you do not specify the
CASCADE CONSTRAINTS option, the DROP TABLE statement will return an error and Oracle
will not drop the table.

DROP TABLE Example


1. DROP TABLE customers;  
This will drop the table named customers.

DROP TABLE Example with PURGE parameter


1. DROP TABLE customers PURGE  

This statement will drop the table called customers and issue a PURGE so that the space
associated with the customers table is released and the customers table is not placed in
recycle bin. So, it is not possible to recover that table if required.

Oracle Global Temporary tables


Temporary tables generally contain all of the features that ordinary tables have like triggers,
join cardinality, information about rows and block etc. the main difference is that the
temporary tables can't have foreign keys related to other tables.

Syntax

1. CREATE GLOBAL TEMPORARY TABLE table_name  
2. ( column1 datatype [ NULL | NOT NULL ],  
3.   column2 datatype [ NULL | NOT NULL ],  
4.   ...  
5.   column_n datatype [ NULL | NOT NULL ]  
6. );  

Parameters
table_name: The parameter table_name specifies the global temporary table that you
want to create.

column1, column2, ... column_ n: It specifies the column that you want create in the
global temporary table. Every column must have a datatype and should be defined as NULL
or NOTNULL. If the value is left blank, it is by default treated as NULL.
Example
The following example specifies how to create a global temporary table

1. CREATE GLOBAL TEMPORARY TABLE students  
2. ( student_id numeric(10) NOT NULL,  
3.   student_name varchar2(50) NOT NULL,  
4.   student_address varchar2(50)  
5. );  
This will create a global temporary table called students

Oracle Local Temporary tables


In Oracle, local temporary tables are distinct within modules. These tables are defined and
scoped to the session in which you created it.

Declare local temporary table


Syntax

1. DECLARE LOCAL TEMPORARY TABLE table_name  
2. ( column1 datatype [ NULL | NOT NULL ],  
3.   column2 datatype [ NULL | NOT NULL ],  
4.   ...  
5.   column_n datatype [ NULL | NOT NULL ]  
6. );  

Parameters
table_name: The parameter table_name specifies the local temporary table that you want
to create.

column1, column2,... column_ n: It specifies the column that you want create in the
local temporary table. Every column must have a datatype and should be defined as NULL
or NOTNULL. If the value is left blank, it is by default treated as NULL.

Oracle VIEWS
Oracle View
In Oracle, view is a virtual table that does not physically exist. It is stored in Oracle data
dictionary and do not store any data. It can be executed when called.

A view is created by a query joining one or more tables.

Oracle CREATE VIEW


Syntax:

1. CREATE VIEW view_name AS  
2. SELECT columns  
3. FROM tables  
4. WHERE conditions;  

Parameters:

o view_name: It specifies the name of the Oracle VIEW that you want to create.

Example:

Let's take an example to create view. In this example, we are creating two tables suppliers
and orders first.

Suppliers table:

1.    
2. CREATE TABLE  "SUPPLIERS"  
3.    (    "SUPPLIER_ID" NUMBER,   
4.     "SUPPLIER_NAME" VARCHAR2(4000),   
5.     "SUPPLIER_ADDRESS" VARCHAR2(4000)  
6.    )  
7. /  
8.    

Orders table:

1. CREATE TABLE  "ORDERS"   
2.    (    "ORDER_NO." NUMBER,   
3.     "QUANTITY" NUMBER,   
4.     "PRICE" NUMBER  
5.    )  
6. /  

Execute the following query to create a view name sup_orders.

Create View Query:

1. CREATE VIEW sup_orders AS  
2. SELECT suppliers.supplier_id, orders.quantity, orders.price  
3. FROM suppliers  
4. INNER JOIN orders  
5. ON suppliers.supplier_id = supplier_id  
6. WHERE suppliers.supplier_name = 'VOJO';  
Output:
View created.
0.21 seconds

You can now check the Oracle VIEW by this query:

1. SELECT * FROM sup_orders;  
Output:
SUPPLIER_ID QUANTITY PRICE
3 35 70
3 26 125
3 18 100
3 rows returned in 0.00 seconds

Oracle Update VIEW


In Oracle, the CREATE OR REPLACE VIEW statement is used to modify the definition of an
Oracle VIEW without dropping it.

Syntax:

1. CREATE OR REPLACE VIEW view_name AS  
2.   SELECT columns  
3.   FROM table  
4.   WHERE conditions;   

Example:

Execute the following query to update the definition of Oracle VIEW called sup_orders
without dropping it.
1. CREATE or REPLACE VIEW sup_orders AS  
2.   SELECT suppliers.supplier_id, orders.quantity, orders.price  
3.   FROM suppliers  
4.   INNER JOIN orders  
5.   ON suppliers.supplier_id = supplier_id  
6.   WHERE suppliers.supplier_name = 'HCL';  

You can now check the Oracle VIEW by this query:

1. SELECT * FROM sup_orders;  

Output:

SUPPLIER_ID QUANTITY PRICE


1 35 70
1 26 125
1 18 100
row(s) 1 - 3 of 3

Oracle DROP VIEW


The DROP VIEW statement is used to remove or delete the VIEW completely.

Syntax:

1. DROP VIEW view_name;  

Example:

1. DROP VIEW sup_orders;  

Oracle Query
Oracle Queries
You can execute many queries in oracle database such as insert, update, delete, alter table,
drop, create and select.

1) Oracle Select Query


Oracle select query is used to fetch records from database. For example:

1. SELECT * from customers;  

More Details...

2) Oracle Insert Query


Oracle insert query is used to insert records into table. For example:

1. insert into customers values(101,'rahul','delhi');  

More Details...

3) Oracle Update Query


Oracle update query is used to update records of a table. For example:

1. update customers set name='bob', city='london' where id=101;  

More Details...

4) Oracle Delete Query


Oracle update query is used to delete records of a table from database. For example:

1. delete from customers where id=101;  

More Details...

5) Oracle Truncate Query


Oracle update query is used to truncate or remove records of a table. It doesn't remove
structure. For example:

1. truncate table customers;  

More Details...

6) Oracle Drop Query


Oracle drop query is used to drop a table or view. It doesn't have structure and data. For
example:
1. drop table customers;  

More Details...

7) Oracle Create Query


Oracle create query is used to create a table, view, sequence, procedure and function. For
example:

1. CREATE TABLE customers    
2. ( id number(10) NOT NULL,    
3.   name varchar2(50) NOT NULL,    
4.   city varchar2(50),  
5. CONSTRAINT customers_pk PRIMARY KEY (id)      
6. );    

More Details...

8) Oracle Alter Query


Oracle alter query is used to add, modify, delete or drop colums of a table. Let's see a query
to add column in customers table:

1. ALTER TABLE customers   
2. ADD age varchar2(50);

    

Oracle SELECT Statement


The Oracle SELECT statement is used to retrieve data from one or more than one tables,
object tables, views, object views etc.

Syntax

1. SELECT expressions  
2. FROM tables  
3. WHERE conditions;   

Parameters
1) expressions: It specifies the columns or calculations that you want to retrieve.
2) tables:This parameter specifies the tables that you want to retrieve records from. There
must be at least one table within the FROM clause.

3) conditions: It specifies the conditions that must be followed for selection.

Select Example: select all fields


Let's take an example to select all fields from an already created table named customers

1. SELECT *  
2. FROM customers;   

output

Select Example: select specific fields


Example

1. SELECT age, address, salary  
2. FROM customers  
3. WHERE  age < 25  
4. AND salary > '20000'  
5. ORDER BY age ASC, salary DESC;  

Select Example: select fields from multiple tables


(JOIN)
1. SELECT customers.name, courses.trainer  
2. FROM courses  
3. INNER JOIN customers  
4. ON courses.course_id = course_id  
5. ORDER BY name;   

output

Oracle Insert Statement


In Oracle, INSERT statement is used to add a single record or multiple records into the
table.

Syntax: (Inserting a single record using the Values keyword):

1.  INSERT INTO table  
2. (column1, column2, ... column_n )  
3. VALUES  
4. (expression1, expression2, ... expression_n );   

Syntax: (Inserting multiple records using a SELECT statement):

1. INSERT INTO table  
2. (column1, column2, ... column_n )  
3. SELECT expression1, expression2, ... expression_n  
4. FROM source_table  
5. WHERE conditions;   

Parameters:
1) table: The table to insert the records into.

2) column1, column2, ... column_n:

The columns in the table to insert values.

3) expression1, expression2, ... expression_n:

The values to assign to the columns in the table. So column1 would be assigned the value of
expression1, column2 would be assigned the value of expression2, and so on.

4) source_table:

The source table when inserting data from another table.

5) conditions:

The conditions that must be met for the records to be inserted.

Oracle Insert Example: By VALUE keyword


It is the simplest way to insert elements to a database by using VALUE keyword.

See this example:

Consider here the already created suppliers table. Add a new row where the value of
supplier_id is 23 and supplier_name is Flipkart.

See this example:


1. INSERT INTO suppliers  
2. (supplier_id, supplier_name)  
3. VALUES  
4. (50, 'Flipkart');  
Output:
1 row(s) inserted.
0.02 seconds

Oracle Insert Example: By SELECT statement


This method is used for more complicated cases of insertion. In this method insertion is
done by SELECT statement. This method is used to insert multiple elements.

See this example:

In this method, we insert values to the "suppliers" table from "customers" table. Both tables
are already created with their respective columns.
Execute this query:
1. INSERT INTO suppliers  
2. (supplier_id, supplier_name)  
3. SELECT age, address  
4. FROM customers  
5. WHERE age > 20;  
Output:
4 row(s) inserted.

0.00 seconds

You can even check the number of rows that you want to insert by following statement:

1. SELECT count(*)  
2. FROM customers  
3. WHERE age > 20;  
Output:
Count(*)
4

Oracle INSERT ALL statement


The Oracle INSERT ALL statement is used to insert multiple rows with a single INSERT
statement. You can insert the rows into one table or multiple tables by using only one SQL
command.

Syntax

1. INSERT ALL  
2.   INTO table_name (column1, column2, column_n) VALUES (expr1, expr2, expr_n)  
3.   INTO table_name(column1, column2, column_n) VALUES (expr1, expr2, expr_n)  
4.   INTO table_name (column1, column2, column_n) VALUES (expr1, expr2, expr_n)  
5. SELECT * FROM dual;  

Parameters
1) table_name: it specifies the table in which you want to insert your records.

2) column1, column2, column_n: this specifies the columns in the table to insert values.

3) expr1, expr2, expr_n: this specifies the values to assign to the columns in the table.

Oracle INSERT ALL Example


This example specifies how to insert multiple records in one table. Here we insert three rows
into the "suppliers" table.

1. INSERT ALL  
2.   INTO suppliers (supplier_id, supplier_name) VALUES (20, 'Google')  
3.   INTO suppliers (supplier_id, supplier_name) VALUES (21, 'Microsoft')  
4.   INTO suppliers (supplier_id, supplier_name) VALUES (22, 'Apple')  
5. SELECT * FROM dual;  

Output

3 row(s) inserted.
0.02 seconds

This is totally equivalent to the following three INSERT statements.

1. INSERT INTO suppliers (supplier_id, supplier_name) VALUES (1000, 'Google');  
2. INSERT INTO suppliers (supplier_id, supplier_name) VALUES (2000, 'Microsoft'); 
 
3. INSERT INTO suppliers (supplier_id, supplier_name) VALUES (3000, 'Apple');  

Oracle INSERT ALL Example: (Insert into multiple


tables)
The INSERT ALL statement can also be used to insert multiple rows into more than one
table by one command only.

In the following example, we are going to insert records into the both "suppliers" and
"customers" tables.

1. INSERT ALL  
2.   INTO suppliers (supplier_id, supplier_name) VALUES (30, 'Google')  
3.   INTO suppliers (supplier_id, supplier_name) VALUES (31, 'Microsoft')  
4.   INTO customers (age, name, address) VALUES (29, 'Luca Warsi', 'New York') 
 
5. SELECT * FROM dual;  

Output

3 row(s) inserted.
0.03 seconds
Here, total 3 rows are inserted, 2 rows are inserted into the suppliers table and one row into
the customers table.

Oracle UPDATE Statement


In Oracle, UPDATE statement is used to update the existing records in a table. You can
update a table in 2 ways.

Traditional Update table method


Syntax:

1. UPDATE table  
2. SET column1 = expression1,  
3.     column2 = expression2,  
4.     ...  
5.     column_n = expression_n  
6. WHERE conditions;  

Update Table by selecting rocords from another table


Syntax:

1. UPDATE table1  
2. SET column1 = (SELECT expression1  
3.                FROM table2  
4.                WHERE conditions)  
5. WHERE conditions;   

Parameters:
1) column1, column2, ... column_n:

It specifies the columns that you want to update.

2) expression1, expression2, ...expression_n:

This specifies the values to assign to the column1, column2, ?. column_n.

3) conditions:It specifies the conditions that must be fulfilled for execution of UPDATE
stateme.
Oracle Update Example: (Update single column)
1. UPDATE suppliers  
2. SET supplier_name = 'Kingfisher'  
3. WHERE supplier_id = 2;  

This example will update the supplier_name as "Kingfisher" where "supplier_id" is 2.

Oracle Update Example: (Update multiple columns)


The following example specifies how to update multiple columns in a table. In this example,
two columns supplier_name and supplier_address is updated by a single statement.

1. UPDATE suppliers  
2. SET supplier_address = 'Agra',  
3.     supplier_name = 'Bata shoes'  
4. WHERE supplier_id = 1;  

Output:

1 row(s) updated.
0.06 seconds

Oracle Update Example: (By selecting records from


another table)
1. UPDATE customers  
2. SET name = (SELECT supplier_name  
3.                  FROM suppliers  
4.                  WHERE suppliers.supplier_name = customers.name)  
5. WHERE age < 25;  

Output:

2 row(s) updated.
0.02 seconds

Here, the customers table is updated by fetching the data from "suppliers" table.

Oracle DELETE Statement


In Oracle, DELETE statement is used to remove or delete a single record or multiple records
from a table.

Syntax

1. DELETE FROM table_name  
2. WHERE conditions;   

Parameters
1) table_name: It specifies the table which you want to delete.

2) conditions: It specifies the conditions that must met for the records to be deleted.

Oracle Delete Example: On one condition


1. DELETE FROM customers  
2. WHERE name = 'Sohan';     

This statement will delete all records from the customer table where name is "Sohan".

Oracle Delete Example: On multiple conditions


1. DELETE FROM customers  
2. WHERE last_name = 'Maurya'  
3. AND customer_id > 2;  

This statement will delete all records from the customers table where the last_name is
"Maurya" and the customer_id is greater than 2.

Oracle TRUNCATE TABLE


In Oracle, TRUNCATE TABLE statement is used to remove all records from a table. It works
same as DELETE statement but without specifying a WHERE clause. It is generally used
when you don?t have to worry about rolling back

Once a table is truncated, it can?t be rolled back. The TRUNCATE TABLE statement does not
affect any of the table?s indexes, triggers or dependencies.

Syntax

1. TRUNCATE TABLE [schema_name.]table_name   
Parameters
1) schema_name: This parameter specifies the name of the schema that the table belongs
to. It is optional.

2) table_name: It specifies the table that you want to truncate.

Oracle TRUNCATE Table Example


Consider a table named "customers" and execute the following query to truncate this

1. TRUNCATE TABLE customers;  

Output

Table truncated.
1.11 seconds

Now check the customers table, you will find that there is no data available in that table. It
is equally similar to DELETE TABLE statement in Oracle.

Oracle DELETE Table Example


1. DELETE TABLE customers;  

TRUNCATE TABLE vs DELETE TABLE


Both the statements will remove the data from the "customers" table but the main
difference is that you can roll back the DELETE statement whereas you can't roll back the
TRUNCATE TABLE statement.

Oracle Clauses
Oracle DISTINCT Clause
Oracle DISTINCT clause is used to remove the duplicate records from the result set. It is
only used with SELECT statement.

Syntax:

1. SELECT DISTINCT expressions  
2. FROM tables  
3. WHERE conditions;  
Parameters:
expressions:It specifies the columns that you want to retrieve.

tables: It specifies the table from where you want to retrieve records.

conditions: It specifies the conditions that must be fulfilled.

Oracle DISTINCT Example: (with single expression)


Let's take a table "customers"

Customer table:

1. CREATE TABLE  "CUSTOMERS"   
2.    (    "NAME" VARCHAR2(4000),   
3.     "AGE" NUMBER,   
4.     "SALARY" NUMBER,   
5.     "STATE" VARCHAR2(4000)  
6.    )  
7. /  

Execute this query:


1. SELECT DISTINCT state  
2. FROM customers  
3. WHERE name = 'charu';  

Output:

Oracle DISTINCT Example: (with multiple expressions)


Execute this query:

1. SELECT DISTINCT name, age, salary  
2. FROM customers  
3. WHERE age >= '60';  

Output:

This example specifies distinct name, age and salary of the customer where age is greater
than or equal to 65.

Oracle FROM Clause


FROM clause is a mandatory clause in SELECT expression. It specifies the tables from which
data is to be retrieved.

Syntax:

1. FROM table_name...  
2. Expressions...  

Oracle FROM Clause Example: (with one table)


Let's take an example to explain how to use FROM clause to retrieve data from one table.
Consider a table "customers".

Customer table:
1. CREATE TABLE  "CUSTOMERS"   
2.    (    "NAME" VARCHAR2(4000),   
3.     "AGE" NUMBER,   
4.     "SALARY" NUMBER,   
5.     "STATE" VARCHAR2(4000)  
6.    )  
7. /  

Execute this query:

1. SELECT *  
2. FROM customers  
3. WHERE salary >= 20000  
4. ORDER BY salary ASC;  

Output:
Oracle FROM Clause Example: (with two tables)
Inner Join example:

Let's take two tables "suppliers" and "order1".

Suppliers:

Order1:
Execute the following query:

1. SELECT suppliers.supplier_id, suppliers.supplier_name, order1.order_number  
2. FROM suppliers  
3. INNER JOIN order1  
4. ON suppliers.supplier_id = order1.supplier_id;  

Output:

Oracle ORDER BY Clause


In Oracle, ORDER BY Clause is used to sort or re-arrange the records in the result set. The
ORDER BY clause is only used with SELECT statement.

Syntax:

1. SELECT expressions  
2. FROM tables  
3. WHERE conditions  
4. ORDER BY expression [ ASC | DESC ];   

Parameters:
expressions: It specifies columns that you want to retrieve.

tables: It specifies the table name from where you want to retrieve records.

conditions: It specifies the conditions that must be fulfilled for the records to be selected.

ASC: It is an optional parameter that is used to sort records in ascending order.

DESC: It is also an optional parameter that is used to sort records in descending order.

Oracle ORDER BY Example: (without ASC/DESC


attribute)
Let's take a table "supplier"

Supplier table:

1. CREATE TABLE  "SUPPLIER"   
2.    (    "SUPPLIER_ID" NUMBER,   
3.     "FIRST_NAME" VARCHAR2(4000),   
4.     "LAST_NAME" VARCHAR2(4000)  
5.    )  
6. /  

Execute this Query:

1. SELECT *  
2. FROM supplier  
3. ORDER BY last_name;  

Output:
The above example returns the first_name ordered by last_name in ascending order.

Oracle ORDER BY Example: (sorting in descending


order)
If you want to sort your result in descending order, you should use the DESC attribute in
your ORDER BY clause:

Execute this Query:

1. SELECT *  
2. FROM supplier  
3. ORDER BY last_name DESC;  

Output

The above example returns the first_name ordered by last_name in descending order.

Oracle GROUP BY Clause


In Oracle GROUP BY clause is used with SELECT statement to collect data from multiple
records and group the results by one or more columns.

Syntax:

1. SELECT expression1, expression2, ... expression_n,   
2. aggregate_function (aggregate_expression)  
3. FROM tables  
4. WHERE conditions  
5. GROUP BY expression1, expression2, ... expression_n;   

Parameters:
expression1, expression2, ... expression_n: It specifies the expressions that are not
encapsulated within aggregate function. These expressions must be included in GROUP BY
clause.

aggregate_function: It specifies the aggregate functions i.e. SUM, COUNT, MIN, MAX or
AVG functions.

aggregate_expression: It specifies the column or expression on that the aggregate


function is based on.

tables: It specifies the table from where you want to retrieve records.

conditions: It specifies the conditions that must be fulfilled for the record to be selected.

Oracle GROUP BY Example: (with SUM function)


Let's take a table "salesdepartment"

Salesdepartment table:

1. CREATE TABLE  "SALESDEPARTMENT"   
2.    (    "ITEM" VARCHAR2(4000),   
3.     "SALE" NUMBER,   
4.     "BILLING_ADDRESS" VARCHAR2(4000)  
5.    )  
6. /  
Execute this query:

1. SELECT item, SUM(sale) AS "Total sales"  
2. FROM salesdepartment  
3. GROUP BY item;  

Output

The above example will show the total sales of every individual item.

Oracle GROUP BY Example: (with COUNT function)


Let's take a table "customers"

Here we are creating a table named customers. This table doesn't have any primary key.

Customer table:

1. CREATE TABLE  "CUSTOMERS"   
2.    (    "NAME" VARCHAR2(4000),   
3.     "AGE" NUMBER,   
4.     "SALARY" NUMBER,   
5.     "STATE" VARCHAR2(4000)  
6.    )  
7. /  

Execute this query:

1. SELECT state, COUNT(*) AS "Number of customers"  
2. FROM customers  
3. WHERE salary > 10000  
4. GROUP BY state;  

Output:
Oracle GROUP BY Example: (with MIN function)
Let?s take a table "employees"

Employees table:

1. CREATE TABLE  "EMPLOYEES"   
2.    (    "EMP_ID" NUMBER,   
3.     "NAME" VARCHAR2(4000),   
4.     "AGE" NUMBER,   
5.     "DEPARTMENT" VARCHAR2(4000),   
6.     "SALARY" NUMBER  
7.    )  
8. /  

Execute this query:

1. SELECT department,   
2. MIN(salary) AS "Lowest salary"  
3. FROM employees  
4. GROUP BY department;  

Output:
Oracle GROUP BY Example: (with MAX function)
In this example, we are using "employees" table that is given above.

Execute this query:

1. SELECT department,  
2. MAX(salary) AS "Highest salary"  
3. FROM employees  
4. GROUP BY department;  

Output:

Oracle HAVING Clause


In Oracle, HAVING Clause is used with GROUP BY Clause to restrict the groups of returned
rows where condition is TRUE.

Syntax:

1. SELECT expression1, expression2, ... expression_n,   
2.  aggregate_function (aggregate_expression)  
3. FROM tables  
4. WHERE conditions  
5. GROUP BY expression1, expression2, ... expression_n  
6. HAVING having_condition;   

Parameters:
expression1, expression2, ... expression_n: It specifies the expressions that are not
encapsulated within aggregate function. These expressions must be included in GROUP BY
clause.

aggregate_function: It specifies the aggregate functions i.e. SUM, COUNT, MIN, MAX or
AVG functions.
aggregate_expression: It specifies the column or expression on that the aggregate
function is based on.

tables: It specifies the table from where you want to retrieve records.

conditions: It specifies the conditions that must be fulfilled for the record to be selected.

having_conditions: It specifies the conditions that are applied only to the aggregated
results to restrict the groups of returned rows.

Oracle HAVING Example: (with GROUP BY SUM


function)
Let's take a table "salesdepartment"

Salesdepartment table:

1. CREATE TABLE  "SALESDEPARTMENT"   
2.    (    "ITEM" VARCHAR2(4000),   
3.     "SALE" NUMBER,   
4.     "BILLING_ADDRESS" VARCHAR2(4000)  
5.    )  
6. /  

Execute this query:

1.    
2. SELECT item, SUM(sale) AS "Total sales"  
3. FROM salesdepartment  
4. GROUP BY item  
5. HAVING SUM(sale) < 1000;  

Output:

Oracle HAVING Example: (with GROUP BY COUNT


function)
Let's take a table "customers"

Customer table:

1. CREATE TABLE  "CUSTOMERS"   
2.    (    "NAME" VARCHAR2(4000),   
3.     "AGE" NUMBER,   
4.     "SALARY" NUMBER,   
5.     "STATE" VARCHAR2(4000)  
6.    )  
7. /  
Execute this query:

1. SELECT state, COUNT(*) AS "Number of customers"  
2. FROM customers  
3. WHERE salary > 10000  
4. GROUP BY state  
5. HAVING COUNT(*) >= 2;  

Output:

Oracle HAVING Example: (with GROUP BY MIN


function)
Let's take a table "employees"

Employees table:
1. CREATE TABLE  "EMPLOYEES"   
2.    (    "EMP_ID" NUMBER,   
3.     "NAME" VARCHAR2(4000),   
4.     "AGE" NUMBER,   
5.     "DEPARTMENT" VARCHAR2(4000),   
6.     "SALARY" NUMBER  
7.    )  
8. /  

Execute this query:

1. SELECT department,   
2. MIN(salary) AS "Lowest salary"  
3. FROM employees  
4. GROUP BY department  
5. HAVING MIN(salary) < 15000;  

Output

Oracle HAVING Example: (with GROUP BY MAX


function)
Execute this query:
1. SELECT department,  
2. MAX(salary) AS "Highest salary"  
3. FROM employees  
4. GROUP BY department  
5. HAVING MAX(salary) > 30000;  

Output:

ORACLE OPERATORS
Oracle UNION Operator
In Oracle, UNION operator is used to combine the result sets of two or more Oracle SELECT
statements. It combines the both SELECT statement and removes duplicate rows between
them./p>

Each SELECT statement within the UNION operator must have the same number of fields in
the result sets with similar data types.

Syntax

1. SELECT expression1, expression2, ... expression_n  
2. FROM table1  
3. WHERE conditions  
4. UNION  
5. SELECT expression1, expression2, ... expression_n  
6. FROM table2  
7. WHERE conditions;   

Parameters
1) expression1, expression2, ... expression_n: It specifies the columns that you want
to retrieve.

2) table1, table2: it specifies the tables from where you retrieve the records.

3) conditions: it specifies the conditions that must be fulfilled for the records to be
selected.

Note: The number of expressions must be same in both of the SELECT statements.


Oracle UNION Example: (Fetch single field)
1. SELECT supplier_id  
2. FROM suppliers  
3. UNION  
4. SELECT supplier_id  
5. FROM order_details  

output

In this example, supplier_id is defined in both of the table "suppliers" and "order_details".
After the UNION, it would appear once in the result set because Oracle UNION operator
removes duplicate sets.

Note: If you don't want to remove duplicates, use Oracle UNION ALL operator.

Oracle UNION Example: (Using ORDER BY)


The Oracle UNION operator can be used with ORDER BY clause to orders the results of the
query.

1. SELECT supplier_id, supplier_name  
2. FROM suppliers  
3. WHERE supplier_id <= 20  
4. UNION  
5. SELECT s_id, s_name  
6. FROM shopkeepers  
7. WHERE s_name = 'dhirubhai'  
8. ORDER BY 1;  

Output

In the above example, result is sorted by supplier_name/s_name in ascending order, as


denoted by ORDER BY 1.

Oracle UNION ALL Operator


In Oracle, the UNION ALL operator is used to combine the result sets of 2 or more SELECT
statements. It is different from UNION operator in a way that it does not remove duplicate
rows between the various SELECT statements. It returns all of the rows.

Each SELECT statement within the UNION ALL must have the same number of fields in the
result sets with similar data types.

Difference between UNION and UNION ALL operators


UNION operator removes duplicate rows while UNION ALL operator does not remove
duplicate rows.

Syntax

1. SELECT expression1, expression2, ... expression_n  
2. FROM table1  
3. WHERE conditions  
4. UNION ALL  
5. SELECT expression1, expression2, ... expression_n  
6. FROM table2  
7. WHERE conditions;   
Parameters

1) expression1, expression2, expression_n: It specifies the columns that you want to


retrieve. Number of expressions must be same in both SELECT statements.

2) table1, table2: It specifies the table name that you want to retrieve records from.

3) conditions: It specifies the conditions that must be fulfilled for the records to be
selected.

Oracle UNION ALL Operator Example


1. SELECT supplier_id  
2. FROM suppliers  
3. UNION ALL  
4. SELECT supplier_id  
5. FROM order_details;  

The above example will return the supplier_id multiple times in the result set if the same
value appeared in both the supplier_id and order_details table.

Output

Oracle INTERSECT Operator


In Oracle, INTERSECT Operator is used to return the results of 2 or more SELECT
statement. It picks the common or intersecting records from compound SELECT queries.
Syntax

1. SELECT expression1, expression2, ... expression_n  
2. FROM table1  
3. WHERE conditions  
4. INTERSECT  
5. SELECT expression1, expression2, ... expression_n  
6. FROM table2  
7. WHERE conditions;  

Parameters
1) expression1, expression2, ... expression_n: It specifies the columns that you want
to retrieve.

2) table1, table2: It specifies the tables that you want to retrieve records from.

3) conditions: it specifies the conditions that must be fulfilled for the records to be
selected.

Oracle INTERSECT Example: (with single expression)


Suppliers Table

Suppliers Data
Order_details Table

Order_details Data

1. SELECT supplier_id  
2. FROM suppliers  
3. INTERSECT  
4. SELECT supplier_id  
5. FROM order_details;  

In the above example, the supplier_id appears in both the suppliers and order_details table.
Now the common entries will be returned in the result set.

Output

Oracle INTERSECT Example: (with multiple


expressions)
Supplier Table
Supplier Data

Customer Table

Customer Data

1. SELECT supplier_id, last_name, first_name  
2. FROM supplier  
3. WHERE first_name <> 'dhirubhai'  
4. INTERSECT  
5. SELECT customer_id, last_name, first_name  
6. FROM customer  
7. WHERE customer_id < 5;  

Output

The above example returns the records from the supplier table where the supplier_id,
last_name and first_name values match the customer_id, last_name, and first_name value
of customer table.

Oracle MINUS operator


In Oracle, MINUS operator is used to return all rows in the first SELECT statement that are
not returned by the second SELECT statement.

Each SELECT statement has a dataset and the MINUS operator returns all documents from
the first dataset and then removes all documents from the second dataset.

For example

Syntax

1. SELECT expression1, expression2, ... expression_n  
2. FROM table1  
3. WHERE conditions  
4. MINUS  
5. SELECT expression1, expression2, ... expression_n  
6. FROM table2  
7. WHERE conditions;  

Parameters
1) expression1, expression2, ... expression_n: It specifies the columns that you want
to retrieve.

2) table1, table2: it specifies the tables that you want to retrieve records from.

3) conditions: it specifies the conditions that must be fulfilled for the records to be
selected.

Note: The expressions must be same in number for both the SELECT statement and have
similar datatype.

Oracle MINUS Example


This example will return one field with the same datatype from two tables "suppliers" and
"order_details".

1. SELECT supplier_id  
2. FROM suppliers  
3. MINUS  
4. SELECT supplier_id  
5. FROM order_details;  

Output
ORACLE JOINS
Oracle Joins
Join is a query that is used to combine rows from two or more tables, views, or materialized
views. It retrieves data from multiple tables and creates a new table.

Join Conditions
There may be at least one join condition either in the FROM clause or in the WHERE clause
for joining two tables. It compares two columns from different tables and combines pair of
rows, each containing one row from each table, for which join condition is true.

Types of Joins
o Inner Joins (Simple Join)

o Outer Joins

o Left Outer Join (Left Join)

o Right Outer Join (Right Join)

o Full Outer Join (Full Join)

o Equijoins

o Self Joins

o Cross Joins (Cartesian Products)

o Antijoins

o Semijoins
Oracle INNER JOIN
Inner Join is the simplest and most common type of join. It is also known as simple join. It
returns all rows from multiple tables where the join condition is met.

Syntax

1. SELECT columns  
2. FROM table1   
3. INNER JOIN table2  
4. ON table1.column = table2.column;   

Image representation of Inner Join

Oracle INNER JOIN Example


Let's take an example to perform Inner Join on two tables "Suppliers" and "Order1".

Suppliers
Order1

This example will return all rows from "suppliers" and "order1" table where there is a
matching supplier_id value in both the suppliers and order1 tables.

Execute the following query


1. SELECT suppliers.supplier_id, suppliers.supplier_name, order1.order_number  
2. FROM suppliers   
3. INNER JOIN order1  
4. ON suppliers.supplier_id = order1.supplier_id;  

Output

Oracle OUTER JOIN


An outer join is similar to equijoin but it gets also the non-matched rows from the table. It
is categorized in Left Outer Join, Right Outer Join and Full Outer Join by Oracle 9i ANSI/ISO
1999 standard.
Left Outer Join
Left Outer Join returns all rows from the left (first) table specified in the ON condition and
only those rows from the right (second) table where the join condition is met.

Syntax

1. SELECT columns  
2. FROM table1  
3. LEFT [OUTER] JOIN table2  
4. ON table1.column = table2.column;   

Image representation of left outer join

Example

In this example, we are performing left outer join on the already created tables ?suppliers?
and ?order1?.

The following example would return all records from table ?suppliers? and only those
records from table ?order1? where the join fields are equal.

Execute this query

1. SELECT suppliers.supplier_id, suppliers.supplier_name, order1.order_number  
2. FROM suppliers  
3. LEFT OUTER JOIN order1  
4. ON suppliers.supplier_id = order1.supplier_id;  

Output
Right Outer Join
The Right Outer Join returns all rows from the right-hand table specified in the ON condition
and only those rows from the other table where the join condition is met.

Syntax

1. SELECT columns  
2. FROM table1  
3. RIGHT [OUTER] JOIN table2  
4. ON table1.column = table2.column;   

Image representation of Right Outer Join

Example

In this example, we are performing right outer join on the already created tables ?suppliers?
and ?order1?.
The following example would return all rows from the order1 table and only those rows from
the suppliers table where the join condition is met.

Execute this query

1. SELECT order1.order_number, order1.city, suppliers.supplier_name  
2. FROM suppliers  
3. RIGHT OUTER JOIN order1  
4. ON suppliers.supplier_id = order1.supplier_id;  

Output

Full Outer Join


The Full Outer Join returns all rows from the left hand table and right hand table. It places
NULL where the join condition is not met.

Syntax

1. SELECT columns  
2. FROM table1  
3. FULL [OUTER] JOIN table2  
4. ON table1.column = table2.column;   

Image representation of Full Outer Join

Example
In this example, we are performing full outer join on the already created tables ?suppliers?
and ?order1?.

The following example will return all rows from the ?suppliers? table and all rows from the ?
order1? table and whenever the join condition is not met, it places the NULL value.

Execute this query

1. SELECT suppliers.supplier_id, suppliers.supplier_name, order1.order_number  
2. FROM suppliers  
3. FULL OUTER JOIN order1  
4. ON suppliers.supplier_id = order1.supplier_id;  

Output

Oracle EQUI JOIN


Oracle Equi join returns the matching column values of the associated tables. It uses a
comparison operator in the WHERE clause to refer equality.

Syntax

1. SELECT column_list   
2. FROM table1, table2....  
3. WHERE table1.column_name =  
4. table2.column_name;  
Equijoin also can be performed by using JOIN keyword followed by ON keyword and then
specifying names of the columns along with their associated tables to check equality.

Syntax

1. SELECT *  
2. FROM table1   
3. JOIN table2  
4. [ON (join_condition)]   

Oracle EQUI JOIN Example


Let' take two tables "agents" and "customer".

Agents table

Agent data

Customer table
Customer data

Execute this query

1. SELECT agents.agent_city,customer.last_name,    
2. customer.first_name   
3. FROM agents,customer    
4. WHERE agents.agent_id=customer.customer_id;    

Output

Oracle SELF JOIN


Self Join is a specific type of Join. In Self Join, a table is joined with itself (Unary
relationship). A self join simply specifies that each rows of a table is combined with itself
and every other row of the table.
Syntax

1. SELECT a.column_name, b.column_name...   
2. FROM table1 a, table1 b   
3. WHERE a.common_filed = b.common_field;   

Oracle SELF JOIN Example


Let's take a table "customers".

Join this table using SELF JOIN as follows:

1. SELECT  a.name, b.age, a.SALARY  
2. FROM CUSTOMERS a, CUSTOMERS b  
3. WHERE a.SALARY < b.SALARY;  

Output
Oracle Cross Join (Cartesian Products)
The CROSS JOIN specifies that all rows from first table join with all of the rows of second
table. If there are "x" rows in table1 and "y" rows in table2 then the cross join result set
have x*y rows. It normally happens when no matching join columns are specified.

In simple words you can say that if two tables in a join query have no join condition, then
the Oracle returns their Cartesian product.

Syntax

1. SELECT *   
2. FROM table1   
3. CROSS JOIN table2;  

Or

1. SELECT * FROM table1, table2  

Both the above syntax are same and used for Cartesian product. They provide similar result
after execution.

Image representation of cross join

Oracle Cross Join Example


Let's take two tables "customer" and "supplier".

Customer table detail


1. CREATE TABLE  "CUSTOMER"   
2.    (    "CUSTOMER_ID" NUMBER,   
3.     "FIRST_NAME" VARCHAR2(4000),   
4.     "LAST_NAME" VARCHAR2(4000)  
5.    )  
6. /  

Supplier table detail

1. CREATE TABLE  "SUPPLIER"   
2.    (    "SUPPLIER_ID" NUMBER,   
3.     "FIRST_NAME" VARCHAR2(4000),   
4.     "LAST_NAME" VARCHAR2(4000)  
5.    )  
6. /  

Execute this query

1. SELECT * FROM customer,supplier  

Output
Oracle Anti Join
Anti-join is used to make the queries run faster. It is a very powerful SQL construct Oracle
offers for faster queries.

Anti-join between two tables returns rows from the first table where no matches are found
in the second table. It is opposite of a semi-join. An anti-join returns one copy of each row
in the first table for which no match is found.

Anti-joins are written using the NOT EXISTS or NOT IN constructs.

Example

Let's take two tables "departments" and "customer"

Departments table

1. CREATE TABLE  "DEPARTMENTS"   
2.    (    "DEPARTMENT_ID" NUMBER(10,0) NOT NULL ENABLE,   
3.     "DEPARTMENT_NAME" VARCHAR2(50) NOT NULL ENABLE,   
4.      CONSTRAINT "DEPARTMENTS_PK" PRIMARY KEY ("DEPARTMENT_ID") ENABL
E  
5.    )  
6. /  

Customer table

1. CREATE TABLE  "CUSTOMER"   
2.    (    "CUSTOMER_ID" NUMBER,   
3.     "FIRST_NAME" VARCHAR2(4000),   
4.     "LAST_NAME" VARCHAR2(4000),   
5.     "DEPARTMENT_ID" NUMBER  
6.    )  
7. /  

Execute this query

1. SELECT   departments.department_id, departments.department_name  
2.         FROM     departments  
3.         WHERE    NOT EXISTS  
4.                  (  
5.                  SELECT 1  
6.                  FROM   customer  
7.                  WHERE customer.department_id = departments.department_id  
8.                  )  
9.         ORDER BY departments.department_id;  

Output

Oracle Semi Join


Semi-join is introduced in Oracle 8.0. It provides an efficient method of performing a
WHERE EXISTS sub-query.

A semi-join returns one copy of each row in first table for which at least one match is found.

Semi-joins are written using the EXISTS construct.

Oracle Semi Join Example


Let's take two tables "departments" and "customer"

Departments table

1. CREATE TABLE  "DEPARTMENTS"   
2.    (    "DEPARTMENT_ID" NUMBER(10,0) NOT NULL ENABLE,   
3.     "DEPARTMENT_NAME" VARCHAR2(50) NOT NULL ENABLE,   
4.      CONSTRAINT "DEPARTMENTS_PK" PRIMARY KEY ("DEPARTMENT_ID") ENABL
E  
5.    )  
6. /  
7.    
Customer table

1. CREATE TABLE  "CUSTOMER"   
2.    (    "CUSTOMER_ID" NUMBER,   
3.     "FIRST_NAME" VARCHAR2(4000),   
4.     "LAST_NAME" VARCHAR2(4000),   
5.     "DEPARTMENT_ID" NUMBER  
6.    )  
7. /  

Execute this query

1. SELECT   departments.department_id, departments.department_name  
2.         FROM     departments  
3.         WHERE    EXISTS  
4.                  (  
5.                  SELECT 1  
6.                  FROM   customer  
7.                  WHERE customer.department_id = departments.department_id  
8.                  )  
9.         ORDER BY departments.department_id;  

Output

Difference between anti-join and semi-join


While a semi-join returns one copy of each row in the first table for which at least one
match is found, an anti-join returns one copy of each row in the first table for which no
match is found.

Oracle Procedures
A procedure is a group of PL/SQL statements that can be called by name. The call
specification (sometimes called call spec) specifies a java method or a third-generation
language routine so that it can be called from SQL and PL/SQL.

Create Procedure
Syntax

1. CREATE [OR REPLACE] PROCEDURE procedure_name  
2.     [ (parameter [,parameter]) ]  
3. IS  
4.     [declaration_section]  
5. BEGIN  
6.     executable_section  
7. [EXCEPTION  
8.     exception_section]  
9. END [procedure_name];  

Following are the three types of procedures that must be defined to create a procedure.

o IN: It is a default parameter. It passes the value to the subprogram.

o OUT: It must be specified. It returns a value to the caller.


o IN OUT: It must be specified. It passes an initial value to the subprogram and
returns an updated value to the caller.

Oracle Create procedure example


In this example, we are going to insert record in the "user" table. So you need to create
user table first.

Table creation:

1. create table user(id number(10) primary key,name varchar2(100));  

Now write the procedure code to insert record in user table.

Procedure Code:

1. create or replace procedure "INSERTUSER"    
2. (id IN NUMBER,    
3. name IN VARCHAR2)    
4. is    
5. begin    
6. insert into user values(id,name);    
7. end;    
8. /       

Output:

Procedure created.

Oracle program to call procedure


Let's see the code to call above created procedure.

1. BEGIN    
2.    insertuser(101,'Rahul');  
3.    dbms_output.put_line('record inserted successfully');    
4. END;    
5. /    

Now, see the "USER" table, you will see one record is inserted.
ID Name

101 Rahul

Oracle Drop Procedure


Syntax

1. DROP PROCEDURE procedure_name;   

Example to drop procedure

1. DROP PROCEDURE pro1;  

Oracle Function
A function is a subprogram that is used to return a single value. You must declare and
define a function before invoking it. It can be declared and defined at a same time or can be
declared first and defined later in the same block.

CREATE function in Oracle


Syntax

1. CREATE [OR REPLACE] FUNCTION function_name  
2.    [ (parameter [,parameter]) ]  
3. RETURN return_datatype  
4. IS | AS  
5.  [declaration_section]  
6. BEGIN  
7.    executable_section  
8. [EXCEPTION  
9.    exception_section]  
10. END [function_name];  

You must have define some parametrs before creating a procedure or a function. These
parameters are

o IN: It is a default parameter. It passes the value to the subprogram.

o OUT: It must be specified. It returns a value to the caller.

o IN OUT: It must be specified. It passes an initial value to the subprogram and


returns an updated value to the caller.

Oracle Function Example


Let's see a simple example to create a function.

1. create or replace function adder(n1 in number, n2 in number)    
2. return number    
3. is     
4. n3 number(8);    
5. begin    
6. n3 :=n1+n2;    
7. return n3;    
8. end;    
9. /    

Now write another program to call the function.

1. DECLARE    
2.    n3 number(2);    
3. BEGIN    
4.    n3 := adder(11,22);    
5.    dbms_output.put_line('Addition is: ' || n3);    
6. END;    
7. /    

Output:

Addition is: 33
Statement processed.
0.05 seconds
Another Oracle Function Example
Let's take an example to demonstrate Declaring, Defining and Invoking a simple PL/SQL
function which will compute and return the maximum of two values.

1. DECLARE  
2.    a number;  
3.    b number;  
4.    c number;  
5. FUNCTION findMax(x IN number, y IN number)   
6. RETURN number  
7. IS  
8.     z number;  
9. BEGIN  
10.    IF x > y THEN  
11.       z:= x;  
12.    ELSE  
13.       Z:= y;  
14.    END IF;  
15.   
16.    RETURN z;  
17. END;   
18. BEGIN  
19.    a:= 23;  
20.    b:= 45;  
21.   
22.    c := findMax(a, b);  
23.    dbms_output.put_line(' Maximum of (23,45): ' || c);  
24. END;  
25. /  

Output:

Maximum of (23,45): 45
Statement processed.
0.02 seconds

Oracle function example using table


Let's take a customer table. This example illustrates creating and calling a standalone
function. This function will return the total number of CUSTOMERS in the customers table.

Create customers table and have records in it.

Customers

Id Name Department Salary

1 alex web developer 35000

2 ricky program developer 45000

3 mohan web designer 35000

4 dilshad database manager 44000

Create Function:

1. CREATE OR REPLACE FUNCTION totalCustomers  
2. RETURN number IS  
3.    total number(2) := 0;  
4. BEGIN  
5.    SELECT count(*) into total  
6.    FROM customers;  
7.     RETURN total;  
8. END;  
9. /  

After the execution of above code, you will get the following result.

Function created.

Calling Oracle Function:

1. DECLARE  
2.    c number(2);  
3. BEGIN  
4.    c := totalCustomers();  
5.    dbms_output.put_line('Total no. of Customers: ' || c);  
6. END;  
7. /  

After the execution of above code in SQL prompt, you will get the following result.

Total no. of Customers: 4


PL/SQL procedure successfully completed.

Oracle Recursive Function


You already know that a program or a subprogram can call another subprogram. When a
subprogram calls itself, it is called recursive call and the process is known as recursion.

Example to calculate the factorial of a number


Let's take an example to calculate the factorial of a number. This example calculates the
factorial of a given number by calling itself recursively.

1. DECLARE  
2.    num number;  
3.    factorial number;  
4.   
5. FUNCTION fact(x number)  
6. RETURN number   
7. IS  
8.    f number;  
9. BEGIN  
10.    IF x=0 THEN  
11.       f := 1;  
12.    ELSE  
13.       f := x * fact(x-1);  
14.    END IF;  
15. RETURN f;  
16. END;  
17.   
18. BEGIN  
19.    num:= 6;  
20.    factorial := fact(num);  
21.    dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);  
22. END;  
23. /  

After the execution of above code at SQL prompt, it produces the following result.

Factorial 6 is 720
PL/SQL procedure successfully completed.

Oracle Drop Function


If you want to remove your created function from the database, you should use the
following syntax.

Syntax:

1. DROP FUNCTION function_name;  

Oracle Cursor
A cursor is a pointer to a private SQL area that stores information about the processing of a
SELECT or DML statements like INSERT, UPDATE, DELETE or MERGE.

Cursor is a mechanism which facilitates you to assign a name to a SELECT statement and
manipulate the information within that SQL statement.

How to declare cursor


Syntax

1. CURSOR cursor_name  
2. IS  
3.   SELECT_statement;   

Let's see how to define a cursor called c1. We are using a table name "course" having
columns "course_id" and "course_name".

Example

1. CURSOR c1  
2. IS  
3.   SELECT course_id  
4.   FROM courses  
5.   WHERE course_name = name_in;  

In the above example, the result set of this cursor is all course_id whose course_name
matches the variable called name_in.

How to use cursor in a function


Example

1. CREATE OR REPLACE Function FindCourse  
2.    ( name_in IN varchar2 )  
3.    RETURN number  
4. IS  
5.  cnumber number;  
6. CURSOR c1  
7.    IS  
8.      SELECT course_id  
9.      FROM courses  
10.      WHERE course_name = name_in;  
11. BEGIN  
12.  OPEN c1;  
13.    FETCH c1 INTO cnumber;  
14.  if c1%notfound then  
15.       cnumber := 9999;  
16.    end if;  
17.  CLOSE c1;  
18. RETURN cnumber;  
19. END;  

Output

Function created.
0.09 seconds

How to open a cursor


After the declaration of the cursor, you have to use the open statement to open the cursor.
Syntax

1. OPEN cursor_name;  

Example

1. OPEN c1;  

How to use open cursor in a function


This function specifies how to use the open statement.

Example

1. CREATE OR REPLACE Function FindCourse  
2.   ( name_in IN varchar2 )  
3.   RETURN number  
4. IS  
5.    cnumber number;  
6. CURSOR c1  
7.    IS  
8.      SELECT course_id  
9.      FROM courses  
10.    WHERE course_name = name_in;  
11. BEGIN  
12. OPEN c1;  
13.    FETCH c1 INTO cnumber;  
14. if c1%notfound then  
15.       cnumber := 9999;  
16.  end if;  
17. CLOSE c1;  
18. RETURN cnumber;  
19. END;  

Output

Function created.
0.09 seconds

How to fetch rows from cursor


This statement is used after declaring and opening your cursor. It is used to fetch rows from
cursor.

Syntax

1. FETCH cursor_name INTO variable_list;   

Parameters

1) cursor_name:It specifies the name of the cursor that you wish to fetch rows.

2) variable_list: It specifies the list of variables that you wish to store the cursor result set
in.

Example:

Consider a cursor defined as

1. CURSOR c1  
2. IS  
3.    SELECT course_id  
4.    FROM courses  
5.    WHERE course_name = name_in;  

Statement used for fetching data

1. FETCH c1 into cnumber;  

Let's take an example to fetch course_id into the variable called cnumber.

1. CREATE OR REPLACE Function FindCourse  
2.    ( name_in IN varchar2 )  
3.    RETURN number  
4. IS  
5.    cnumber number;  
6.  CURSOR c1  
7.    IS  
8.      SELECT course_id  
9.      FROM courses  
10.      WHERE course_name = name_in;  
11. BEGIN  
12.  OPEN c1;  
13.    FETCH c1 INTO cnumber;  
14. if c1%notfound then  
15.   cnumber := 9999;  
16.    end if;  
17.  CLOSE c1;  
18. RETURN cnumber;  
19. END;   

How to close cursor


CLOSE statement is a final step and it is used to close the cursor once you have finished
using it.

Syntax

1. CLOSE cursor_name;  

Statement for closing cursor

1. CLOSE c1;  

Example

The following example specifies how to close the cursor.

1. CREATE OR REPLACE Function FindCourse  
2.    ( name_in IN varchar2 )  
3.    RETURN number  
4. IS  
5. cnumber number;  
6. CURSOR c1  
7.    IS  
8.      SELECT course_id  
9.      FROM courses  
10.      WHERE course_name = name_in;  
11. BEGIN  
12. OPEN c1;  
13.    FETCH c1 INTO cnumber;  
14. if c1%notfound then  
15.       cnumber := 9999;  
16.    end if;  
17. CLOSE c1;  
18. RETURN cnumber;  
19. END;  

Cursor within cursor


It is also possible to declare a cursor within a cursor. the following example specifies how to
declare a cursor within a cursor.

In this example, there is a cursor named get_tables that retrieves the owner and
table_name values. These values are then used in a second cursor called get_columns.

Example

1. CREATE OR REPLACE PROCEDURE MULTIPLE_CURSORS_PROC is  
2.    v_owner varchar2(40);  
3.    v_table_name varchar2(40);  
4.    v_column_name varchar2(100);  
5.      
6.    /* First cursor */  
7.    CURSOR get_tables IS  
8.      SELECT DISTINCT tbl.owner, tbl.table_name  
9.      FROM all_tables tbl  
10.      WHERE tbl.owner = 'SYSTEM';  
11.        
12.    /* Second cursor */  
13.    CURSOR get_columns IS  
14.      SELECT DISTINCT col.column_name  
15.      FROM all_tab_columns col  
16.      WHERE col.owner = v_owner  
17.      AND col.table_name = v_table_name;  
18.        
19.    BEGIN  
20.      
21.    -- Open first cursor  
22.    OPEN get_tables;  
23.    LOOP  
24.       FETCH get_tables INTO v_owner, v_table_name;  
25.         
26.       -- Open second cursor  
27.       OPEN get_columns;  
28.       LOOP  
29.          FETCH get_columns INTO v_column_name;  
30.       END LOOP;  
31.      CLOSE get_columns;  
32.     END LOOP;  
33.    CLOSE get_tables;  
34.   EXCEPTION  
35.    WHEN OTHERS THEN  
36.  raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- 
'||SQLERRM);  
37. end MULTIPLE_CURSORS_PROC;  

Output

Procedure created.
0.16 seconds

Note: You have to continuously open and close the second cursor each time a new record is
retrieved from the first cursor. That way, the second cursor will use the new variable values
from the first cursor.

Oracle Trigger
In Oracle, you can define procedures that are implicitly executed when an INSERT, UPDATE
or DELETE statement is issued against the associated table. These procedures are called
database triggers.

There are six CREATE TRIGGER statements according to their firing points.

Firing Point: BEFORE


o BEFORE INSERT TRIGGER

o BEFORE UPDATE TRIGGER

o BEFORE DELETE TRIGGER

Firing Point: AFTER


o AFTER INSERT TRIGGER

o AFTER UPDATE TRIGGER

o AFTER DELETE TRIGGER

Trigger Topics
1) Oracle BEFORE INSERT/UPDATE/DELETE Trigger

2) Oracle AFTER INSERT/UPDATE/DELETE Trigger

3) Oracle DROP Trigger

4) Oracle DISABLE Trigger

5) Oracle ENABLE Trigger

Oracle Before INSERT/UPDATE/DELETE


Trigger
This statement specifies that Oracle will fire this trigger BEFORE the INSERT/UPDATE or
DELETE operation is executed.

Syntax

1. CREATE [ OR REPLACE ] TRIGGER trigger_name  
2. BEFORE INSERT or UPDATE or DELETE  
3.  ON table_name  
4.   [ FOR EACH ROW ]  
5. DECLARE  
6.    -- variable declarations  
7. BEGIN  
8.    -- trigger code  
9. EXCEPTION  
10.    WHEN ...  
11.    -- exception handling  
12. END;  

Parameters
OR REPLACE: It is an optional parameter. It is used to re-create the trigger if it already
exists. It facilitates you to change the trigger definition without using a DROP TRIGGER
statement.

trigger_name: It specifies the name of the trigger that you want to create.

BEFORE INSERT or UPDATE or DELETE: It specifies that the trigger will be fired before
the INSERT or UPDATE or DELETE operation is executed.

table_name: It specifies the name of the table on which trigger operation is being
performed.

Limitations
o BEFORE trigger cannot be created on a view.

o You cannot update the OLD values.

o You can only update the NEW values.

Oracle BEFORE Trigger Example


Consider, you have a "suppliers" table with the following parameters.

1. CREATE TABLE  "SUPPLIERS"   
2.    (    "SUPPLIER_ID" NUMBER,   
3.     "SUPPLIER_NAME" VARCHAR2(4000),   
4.     "SUPPLIER_ADDRESS" VARCHAR2(4000)  
5.    )  
6. /  

You can use the following CREATE TRIGGER query to create a BEFORE INSERT or UPDATE
or DELETE Trigger:

1. CREATE OR REPLACE TRIGGER  "SUPPLIERS_T1"   
2. BEFORE  
3. insert or update or delete on "SUPPLIERS"  
4. for each row  
5. begin  
6. when the person performs insert/update/delete operations into the table.  
7. end;  
8. /  
9. ALTER TRIGGER  "SUPPLIERS_T1" ENABLE  
10. /  

Here the trigger name is "SUPPLIERS_T1" and it is fired BEFORE the insert or update or
delete operation is executed on the table "suppliers".

Oracle After INSERT/UPDATE/DELETE Trigger


This statement specifies that Oracle will fire this trigger AFTER the INSERT/UPDATE or
DELETE operation is executed.

Syntax

1. CREATE [ OR REPLACE ] TRIGGER trigger_name  
2. AFTER INSERT or UPDATE or DELETE  
3.  ON table_name  
4.   [ FOR EACH ROW ]  
5. DECLARE  
6.    -- variable declarations  
7. BEGIN  
8.    -- trigger code  
9. EXCEPTION  
10.    WHEN ...  
11.    -- exception handling  
12. END;  

Parameters
OR REPLACE: It is an optional parameter. It is used to re-create the trigger if it already
exists. It facilitates you to change the trigger definition without using a DROP TRIGGER
statement.

trigger_name: It specifies the name of the trigger that you want to create.
AFTER INSERT or UPDATE or DELETE: It specifies that the trigger will be fired after the
INSERT or UPDATE or DELETE operation is executed.

table_name: It specifies the name of the table on which trigger operation is being
performed.

Limitations
o AFTER trigger cannot be created on a view.

o You cannot update the OLD values.

o You can only update the NEW values.

Oracle AFTER Trigger Example


Consider, you have a "suppliers" table with the following parameters.

1. CREATE TABLE  "SUPPLIERS"   
2.    (    "SUPPLIER_ID" NUMBER,   
3.     "SUPPLIER_NAME" VARCHAR2(4000),   
4.     "SUPPLIER_ADDRESS" VARCHAR2(4000)  
5.    )  
6. /  

You can use the following CREATE TRIGGER query to create a AFTER INSERT or UPDATE
or DELETE Trigger:

1. CREATE OR REPLACE TRIGGER  "SUPPLIERS_T2"   
2. AFTER  
3. insert or update or delete on "SUPPLIERS"  
4. for each row  
5. begin  
6. when the person performs insert/update/delete operations into the table.  
7. end;  
8. /  
9. ALTER TRIGGER  "SUPPLIERS_T2" ENABLE  
10. /  

Here the trigger name is "SUPPLIERS_T2" and it is fired AFTER the insert or update or
delete operation is executed on the table "suppliers".
Oracle DROP Trigger
In Oracle, DROP TRIGGER statement is used to drop the trigger if you find that you need to
remove it from the database.

Syntax

1. DROP TRIGGER trigger_name;   

Parameters
trigger_name: It specifies the name of the trigger that you want to drop.

Oracle DROP Trigger Example


1. DROP TRIGGER SUPPLIERS_T1;   

It will drop the trigger name "SUPPLIERS_T1" from the table "SUPPLIERS".

Oracle DISABLE Trigger


The ALTER TRIGGER statement is used to disable a trigger.

Syntax

1. ALTER TRIGGER trigger_name DISABLE;   

Parameters
trigger_name: It specifies the name of the trigger that you want to disable.

Oracle DISABLE Trigger Example


1. ALTER TRIGGER SUPPLIERS_T2 DISABLE;   
This example will disable the trigger called "SUPPLIERS_T2" from the table "SUPPLIERS".

Oracle DISABLE ALL Triggers Example


If there is more than one trigger in a table and you want to disable all the triggers from the
database then you can do it by ALTER TABLE statement.

Syntax

1. ALTER TABLE table_name DISABLE ALL TRIGGERS;   

Example

1. ALTER TABLE SUPPLIERS DISABLE ALL TRIGGERS;  

This example will disable all triggers from the table "suppliers".

Oracle ENABLE Trigger


The ALTER TRIGGER statement is used to enable a trigger.

Syntax

1. ALTER TRIGGER trigger_name ENABLE;   

Parameters
trigger_name: It specifies the name of the trigger that you want to enable.

Oracle ENABLE Trigger Example


1. ALTER TRIGGER SUPPLIERS_T1 ENABLE;   

This example will enable the trigger named "SUPPLIERS_T1" in the "SUPPLIERS" table.
Oracle ENABLE ALL Triggers Example
Syntax

1. ALTER TABLE table_name ENABLE ALL TRIGGERS;  

Example

1. ALTER TABLE SUPPLIERS ENABLE ALL TRIGGERS;  

This example will enable all the triggers on the table name "SUPPLIERS".

Oracle Interview Questions


Oracle is a secured database that is widely used in multinational companies. The frequently
asked questions from oracle database are given below.

1) What are the components of physical database structure of


Oracle database?
Components of physical database structure are given below.

o One or more data files.

o Two or more redo log files.

o One or more control files.


2) What are the components of logical database structure in
Oracle database?
Components of logical database structure.

o Tablespaces

o Database's schema objects

3) What is a tablespace?
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.

4) What is a SYSTEM tablespace and when it is created?


When the database is created in Oracle database system, it automatically generate a
SYSTEM named SYSTEM tablespace. The SYSTEM tablespace contains data dictionary tables
for the entire database.

5) What is an Oracle table?


A table is basic unit of data storage in Oracle database. A table contains all the accessible
information of a user in rows and columns.

6) In the Oracle version 9.3.0.5.0, what does each number


shows?
Oracle version number refers:

o 9 - Major database release number

o 3 - Database maintenance release number

o 0 - Application server release number

o 5 - Component Specific release number

o 0 - Platform Specific release number


7) What is bulk copy or BCP in Oracle?
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.

8) What is the relationship among database, tablespace and data


file?
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.

9) What is a snapshot in Oracle database?


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.

10) What is the difference between hot backup and cold backup in
Oracle? Tell about their benefits also.
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).
11) How many memory layers are in the Oracle shared pool?
Oracle shared pools contains two layers:

1. library cache

2. data dictionary cache

12) What is save point in Oracle database?


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.

13) What is hash cluster in Oracle?


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.

14) What are the various Oracle database objects?


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.

15) What is the difference between pre-select and pre-query?


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.

16) What are the different types of modules in Oracle forms?


Following are the different modules in Oracle forms:

o Form module

o Menu module

o Pl/SQL Library module

o Object Library module

17) What is the usage of ANALYZE command in Oracle?


ANALYZE command is used to perform various functions on index, table, or cluster. The
following list specifies the usage of ANALYZE command in Oracle:

o It is used to identify migrated and chained rows of the table or cluster.

o It is used to validate the structure of the object.

o It helps in collecting the statistics about object used by the optimizer. They are then
stored in the data dictionary.
o It helps in deleting statistics used by object from the data dictionary.

18) Can you create a synonym without having a table?


Yes. We can create a synonym without having a base table.

19) What types of joins are used in writing SUBQUERIES?


o Self join

o Outer Join

o Equi-join
20) What is the usage of control file in Oracle?
In Oracle, control file is used for database recovery. The control file is also used to identify
the database and redo log files that must be opened for database operation to go ahead,
whenever an instance of an ORACLE database begins.

21) What is a synonym?


A synonym is also known as alias for a table, view, sequence or program unit.

22) What are the different types of synonyms?


There are two types of synonyms or alias:

Private: It can only accessed by the owner.

Public: It can be accessed by any database user.

23) What is the usage of synonyms?


o Synonym can be used to hide the real name and owner of an object.

o It provides public access to an object.

o It also provides location transparency for tables, views or program units of a remote
database.
o It simplifies the SQL statements for database users.

24) How do you store pictures in a database?


Yes, you can store pictures in a database using Long Raw Data type. This data type is used
to store binary data for 2 gigabytes of length. However, the table can have only one Long
Raw data type.

25) What is BLOB data type in Oracle?


BLOB data type is a data type with varying length binary string. It is used to store two
gigabytes memory. For BLOB data type, the length needs to be specified in bytes.
26) What is the difference between TRANSLATE and REPLACE
in Oracle?
Translate is used to substitute a character by character while Replace is used to substitute a
single character with a word.

27) What are the different types of database objects?


A list of different types of database objects:

o Tables: This is a set of elements organized in vertical and horizontal fashion.

o Tablespaces: This is a logical storage unit in Oracle.

o Views: It is virtual table derived from one or more tables.

o Indexes: This is a performance tuning method to process the records.

o Synonyms: This is a name for tables.

28) What is the usage of Save Points in Oracle database?


Save Points are used to divide a transaction into smaller phases. It enables rolling back part
of a transaction. There are maximum 5 save points allowed in Oracle Database. Whenever
an error is encountered, it is possible to rollback from the point where the SAVEPOINT has
been saved.

29) What is the difference between post-database commit and


post-form commit?
The post-database commit trigger is executed after Oracle forms issue the commit to
finalized transaction while, the post-form commit is fired during the post and commit
transactions process, after the database commit occurs.
30) What is Logical backup in Oracle?
Logical backup is used to read a set of database records and writing them into a file. An
Export utility is used to take the backup while an Import utility is used to recover from the
backup.

31) What do you understand by Redo Log file mirroring?


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.

32) What is the meaning of recursive hints in Oracle?


The number of times a dictionary table is repeatedly called by various processes is known as
recursive hint. Recursive hint is occurred because of the small size of data dictionary cache.

33) What are the limitations of CHECK constraint?


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.

34) What is the use of GRANT option in IMP command?


GRANT is used to import object grants.

35) What is the use of ROWS option in IMP command?


The ROWS option indicates whether the table rows should be imported.

36) What is the use of INDEXES option in IMP command?


The INDEXES option is used to determine whether indexes are imported.
37) What is the use of IGNORE option in IMP command?
The IGNORE option is used to specify how object creation errors should be handled.

38) What is the use of SHOW option in IMP command?


The SHOW option specifies when the value of show=y, the DDL within the export file is
displayed.

39) What is the use of FILE param in IMP command?


FILE param is used to specify the name of the export file to import. Multiple files can be
listed, separated by commas.

40) How to convert a date to char in Oracle? Give one example.


The to_char() function is used to convert date to character. You can also specify the
format in which you want output.

1. SELECT to_char ( to_date ('12-12-2012', 'DD-MM-YYYY') , 'YYYY-MM-DD') FROM du
al;  

Or,

1. SELECT to_char ( to_date ('12-12-2012', 'DD-MM-YYYY') , 'DD-MM-YYYY') FROM du
al;  

41) What are actual and formal parameters?


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:

1. 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:

1. PROCEDURE raise_sal(empid INTEGER, amt REAL) IS current_salary REAL;  

42) What are the extensions used by Oracle reports?


Oracle reports are use to make business enable with the facility to provide information of all
level within or outside in a secure way. Oracle report uses REP files and RDF file
extensions.

43) How to convert a string to a date in Oracle database?


Syntax: to_date (string , format)

Let us take an example :

1. to_date ('2012-12-12', 'YYYY/MM/DD')  

It will return December 12, 2012.

44) How do you find current date and time in Oracle?


The SYSDATE() function is used in Oracle to find the current date and time of operating
system on which the database is running.

1. SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "Current_Date" FROM D
UAL;  

45) What will be the syntax to find current date and time in format
"YYYY-MM-DD"?
1. SELECT TO_CHAR (SYSDATE, 'YYYY-MM-DD HH24:MI:SS') "Current_Date" FROM D
UAL; 

SQL Interview Questions


There is given sql interview questions and answers that has been asked in many companies.
For PL/SQL interview questions, visit our next page.

1) What is SQL?
SQL stands for structured query language. It is a database language used for database
creation, deletion, fetching rows and modifying rows etc. sometimes it is pronounced as se-
qwell.

2) When SQL appeared?


It appeared in 1974.

3) What are the usages of SQL?


o To execute queries against a database

o To retrieve data from a database

o To inserts records in a database

o To updates records in a database

o To delete records from a database

o To create new databases

o To create new tables in a database

o To create views in a database

4) Does SQL support programming?


No, SQL doesn't have loop or Conditional statement. It is used like commanding language to
access databases.

5) What are the subsets of SQL?


1. Data definition language (DDL)

2. Data manipulation language (DML)

3. Data control language (DCL)


6) What is data definition language?
Data definition language(DDL) allows you to CREATE, ALTER and DELETE database objects
such as schema, tables, view, sequence etc.

7) What is data manipulation language?


Data manipulation language makes user able to access and manipulate data. It is used to
perform following operations.

o Insert data into database

o Retrieve data from the database

o Update data in the database

o Delete data from the database

8) What is data control language?


Data control language allows you to control access to the database. It includes two
commands GRANT and REVOKE.

GRANT: to grant specific user to perform specific task.

REVOKE: to cancel previously denied or granted permissions.

9) What are tables and fields in database?


A table is a set of organized data. It has columns and rows. Columns can be categorized as
vertical, and Rows are horizontal.

A table contains specified number of column called fields but can have any number of rows
which is known as record.

10) What is a primary key?


A primary key is a combination of fields which uniquely specify a row. This is a special kind
of unique key. Primary key values cannot be NULL.
11) What is a foreign key?
A foreign key is specified as a key which is related to the primary key of another table.
Relationship needs to be created between two tables by referencing foreign key with the
primary key of another table.

12) What is a unique key?


A Unique key constraint uniquely identifies each record in the database. This provides
uniqueness for the column or set of columns.

13) What are the type of operators available in SQL?


1. Arithmetic operators

2. Logical operators

3. Comparison operator

14) What is view in SQL?


A view is a virtual table which contains a subset of data within a table. Views are not
virtually present, and it takes less space to store. View can have data of one or more tables
combined, and it is depending on the relationship.

15) What is an Index in SQL?


Index is used to increase the performance and allow faster retrieval of records from the
table. An index creates an entry for each value and it will be faster to retrieve data.

16) Which are the different types of indexes in SQL?


There are three types of Indexes in SQL:

o Unique Index

o Clustered Index
o NonClustered Index

17) What is Unique Index?


Unique Index:

This indexing does not allow the field to have duplicate values if the column is unique
indexed. Unique index can be applied automatically when primary key is defined.

18) What is Clustered Index in SQl?


Clustered Index:

The clustered index is used to reorder the physical order of the table and search based on
the key values. Each table can have only one clustered index.

19) What is NonClustered Index in SQL?


NonClustered Index:

NonClustered Index does not alter the physical order of the table and maintains logical
order of data. Each table can have 999 non-clustered indexes.

20) What is the difference between SQL, MySQL and SQL


Server?
SQL or Structured Query Language is a language which is used to communicate with a
relational database. It provides a way to manipulate and create databases. On the other
hand, MySQL and Microsoft's SQL Server both are relational database management systems
that use SQL as their standard relational database language.

21) What is the difference between SQL and PL/SQL?


SQL or Structured Query Language is a language which is used to communicate with a
relational database. It provides a way to manipulate and create databases. On the other
hand, PL/SQL is a dialect of SQL which is used to enhance the capabilities of SQL. It was
developed by Oracle Corporation in the early 90's. It adds procedural features of
programming languages in SQL.

22) Is it possible to sort a column using a column alias?


Yes. You can use column alias in the ORDER BY clause for sorting.

23) What is the difference between clustered and non clustered


index in SQL?
There are mainly two type of indexes in SQL, Clustered index and non clustered index. The
differences between these two indexes is very important from SQL performance perspective.

1. One table can have only one clustered index but it can have many non clustered
index.(approximately 250).

2. clustered index determines how data is stored physically in table. Actually clustered
index stores data in cluster, related data is stored together so it makes simple to
retrieve data.

3. reading from a clustered index is much faster than reading from non clustered index
from the same table.

4. clustered index sort and store data rows in the table or view based on their key
value, while non cluster have a structure separate from the data row.

24) What is the SQL query to display current date?


There is a built in function in SQL called GetDate() which is used to return current
timestamp.

25) Which are the most commonly used SQL joins?


Most commonly used SQL joins are INNER JOIN and (left/right) OUTER JOIN.
26) What are the different types of joins in SQL?
Joins are used to merge two tables or retrieve data from tables. It depends on the
relationship between tables.

Following are the most commonly used joins in SQL:

o Inner Join

o Right Join

o Left Join

o Full Join

27) What is Inner Join in SQL?


Inner join:

Inner join returns rows when there is at least one match of rows between the tables.

28) What is Right Join in SQL?


Right Join:

Right join is used to retrieve rows which are common between the tables and all rows of
Right hand side table. It returns all the rows from the right hand side table even though
there are no matches in the left hand side table.

29) What is Left Join in SQL?


Left Join:

Left join is used to retrieve rows which are common between the tables and all rows of Left
hand side table. It returns all the rows from Left hand side table even though there are no
matches in the Right hand side table.

30) What is Full Join in SQL?


Full Join:
Full join return rows when there are matching rows in any one of the tables. This means, it
returns all the rows from the left hand side table and all the rows from the right hand side
table.

31) What is "TRIGGER" in SQL?


Trigger allows you to execute a batch of SQL code when an insert, update or delete
command is executed against a specific table.

Actually triggers are special type of stored procedures that are defined to execute
automatically in place or after data modifications.

32) What is self join and what is the requirement of self join?
Self join is often very useful to convert a hierarchical structure to a flat structure. It is used
to join a table to itself as like if that is the second table.

33) What are set operators in SQL?


Union, Intersect or Minus operators are called set operators.

34) What is the difference between BETWEEN and IN condition


operators?
The BETWEEN operator is used to display rows based on a range of values. The IN condition
operator is used to check for values contained in a specific set of values.

35) What is a constraint? Tell me about its various levels.


Constraints are representators of a column to enforce data entity and consistency. There
are two levels :

1. column level constraint

2. table level constraint


36) Write an SQL query to find names of employee start with 'A'?
1. SELECT * FROM Employees WHERE EmpName like 'A%'  

37) Write an SQL query to get third maximum salary of an


employee from a table named employee_table.
1. SELECT TOP 1 salary   
2. FROM (  
3. SELECT TOP 3 salary  
4. FROM employee_table  
5. ORDER BY salary DESC ) AS emp  
6. ORDER BY salary ASC;      

38) What is the difference between DELETE and TRUNCATE


statement in SQL?
The main differences between SQL DELETE and TRUNCATE statements are given below:

No. DELETE TRUNCATE

1 DELETE is a DML command. TRUNCATE is a DDL command.


)

2 We can use WHERE clause in We cannot use WHERE clause with


) DELETE command. TRUNCATE

3 DELETE statement is used to TRUNCATE statement is used to remove


) delete a row from a table all the rows from a table.

4 DELETE is slower than TRUNCATE TRUNCATE statement is faster than


) statement. DELETE statement.

5 You can rollback data after using It is not possible to rollback after using


) DELETE statement. TRUNCATE statement.
39) What is ACID property in database?
ACID property is used to ensure that the data transactions are processed reliably in a
database system.

A single logical operation of a data is called transaction.

ACID is an acronym for Atomicity, Consistency, Isolation, Durability.

Atomicity: it requires that each transaction is all or nothing. It means if one part of the
transaction fails, the entire transaction fails and the database state is left unchanged.

Consistency: the consistency property ensure that the data must meet all validation rules.
In simple words you can say that your transaction never leaves your database without
completing its state.

Isolation: this property ensure that the concurrent property of execution should not be
met. The main goal of providing isolation is concurrency control.

Durability: durability simply means that once a transaction has been committed, it will
remain so, come what may even power loss, crashes or errors.

40) What is the difference among NULL value, zero and blank
space?
Ans: A NULL value is not same as zero or a blank space. A NULL value is a value which is
'unavailable, unassigned, unknown or not applicable'. On the other hand, zero is a number
and blank space is treated as a character.

41) What is the usage of SQL functions?


SQL functions are used for following purpose:

o To perform calculations on data.

o To modify individual data items.

o To manipulate the output.

o To format dates and numbers.

o To convert data types.


42) Which are the different case manipulation functions in SQL?
There are three case manipulation functions in SQL:

o LOWER

o UPPER

o INITCAP

43) What is the usage of NVL function?


The NVL function is used to convert NULL value to a actual value.

44) Which function is used to return remainder in a division


operator in SQL?
The MOD function returns the remainder in a division operation.

45) What is the syntax and use of the COALESCE function?


The syntax of COALESCE function:

1. COALESCE(exp1, exp2, ... expn)  

The COALESCE function is used to return the first non-null expression given in the
parameter list.

46) What is the usage of DISTINCT keyword?


The DISTINCT keyword is used to ensure that the fetched value is only a non-duplicate
value.

PL/SQL Interview Questions


PL/SQL is an advance version of SQL. There are given top list of PL/SQL interview questions
with answer.

1) What is PL/SQL?
PL/SQL stands for procedural language extension to SQL. It supports procedural features of
programming language and SQL both. It was developed by Oracle Corporation in early of
90's to enhance the capabilities of SQL.

2) What is the purpose of using PL/SQL?


PL/SQL is an extension of SQL. While SQL is non-procedural, PL/SQL is a procedural
language designed by Oracle. It is invented to overcome the limitations of SQL.

3) What are the most important characteristics of PL/SQL?


A list of some notable characteristics:

o PL/SQL is a block-structured language.

o It is portable to all environments that support Oracle.

o PL/SQL is integrated with the Oracle data dictionary.

o Stored procedures help better sharing of application.

4) What is PL/SQL table? Why it is used?


Objects of type tables are called PL/SQL tables that are modeled as database table. We can
also say that PL/SQL tables are a way to providing arrays. Arrays are like temporary tables
in memory that are processed very quickly. PL/SQL tables are used to move bulk data. They
simplifies moving collections of data.

5) What are the datatypes available in PL/SQL?


There are two types of datatypes in PL/SQL:
1. Scalar datatypes Example are NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN
etc.

2. Composite datatypes Example are RECORD, TABLE etc.

6) What is the basic structure of PL/SQL?


PL/SQL uses BLOCK structure as its basic structure. Each PL/SQL program consists of SQL
and PL/SQL statement which form a PL/SQL block.

PL/SQL block contains 3 sections.

1. The Declaration Section (optional)

2. The Execution Section (mandatory)

3. The Exception handling Section (optional)

7) What is the difference between FUNCTION, PROCEDURE


AND PACKAGE in PL/SQL?
Function: The main purpose of a PL/SQL function is generally to compute and return a
single value. A function has a return type in its specification and must return a value
specified in that type.

Procedure: A procedure does not have a return type and should not return any value but it
can have a return statement that simply stops its execution and returns to the caller. A
procedure is used to return multiple values otherwise it is generally similar to a function.

Package: A package is schema object which groups logically related PL/SQL types , items
and subprograms. You can also say that it is a group of functions, procedure, variables and
record type statement. It provides modularity, due to this facility it aids application
development. It is used to hide information from unauthorized users.

8) What is exception? What are the types of exceptions?


Exception is an error handling part of PL/SQL. There are two type of exceptions:
pre_defined exception and user_defined exception.
9) How to write a single statement that concatenates the words ?
Hello? and ?World? and assign it in a variable named Greeting?
Greeting := 'Hello' || 'World';

10) Does PL/SQL support CREATE command?


No. PL/SQL doesn't support the data definition commands like CREATE.

11) Write a unique difference between a function and a stored


procedure.
A function returns a value while a stored procedure doesn?t return a value.

12) How exception is different from error?


Whenever an Error occurs Exception arises. Error is a bug whereas exception is a warning or
error condition.

13) What is the main reason behind using an index?


Faster access of data blocks in the table.

14) What are PL/SQL exceptions? Tell me any three.


1. Too_many_rows

2. No_Data_Found

3. Value_error

4. Zero_error etc.
15) How do you declare a user-defined exception?
You can declare the User defined exceptions under the DECLARE section, with the keyword
EXCEPTION.

Syntax:

1. <exception_name> EXCEPTION;  

16) What are some predefined exceptions in PL/SQL?


A list of predefined exceptions in PL/SQL:

o DUP_VAL_ON_INDEX

o ZERO_DIVIDE

o NO_DATA_FOUND

o TOO_MANY_ROWS

o CURSOR_ALREADY_OPEN

o INVALID_NUMBER

o INVALID_CURSOR

o PROGRAM_ERROR

o TIMEOUT _ON_RESOURCE

o STORAGE_ERROR

o LOGON_DENIED

o VALUE_ERROR

o etc.

17) What is a trigger in PL/SQL?


A trigger is a PL/SQL program which is stored in the database. It is executed immediately
before or after the execution of INSERT, UPDATE, and DELETE commands.
18) What is the maximum number of triggers, you can apply on a
single table?
12 triggers.

19) How many types of triggers exist in PL/SQL?


There are 12 types of triggers in PL/SQL that contains the combination of BEFORE, AFTER,
ROW, TABLE, INSERT, UPDATE, DELETE and ALL keywords.

o BEFORE ALL ROW INSERT

o AFTER ALL ROW INSERT

o BEFORE INSERT

o AFTER INSERT etc.

20) What is the difference between execution of triggers and


stored procedures?
A trigger is automatically executed without any action required by the user, while, a stored
procedure is explicitly invoked by the user.

21) What happens when a trigger is associated to a view?


When a trigger is associated to a view, the base table triggers are normally enabled.

22) What is the usage of WHEN clause in trigger?


A WHEN clause specifies the condition that must be true for the trigger to be triggered.

23) How to disable a trigger name update_salary?


ALTER TRIGGER update_salary DISABLE;
24) Which command is used to delete a trigger?
DROP TRIGGER command.

25) what are the two virtual tables available at the time of
database trigger execution?
Table columns are referred as THEN.column_name and NOW.column_name.

For INSERT related triggers, NOW.column_name values are available only.

For DELETE related triggers, THEN.column_name values are available only.

For UPDATE related triggers, both Table columns are available.

26) What is stored Procedure?


A stored procedure is a sequence of statement or a named PL/SQL block which performs
one or more specific functions. It is similar to a procedure in other programming languages.
It is stored in the database and can be repeatedly executed. It is stored as schema object.
It can be nested, invoked and parameterized.

27) What are the different schemas objects that can be created
using PL/SQL?
o Stored procedures and functions

o Packages

o Triggers

o Cursors

28) What do you know by PL/SQL Cursors?


Oracle uses workspaces to execute the SQL commands. When Oracle processes a SQL
command, it opens an area in the memory called Private SQL Area. This area is identified by
the cursor. It allows programmers to name this area and access it?s information.
29) What is the difference between the implicit and explicit
cursors?
Implicit cursor is implicitly declared by Oracle. This is a cursor to all the DDL and DML
commands that return only one row.

Explicit cursor is created for queries returning multiple rows.

30) What will you get by the cursor attribute SQL%ROWCOUNT?


The cursor attribute SQL%ROWCOUNT will return the number of rows that are processed by
a SQL statement.

31) What will you get by the cursor attribute SQL%FOUND?


It returns the Boolean value TRUE if at least one row was processed.

32) What will you get by the cursor attribute SQL%NOTFOUND?


It returns the Boolean value TRUE if no rows were processed.

33) What do you understand by PL/SQL packages?


A PL/SQL package can be specified as a file that groups functions, cursors, stored
procedures, and variables in one place.

34) What are the two different parts of the PL/SQL packages?
PL/SQL packages have the following two parts:

Specification part: It specifies the part where the interface to the application is defined.

Body part: This part specifies where the implementation of the specification is defined.
35) Which command is used to delete a package?
The DROP PACKAGE command is used to delete a package.

36) How to execute a stored procedure?


There are two way to execute a stored procedure.

From the SQL prompt, write EXECUTE or EXEC followed by procedure_name.

1. EXECUTE or [EXEC] procedure_name;  

Simply use the procedure name

1. procedure_name;  

37) What are the advantages of stored procedure?


Modularity, extensibility, reusability, Maintainability and one time compilation.

38) What are the cursor attributes used in PL/SQL?


%ISOPEN: it checks whether the cursor is open or not.

%ROWCOUNT: returns the number of rows affected by DML operations:


INSERT,DELETE,UPDATE,SELECT.

%FOUND: it checks whether cursor has fetched any row. If yes - TRUE.

%NOTFOUND: it checks whether cursor has fetched any row. If no - TRUE.

39) What is the difference between syntax error and runtime


error?
A syntax error can be easily detected by a PL/SQL compiler. For example: incorrect spelling
etc. while, a runtime error is handled with the help of exception-handling section in a
PL/SQL block. For example: SELECT INTO statement, which does not return any rows.
40) Explain the Commit statement.
Following conditions are true for the Commit statement:

o Other users can see the data changes made by the transaction.

o The locks acquired by the transaction are released.

o The work done by the transaction becomes permanent.

41) Explain the Rollback statement?


The Rollback statement is issued when the transaction ends. Following conditions are true
for a Rollback statement:

o The work done in a transition is undone as if it was never issued.

o All locks acquired by transaction are released.

42) Explain the SAVEPOINT statement.


With SAVEPOINT, only part of transaction can be undone.

43) What is mutating table error?


Mutating table error is occurred when a trigger tries to update a row that it is currently
using. It is fixed by using views or temporary tables.

44) What is consistency?


Consistency simply means that each user sees the consistent view of the data.

Consider an example: there are two users A and B. A transfers money to B's account. Here
the changes are updated in A's account (debit) but until it will be updated to B's account
(credit), till then other users can't see the debit of A's account. After the debit of A and
credit of B, one can see the updates. That?s consistency.
45) What is cursor and why it is required?
A cursor is a temporary work area created in a system memory when an SQL statement
is executed.

A cursor contains information on a select statement and the row of data accessed by it. This
temporary work area stores the data retrieved from the database and manipulate this data.
A cursor can hold more than one row, but can process only one row at a time. Cursor are
required to process rows individually for queries.

46) How many types of cursors are available in PL/SQL?


There are two types of cursors in PL/SQL.

1. Implicit cursor, and

2. explicit cursor

starting the oracle server


----------------------------

At the operating system prompt, enter the following command to start SQL Command Line and
connect to the database:

SQLPLUS / AS SYSDBA

The slash (/) indicates that the database should authenticate you with operating system
authentication.

At the SQL Command Line prompt, enter the following command:

STARTUP

If the command is successful, it displays the following output. (System global area sizes will
vary depending on the amount of physical memory in your Oracle Database XE host computer.)

ORACLE instance started.

Total System Global Area 599785472 bytes


Fixed Size 1220804 bytes
Variable Size 180358972 bytes
Database Buffers 415236096 bytes
Redo Buffers 2969600 bytes
Database mounted.
Database opened.

(Optional) Enter the following SQL query to verify that the database started up properly:

select count(*) from hr.employees;

The query results should look similar to the following:

COUNT(*)
----------
107

Enter the following command to exit SQL Command Line:

EXIT

shuttingdown the oracle server


------------------------------

At the SQL Command Line prompt, enter the following command:

SHUTDOWN IMMEDIATE

Note that this command may take a short while to complete. If the command is successful, it
displays the following output:

Database closed.
Database dismounted.
ORACLE instance shut down.

If the command displays no output after a number of minutes, indicating that the shutdown
operation is not proceeding, you can press CTRL-C to interrupt the command, and then enter the
following command:

SHUTDOWN ABORT

The database must go through a recovery process when it starts up after a SHUTDOWN ABORT
command. It is recommended that you enable the recovery process to take place immediately,
after which you can shut down the database normally. To do this, enter the following commands
when the SHUTDOWN ABORT completes:

STARTUP
SHUTDOWN IMMEDIATE
See Oracle Database Administrator's Guide for information on the SHUTDOWN ABORT
command.

Enter the following command to exit SQL Command Line:

EXIT

D:\app\Admin\product\11.1.0\db_1\sqldeveloper\sqldeveloper\bin\sqldeveloper.exe

You might also like