0% found this document useful (0 votes)
23 views

Oracle

The document contains an answer sheet for an Oracle exam. It includes answers to multiple choice and written questions related to Oracle concepts like SQL queries, table creation, joins, views, and data types. For question 1, the respondent provides SQL code to create tables with constraints, write queries to display employee details based on various criteria, and calculate totals. For question 2, short notes are written about views and the CLOB data type. For question 3, the types of SQL joins are explained with examples.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Oracle

The document contains an answer sheet for an Oracle exam. It includes answers to multiple choice and written questions related to Oracle concepts like SQL queries, table creation, joins, views, and data types. For question 1, the respondent provides SQL code to create tables with constraints, write queries to display employee details based on various criteria, and calculate totals. For question 2, short notes are written about views and the CLOB data type. For question 3, the types of SQL joins are explained with examples.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

ANSWER SHEET

SUBJECT: ORACLE

Q1. Solve
1. Consider the following table to solve any five the following SQL
queries:
Employee (Empno, Ename, Salary, Joining_date, Birth_date, Job_id) Job
(Job_id, Job_desc, Job Title, Max_salary, Min_salary)

a) Create tables with appropriate constraints


Ans:
-- Create the Employee table

CREATE TABLE Employee (


Empno INT PRIMARY KEY,
Ename VARCHAR(50),
Salary DECIMAL(10, 2),
Joining_date DATE,
Birth_date DATE,
Job_id INT,
FOREIGN KEY (Job_id) REFERENCES Job(Job_id)
);

-- Create the Job table

CREATE TABLE Job (


Job_id INT PRIMARY KEY,
Job_desc VARCHAR(50),
Job_title VARCHAR(50),
Max_salary DECIMAL(10, 2),
Min_salary DECIMAL(10, 2)
);

b) Display employee name along with his job title


Ans:

SELECT Employee.Ename, Job.Job_title


FROM Employee
JOIN Job ON Employee.Job_id = Job.Job_id;
c) Display list of employees whose employee name starts with ‘P’
character
Ans:

SELECT *
FROM Employee
WHERE Ename LIKE 'P%';

d) Display details of employees earning salary greater than the minimum


salary for their job.
Ans:

SELECT Employee.*
FROM Employee
JOIN Job ON Employee.Job_id = Job.Job_id
WHERE Employee.Salary > Job.Min_salary;

e) Display list of employees who have joined after ‘1st January, 2010’
Ans:

SELECT *
FROM Employee
WHERE Joining_date > '2010-01-01';

f) Display total salary for each job.


Ans:

SELECT Job.Job_title, SUM(Employee.Salary) AS Total_Salary


FROM Employee
JOIN Job ON Employee.Job_id = Job.Job_id
GROUP BY Job.Job_title;

g) Display employee name and age for employees


Ans:

SELECT Ename, TIMESTAMPDIFF(YEAR, Birth_date, CURDATE()) AS Age


FROM Employee;

h) Display details of employees who are working as ‘MANAGER’


Ans:

SELECT *
FROM Employee
JOIN Job ON Employee.Job_id = Job.Job_id
WHERE Job_title = 'MANAGER';

Q2. Write short notes on (any two):

1. VIEWS

Ans: In Oracle, views are virtual tables that provide a customized and logical
representation of data stored in one or more underlying tables. They are
created by combining data from different tables or selecting specific columns
and rows from existing tables. Views are a powerful tool in database
management as they allow users to retrieve data without directly accessing or
modifying the underlying tables.

Here are a few key points about views in Oracle:

1. Structure: Views have a defined structure, including column names, data


types, and constraints. They can include columns from one or more tables and
can also perform calculations or transformations on the data.

2. Security: Views can be used to control access to data by restricting the


columns or rows visible to different users or user groups. This enables fine-
grained security mechanisms and ensures that sensitive information remains
protected.

3. Simplified Queries: Views simplify complex queries by predefining the join


operations, filtering criteria, or calculations needed to retrieve specific data.
Users can query a view as if it were a regular table, abstracting away the
underlying complexity.

4. Data Modification: Depending on the configuration, views can allow data


modification operations such as inserting, updating, or deleting records. These
modifications are automatically applied to the underlying tables, ensuring data
consistency.

