Oracle Tutorial
Oracle Tutorial
Oracle Tutorial
Oracle tutorial provides basic and advanced concepts of Oracle. Our Oracle tutorial is
designed for beginners and professionals.
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.
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.
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. );
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.
CREATE TABLE customers
( customer_id number(10) NOT NULL,
customer_name varchar2(50) NOT NULL,
city varchar2(50)
);
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);
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);
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.
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".
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);
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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. /
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
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
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';
1. SELECT * FROM sup_orders;
Output:
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. SELECT * from customers;
More Details...
1. insert into customers values(101,'rahul','delhi');
More Details...
1. update customers set name='bob', city='london' where id=101;
More Details...
1. delete from customers where id=101;
More Details...
1. truncate table customers;
More Details...
More Details...
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...
1. ALTER TABLE customers
2. ADD age varchar2(50);
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.
1. SELECT *
2. FROM customers;
output
1. SELECT age, address, salary
2. FROM customers
3. WHERE age < 25
4. AND salary > '20000'
5. ORDER BY age ASC, salary DESC;
output
1. INSERT INTO table
2. (column1, column2, ... column_n )
3. VALUES
4. (expression1, expression2, ... expression_n );
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.
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:
5) conditions:
Consider here the already created suppliers table. Add a new row where the value of
supplier_id is 23 and supplier_name is Flipkart.
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
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.
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
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');
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.
1. UPDATE table
2. SET column1 = expression1,
3. column2 = expression2,
4. ...
5. column_n = expression_n
6. WHERE conditions;
1. UPDATE table1
2. SET column1 = (SELECT expression1
3. FROM table2
4. WHERE conditions)
5. WHERE conditions;
Parameters:
1) 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;
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
Output:
2 row(s) updated.
0.02 seconds
Here, the customers table is updated by fetching the data from "suppliers" 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.
This statement will delete all records from the customer table where name is "Sohan".
This statement will delete all records from the customers table where the last_name is
"Maurya" and the customer_id is greater than 2.
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.
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 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.
Customer table:
1. CREATE TABLE "CUSTOMERS"
2. ( "NAME" VARCHAR2(4000),
3. "AGE" NUMBER,
4. "SALARY" NUMBER,
5. "STATE" VARCHAR2(4000)
6. )
7. /
Output:
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.
Syntax:
1. FROM table_name...
2. Expressions...
Customer table:
1. CREATE TABLE "CUSTOMERS"
2. ( "NAME" VARCHAR2(4000),
3. "AGE" NUMBER,
4. "SALARY" NUMBER,
5. "STATE" VARCHAR2(4000)
6. )
7. /
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:
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:
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.
DESC: It is also an optional parameter that is used to sort records in descending order.
Supplier table:
1. CREATE TABLE "SUPPLIER"
2. ( "SUPPLIER_ID" NUMBER,
3. "FIRST_NAME" VARCHAR2(4000),
4. "LAST_NAME" VARCHAR2(4000)
5. )
6. /
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.
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.
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.
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.
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.
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. /
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. /
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.
1. SELECT department,
2. MAX(salary) AS "Highest salary"
3. FROM employees
4. GROUP BY department;
Output:
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.
Salesdepartment table:
1. CREATE TABLE "SALESDEPARTMENT"
2. ( "ITEM" VARCHAR2(4000),
3. "SALE" NUMBER,
4. "BILLING_ADDRESS" VARCHAR2(4000)
5. )
6. /
1.
2. SELECT item, SUM(sale) AS "Total sales"
3. FROM salesdepartment
4. GROUP BY item
5. HAVING SUM(sale) < 1000;
Output:
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:
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. /
1. SELECT department,
2. MIN(salary) AS "Lowest salary"
3. FROM employees
4. GROUP BY department
5. HAVING MIN(salary) < 15000;
Output
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.
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.
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
Each SELECT statement within the UNION ALL 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 ALL
5. SELECT expression1, expression2, ... expression_n
6. FROM table2
7. WHERE conditions;
Parameters
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.
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
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.
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
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.
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.
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 Equijoins
o Self Joins
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;
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.
Output
Syntax
1. SELECT columns
2. FROM table1
3. LEFT [OUTER] JOIN table2
4. ON table1.column = table2.column;
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.
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;
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.
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
Syntax
1. SELECT columns
2. FROM table1
3. FULL [OUTER] JOIN table2
4. ON table1.column = table2.column;
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.
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
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)]
Agents table
Agent data
Customer table
Customer data
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
1. SELECT a.column_name, b.column_name...
2. FROM table1 a, table1 b
3. WHERE a.common_filed = b.common_field;
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.
1. CREATE TABLE "SUPPLIER"
2. ( "SUPPLIER_ID" NUMBER,
3. "FIRST_NAME" VARCHAR2(4000),
4. "LAST_NAME" VARCHAR2(4000)
5. )
6. /
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.
Example
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. /
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
A semi-join returns one copy of each row in first table for which at least one match is found.
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. /
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
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.
Table creation:
1. create table user(id number(10) primary key,name varchar2(100));
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.
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
1. DROP PROCEDURE procedure_name;
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.
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
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. /
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
Customers
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.
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.
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.
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.
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.
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
1. OPEN cursor_name;
Example
1. OPEN c1;
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
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:
1. CURSOR c1
2. IS
3. SELECT course_id
4. FROM courses
5. WHERE course_name = name_in;
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;
Syntax
1. CLOSE cursor_name;
1. CLOSE c1;
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;
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.
Trigger Topics
1) Oracle BEFORE INSERT/UPDATE/DELETE Trigger
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.
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".
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.
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.
It will drop the trigger name "SUPPLIERS_T1" from the table "SUPPLIERS".
Syntax
1. ALTER TRIGGER trigger_name DISABLE;
Parameters
trigger_name: It specifies the name of the trigger that you want to disable.
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".
Syntax
1. ALTER TRIGGER trigger_name ENABLE;
Parameters
trigger_name: It specifies the name of the trigger that you want to 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".
o Tablespaces
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.
The main advantage of BCP is fast mechanism for coping data and you can also take the
backup of data easily.
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
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.
o Form module
o Menu module
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.
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.
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.
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;
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;
1. to_date ('2012-12-12', 'YYYY/MM/DD')
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;
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.
A table contains specified number of column called fields but can have any number of rows
which is known as record.
2. Logical operators
3. Comparison operator
o Unique Index
o Clustered Index
o NonClustered 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.
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.
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.
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.
o Inner Join
o Right Join
o Left Join
o Full Join
Inner join returns rows when there is at least one match of rows between the tables.
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.
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.
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.
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.
o LOWER
o UPPER
o INITCAP
1. COALESCE(exp1, exp2, ... expn)
The COALESCE function is used to return the first non-null expression given in the
parameter list.
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.
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.
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;
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.
o BEFORE INSERT
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.
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
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.
1. EXECUTE or [EXEC] procedure_name;
1. procedure_name;
%FOUND: it checks whether cursor has fetched any row. If yes - TRUE.
o Other users can see the data changes made by the transaction.
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.
2. explicit cursor
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.
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.)
(Optional) Enter the following SQL query to verify that the database started up properly:
COUNT(*)
----------
107
EXIT
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.
EXIT
D:\app\Admin\product\11.1.0\db_1\sqldeveloper\sqldeveloper\bin\sqldeveloper.exe