5. Performance: Views can improve query performance by aggregating data or


precomputing complex calculations, storing the results in the view. This
reduces the computational overhead during query execution.

6. Dependency Management: Oracle tracks dependencies between views and


the underlying tables. If a table used in a view is modified, the view is
automatically invalidated, ensuring data integrity and accuracy.

7. Materialized Views: Oracle also supports materialized views, which are


physical copies of the view data stored in the database. Materialized views are
useful when the underlying tables contain large amounts of data, and
precomputed results need to be stored for faster access.

Views provide a layer of abstraction in database systems, enhancing data


security, simplifying queries, and improving performance. They are widely used
in Oracle databases to simplify complex data models, enhance data access
control, and optimize query execution.

2. CLOB Data Type:


Ans: CLOB (Character Large Object) is a data type in Oracle (and other
database systems) that is used to store large amounts of character data. It is
designed to handle textual data exceeding the limit of a regular VARCHAR2 or
NVARCHAR2 data type.

Here are some key points about CLOB data type in Oracle:

1. Capacity: CLOB can store up to 4 terabytes of character data, making it


suitable for storing very large text documents, XML data, or other textual
content.

2. Character Encoding: CLOB data type supports both single-byte and


multibyte character sets. It can handle various character encodings such as
ASCII, UTF-8, UTF-16, etc.

3. Storage: CLOB data is stored in a separate segment from the rest of the
table data. It can be stored inline (in the same data block as the table) or in an
out-of-line manner (in a separate segment).

4. Manipulation: CLOB data can be manipulated and queried using SQL


statements and functions. You can perform operations like insertion, retrieval,
update, and deletion of CLOB data.

5. Indexing: Oracle allows you to create indexes on CLOB columns to improve


the performance of search operations. However, the index is limited to a prefix
of the CLOB column due to its potentially large size.

6. LOB Functions: Oracle provides a set of built-in functions to work with


CLOB data, such as SUBSTR, LENGTH, INSTR, and CONCATENATE. These
functions allow you to extract, manipulate, and combine CLOB data as needed.

7. Performance Considerations: Retrieving or manipulating large CLOB data


can have an impact on database performance, especially when dealing with
extensive text content. It's important to consider efficient data access
strategies, indexing, and appropriate query optimization techniques.
CLOB data type is widely used in Oracle databases for storing and processing
large textual data, such as long documents, web pages, XML files, or any other
text-based information that exceeds the capacity of regular string types. It
provides a flexible and scalable solution for managing and working with
substantial amounts of character data efficiently.
3. Group by- having clause
Ans: The GROUP BY and HAVING clauses in SQL are used together to filter
and aggregate data in a grouped result set. Here's a short note on how these
clauses work:

1. GROUP BY Clause:
- The GROUP BY clause is used to group rows from a table based on one or
more columns.
- It divides the result set into groups, where each group has the same values
for the specified column(s).
- It is often used with aggregate functions like COUNT, SUM, AVG, etc., to
perform calculations on each group of data.
- The columns specified in the GROUP BY clause determine the grouping
criteria.

2. HAVING Clause:
- The HAVING clause is used in combination with the GROUP BY clause to
filter the result set based on conditions applied to the grouped data.
- It allows you to specify conditions that must be satisfied by the groups
selected by the GROUP BY clause.
- The HAVING clause operates similarly to the WHERE clause, but it works on
groups rather than individual rows.
- It can use aggregate functions and column aliases defined in the SELECT
statement.
- The conditions in the HAVING clause are applied after the grouping and
aggregation have taken place.

Example:

SELECT department, COUNT(*) AS total_employees


FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
```
- In this example, the GROUP BY clause groups the rows by the "department"
column.
- The COUNT(*) function calculates the number of employees in each
department.
- The HAVING clause filters out the groups where the count of employees is
greater than 5, and only those groups are included in the result set.

The GROUP BY and HAVING clauses are powerful tools for aggregating and
filtering data in SQL. They allow you to perform calculations and apply
conditions to grouped data, providing flexibility and control over the result set
based on specific criteria.

Q3. Solve

1. Explain different types of Join operations with example


Ans:
In Oracle, there are several types of join operations that allow you to combine
data from multiple tables based on specified conditions. Let's explore the
different types of join operations along with examples:

1. INNER JOIN:
An inner join returns only the rows that have matching values in both tables
being joined. It combines rows from two tables based on the specified join
condition.

Syntax:

SELECT *
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
```

Example:

SELECT *
FROM employees
INNER JOIN departments
ON employees.department_id = departments.department_id;
```

This query combines the "employees" and "departments" tables based on the
matching "department_id" column. It returns rows where there is a match
between the two tables.

2. LEFT JOIN (or LEFT OUTER JOIN):


A left join returns all the rows from the left table and the matching rows from
the right table. If there is no match, NULL values are returned for the columns
of the right table.

Syntax:

SELECT *
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
```

Example:

SELECT *
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.department_id;
```

This query performs a left join between the "employees" and "departments"
tables. All rows from the "employees" table are returned, and the corresponding
matching rows from the "departments" table are included. If there is no match,
NULL values are returned for the "departments" columns.

3. RIGHT JOIN (or RIGHT OUTER JOIN):


A right join returns all the rows from the right table and the matching rows
from the left table. If there is no match, NULL values are returned for the
columns of the left table.

Syntax:

SELECT *
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
```

Example:

SELECT *
FROM employees
RIGHT JOIN departments
ON employees.department_id = departments.department_id;
```

This query performs a right join between the "employees" and "departments"
tables. All rows from the "departments" table are returned, and the
corresponding matching rows from the "employees" table are included. If there
is no match, NULL values are returned for the "employees" columns.

4. FULL JOIN (or FULL OUTER JOIN):


A full join returns all the rows from both tables and combines them based on
the specified join condition. If there is no match, NULL values are returned for
the columns of the non-matching table.

Syntax:

SELECT *
FROM table1
FULL JOIN table2
ON table1.column = table2.column;
```

Example:

SELECT *
FROM employees
FULL JOIN departments
ON employees.department_id = departments.department_id;
```

This query performs a full join between the "employees" and "departments"
tables. It returns all rows from both tables and combines them based on the
matching "department_id" column. If there is no match, NULL values are
returned for the non-matching columns.

These are the commonly used join operations in Oracle. Each type of join
allows you to combine data from multiple tables based on different conditions,
providing flexibility in retrieving and analyzing data from related tables.

2. What is mean by Constraints? Explain different types of constraints


available in Oracle
Ans:
Constraints in Oracle are rules or conditions that are applied to columns or
tables to ensure data integrity and enforce business rules. They define limits or
restrictions on the data that can be stored in the database. Constraints help
maintain data accuracy, consistency, and validity by preventing invalid or
inconsistent data from being inserted or updated.

Oracle supports various types of constraints. Let's explore the different types:

1. NOT NULL Constraint:


The NOT NULL constraint ensures that a column must always have a non-null
value. It prevents inserting or updating null values in the specified column.

Syntax:

CREATE TABLE table_name (


column_name data_type NOT NULL
);
```

2. UNIQUE Constraint:
The UNIQUE constraint ensures that each value in a column or a set of
columns is unique across the table. It prevents duplicate values from being
inserted or updated.

Syntax:

CREATE TABLE table_name (


column_name data_type UNIQUE
);
```

3. PRIMARY KEY Constraint:


The PRIMARY KEY constraint uniquely identifies each row in a table. It is a
combination of the NOT NULL and UNIQUE constraints. Only one primary key
can be defined for a table.

Syntax:

CREATE TABLE table_name (


column_name data_type PRIMARY KEY
);
```

4. FOREIGN KEY Constraint:


The FOREIGN KEY constraint establishes a relationship between two tables
based on a column in each table. It ensures referential integrity by enforcing
that values in the foreign key column must exist in the referenced primary key
column of the related table.

Syntax:

CREATE TABLE table1 (


column1 data_type,
FOREIGN KEY (column1) REFERENCES table2(column2)
);
```

5. CHECK Constraint:
The CHECK constraint validates the data entered into a column based on a
specified condition or expression. It allows you to define custom rules for data
integrity.

Syntax:

CREATE TABLE table_name (


column_name data_type CHECK (condition)
);
```

6. UNIQUE INDEX Constraint:


The UNIQUE INDEX constraint creates a unique index on one or more columns
of a table. It provides a fast lookup for enforcing the uniqueness of values and
improves query performance.

Syntax:

CREATE TABLE table_name (


column_name data_type,
CONSTRAINT constraint_name UNIQUE (column_name)
);
```

These are the commonly used constraints in Oracle. By applying constraints,


you can maintain data integrity, enforce business rules, and ensure the
reliability of the database. Constraints play a vital role in maintaining the
consistency and accuracy of the data stored in Oracle tables.

Q4. Solve
1. What is mean by Cursor? Explain different types of Cursor available in
Oracle
Ans: In Oracle, a cursor is a database object used to retrieve and manipulate
data in a result set. It provides a way to iterate over the rows returned by a
SQL query and perform operations on them. A cursor acts as a pointer to the
result set, allowing you to fetch and process data row by row.

There are two types of cursors in Oracle:

1. Implicit Cursor:
- An implicit cursor is automatically created by Oracle whenever a SQL
statement is executed.
- It is used for executing single-row queries or DML (Data Manipulation
Language) statements such as INSERT, UPDATE, DELETE.
- Implicit cursors are managed by Oracle internally and do not need to be
explicitly declared or controlled by the user.

Example:

BEGIN
SELECT column1 INTO variable
FROM table1
WHERE condition;

-- Perform operations using the fetched value


END;
```

In this example, the implicit cursor is used to execute the SELECT statement
and fetch the value of "column1" into the "variable" for further processing.

2. Explicit Cursor:
- An explicit cursor is explicitly declared and managed by the user.
- It provides more control and flexibility over result set retrieval and
processing.
- Explicit cursors are used when you need to work with multiple rows or when
you need to explicitly open, fetch, and close the cursor.

Syntax:

DECLARE
cursor_name cursor_type;
BEGIN
-- Cursor declaration
OPEN cursor_name;

-- Cursor processing
FETCH cursor_name INTO variables;
-- Perform operations using the fetched values

CLOSE cursor_name;
END;
```

Example:

DECLARE
CURSOR cursor_name IS
SELECT column1, column2
FROM table1
WHERE condition;

variable1 table1.column1%TYPE;
variable2 table1.column2%TYPE;
BEGIN
OPEN cursor_name;

LOOP
FETCH cursor_name INTO variable1, variable2;
EXIT WHEN cursor_name%NOTFOUND;

-- Perform operations using the fetched values


END LOOP;

CLOSE cursor_name;
END;
```

In this example, an explicit cursor named "cursor_name" is declared to retrieve


rows from "table1" based on the specified condition. The cursor is then opened,
and a loop is used to fetch and process each row of the result set until there
are no more rows.

Explicit cursors provide more control and flexibility in handling result sets,
allowing you to perform various operations on retrieved data. They are
especially useful when dealing with multiple rows or when you need to control
the cursor behavior explicitly.
2. Explain different SQL functions available in oracle
Ans: Oracle provides a wide range of built-in SQL functions that can be used to
perform various operations on data. Here are some commonly used SQL
functions available in Oracle:

1. Aggregate Functions:
- COUNT(): Returns the number of rows or non-null values in a column.
- SUM(): Calculates the sum of values in a column.
- AVG(): Computes the average of values in a column.
- MIN(): Retrieves the minimum value from a column.
- MAX(): Retrieves the maximum value from a column.

2. String Functions:
- CONCAT(): Concatenates two or more strings together.
- SUBSTR(): Extracts a substring from a string.
- INSTR(): Finds the position of a substring within a string.
- REPLACE(): Replaces occurrences of a substring in a string.
- UPPER(): Converts a string to uppercase.
- LOWER(): Converts a string to lowercase.
- TRIM(): Removes leading or trailing spaces from a string.

3. Date Functions:
- SYSDATE: Returns the current system date and time.
- TO_CHAR(): Converts a date or timestamp to a specific format.
- TO_DATE(): Converts a string to a date using a specified format.
- EXTRACT(): Extracts a specific part (year, month, day, etc.) from a date.

4. Numeric Functions:
- ROUND(): Rounds a number to a specified decimal place or precision.
- TRUNC(): Truncates a number to a specified decimal place or precision.
- ABS(): Returns the absolute value of a number.
- MOD(): Computes the remainder of a division operation.

5. Conversion Functions:
- TO_NUMBER(): Converts a string to a number.
- TO_CHAR(): Converts a number or date to a string.
- TO_DATE(): Converts a string to a date.

6. Conditional Functions:
- CASE: Performs conditional operations based on specified conditions.

7. Analytic Functions:
- RANK(): Assigns a rank to each row based on the specified criteria.
- ROW_NUMBER(): Assigns a unique sequential number to each row.
- LAG() and LEAD(): Accesses data from previous or subsequent rows in a
result set.

These are just a few examples of the SQL functions available in Oracle. Oracle
provides a rich set of functions to manipulate, transform, and analyze data in
various ways. By leveraging these functions, you can perform complex
calculations, manipulate strings, convert data types, and more within your
SQL queries.

Q5. Solve

1. Write a Cursor to display first five top salaried records of Employee


table
Ans: To display the first five top salaried records from the Employee table using
a cursor, you can follow the below steps:

1. Declare a cursor that selects the required columns from the Employee table,
ordered by salary in descending order.
2. Use the FETCH statement to fetch the first five rows from the cursor.
3. Create variables to store the column values fetched from each row.
4. Loop through the cursor result set and display the values.
5. Close the cursor when finished.

Here's an example of how to implement this in PL/SQL:

DECLARE
CURSOR top_salary_cursor IS
SELECT employee_id, first_name, last_name, salary
FROM employee
ORDER BY salary DESC;

-- Variables to store fetched values


v_employee_id employee.employee_id%TYPE;
v_first_name employee.first_name%TYPE;
v_last_name employee.last_name%TYPE;
v_salary employee.salary%TYPE;

-- Counter variable
v_counter INTEGER := 0;
BEGIN
OPEN top_salary_cursor;

LOOP
FETCH top_salary_cursor INTO v_employee_id, v_first_name, v_last_name,
v_salary;
EXIT WHEN top_salary_cursor%NOTFOUND OR v_counter = 5;

-- Display the fetched values


DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_employee_id);
DBMS_OUTPUT.PUT_LINE('Name: ' || v_first_name || ' ' || v_last_name);
DBMS_OUTPUT.PUT_LINE('Salary: ' || v_salary);
DBMS_OUTPUT.PUT_LINE('-------------------');

v_counter := v_counter + 1;
END LOOP;

CLOSE top_salary_cursor;
END;
/
```

This code declares a cursor named `top_salary_cursor`, which selects the


employee_id, first_name, last_name, and salary columns from the Employee
table ordered by salary in descending order. The loop fetches the values into
the declared variables and displays them using `DBMS_OUTPUT.PUT_LINE()`.
The loop will exit either when it fetches the first five rows or when there are no
more rows to fetch.

2. Write a Function Fact() to test whether the input number is ODD or EVEN
Ans: To write a function in Oracle that tests whether an input number is odd
or even, you can use the modulus operator (%). The modulus operator
calculates the remainder when one number is divided by another. If the
remainder is 0, the number is even; otherwise, it is odd. Here's an example:

CREATE OR REPLACE FUNCTION is_odd_or_even(input_number NUMBER)


RETURN VARCHAR2 IS
BEGIN
IF MOD(input_number, 2) = 0 THEN
RETURN 'Even';
ELSE
RETURN 'Odd';
END IF;
END;
/
```
In this example, a function named `is_odd_or_even` is created. It takes an
input number as a parameter and returns a VARCHAR2 result. Inside the
function, the MOD function is used to calculate the remainder when the input
number is divided by 2. If the remainder is 0, the function returns 'Even';
otherwise, it returns 'Odd'.

You can then call this function in a SQL query or PL/SQL code to test whether
a number is odd or even. Here's an example:

DECLARE
input_num NUMBER := 10;
result VARCHAR2(10);
BEGIN
result := is_odd_or_even(input_num);
DBMS_OUTPUT.PUT_LINE('The number ' || input_num || ' is ' || result);
END;
/
```

In this code snippet, the `input_num` variable is set to 10, and the
`is_odd_or_even` function is called to determine if it is odd or even. The result
is stored in the `result` variable and displayed using
`DBMS_OUTPUT.PUT_LINE()`.

You can modify the value of `input_num` variable to test different numbers and
check their odd or even status using the function.

You might also like