0% found this document useful (0 votes)
3 views141 pages

PL SQL

The document outlines a comprehensive curriculum for PL/SQL, covering SQL basics, DDL, DML, built-in functions, views, PL/SQL programming, exception handling, cursors, procedures, functions, triggers, and database objects in Oracle. It also explains Codd's 12 rules for relational databases and various SQL sub-languages, including DDL, DML, DQL, and DCL. Each section provides essential definitions, descriptions, and examples relevant to database management and operations.

Uploaded by

Arpit Bangre
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views141 pages

PL SQL

The document outlines a comprehensive curriculum for PL/SQL, covering SQL basics, DDL, DML, built-in functions, views, PL/SQL programming, exception handling, cursors, procedures, functions, triggers, and database objects in Oracle. It also explains Codd's 12 rules for relational databases and various SQL sub-languages, including DDL, DML, DQL, and DCL. Each section provides essential definitions, descriptions, and examples relevant to database management and operations.

Uploaded by

Arpit Bangre
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 141

Page 1 of 141

PL/SQL

UNIT - I:
SQL Basics: Codd's Rules, Oracle Database Objects, SQL Sub-languages, Data types,
Operators.

DDL Statements: Create, Alter, Drop Tables, Integrity Constraints (Naming, Viewing,
Adding/Dropping).

DML Statements: SELECT, Insert, Update, Delete, Sequences, Synonyms.

Built-in Functions: Arithmetic, Date, Character, Conversion, Single-row, Aggregate, Decode.

Joins, Set Operators, Subqueries.

DCL/TCL Statements: Grant, Revoke, Commit, Rollback, Savepoints.

UNIT - II:
Views: Create, Drop, Insert, Update, Delete, Types of Views.

PL/SQL: Data Types, Identifiers, Operators, Iterative/Conditional Statements, Problem-


solving.

UNIT - III:
Exception Handling: Predefined and User-defined Exceptions.

Cursors: Declaring, Opening, Retrieving, Closing, Attributes, Parameter Passing.

Procedures: Create, Drop, Parameters, Calling, Granting EXECUTE Permission, Problem-


solving.

UNIT - IV:
Functions: Creating/Dropping, Purity Levels, Executing Functions.

Triggers: Create, Types (BEFORE, AFTER, INSTEAD-OF), Trigger Predicates,


Inserting/Updating/Deleting, Enabling/Disabling, Dropping, Problem-solving.
Page 2 of 141

Here's a bold representation of the number "1" using special characters:

markdown

1111111
1 1
1 1
1111111
1
1
1

This uses special characters to make it look very bold! Let me know if you need any changes
or more designs!

CODD'S Rules, Oracle Database Objects, Sub-languages of SQL, Data Types, Operators

Question:
Explain Codd's Rules in detail.
Asked in: S 16, W 16, S 17, W 17, S 18, W 19

Explanation:
Codd's 12 rules, formulated by Edgar F. Codd, are a set of rules that define what is required for
a database management system (DBMS) to be considered truly relational. These rules are the
foundation of relational databases, ensuring data integrity, consistency, and flexibility in
storing and managing information. Let's go over each rule in detail:

1. The Information Rule:

Description: All information in a relational database is represented explicitly in tables. Each


piece of data is stored as a value in a field, and each field is part of a record (or row) in a
table.

Explanation: In relational databases, data must be stored in tables, where the tables
consist of rows and columns. Each piece of data should be represented as a value in a
column. For example, customer names and addresses are stored in rows under appropriate
columns in a table.

2. The Rule of Guaranteed Access:

Description: All data in a relational database should be accessible by using a combination


of the table name, primary key, and column name.

Explanation: The database must allow users to retrieve data easily by referencing the table,
column, and specific data using the primary key. It guarantees that each piece of data can
be uniquely identified and accessed by its location in the table (row and column).

3. Systematic Treatment of Null Values:


Page 3 of 141

Description: The database must support a representation for missing or inapplicable


information, which is referred to as "null".

Explanation: A "null" value indicates missing or unknown data. The system should allow
the differentiation between "null" (no value) and other values like 0 or empty string. Null
values should be treated systematically in all operations, such as comparisons and queries.

4. Dynamic Online Catalog Based on the Relational Model:

Description: The database system must store the structure (catalog) of the database itself in
relational tables, allowing access through the same relational methods as user data.

Explanation: The database schema, which defines tables, columns, and relationships,
should be stored within the database itself. This structure can be queried in the same way
as any other data in the database, making the system flexible and easier to manage.

5. The Comprehensive Data Sublanguage Rule:

Description: A relational database must support at least one language that can be used
interactively to define and manipulate data (such as SQL).

Explanation: The database must provide a language (e.g., SQL) that allows users to define,
manipulate, and query data. This language should be comprehensive, meaning that it can
handle all operations including data insertion, updates, deletions, and complex queries.

6. The View Updating Rule:

Description: All views (virtual tables created by querying the database) should be
updatable.

Explanation: In a relational database, views are often used to simplify complex queries or
provide a user-friendly view of the data. According to Codd's rule, the database should
allow the modification of data through views (inserts, updates, deletes) unless the view
violates certain restrictions like aggregation.

7. The High-Level Insert, Update, and Delete Rule:

Description: A relational DBMS must support operations like inserting, updating, and
deleting data at a high level.

Explanation: The database should allow the user to insert, update, and delete data at a
high level, using queries that don't require low-level data manipulation. This ensures ease
of use and consistency in the database operations.

8. The Physical Data Independence Rule:

Description: The DBMS should allow users to change the physical storage of data without
affecting how the data is accessed.

Explanation: The way data is stored on disk (physical storage) should be independent of
how it is logically represented and queried. This allows the database to be optimized for
performance without requiring changes to the applications that use it.

9. The Logical Data Independence Rule:

Description: Changes to the logical schema (structure of data) should not require changes
to the applications that use the data.
Page 4 of 141

Explanation: The logical schema refers to the way the data is organized and structured in
tables. Codd emphasized that changes to this structure, such as adding or removing tables
or columns, should not affect the applications that access the data. This provides flexibility
and future-proofing.

10. The Integrity Independence Rule:

Description: Integrity constraints (such as uniqueness, foreign key relationships, etc.) must
be defined separately from application programs.

Explanation: The rules for maintaining data integrity, such as ensuring unique values in a
column or maintaining relationships between tables, should be defined within the
database and not within application code. This ensures that the integrity of the data is
maintained consistently across applications.

11. The Distribution Independence Rule:

Description: The DBMS must allow data to be distributed across multiple locations without
affecting how the data is accessed.

Explanation: The data may be stored in different physical locations, but this should be
transparent to the users and applications. The DBMS should handle the distribution of
data and allow access as if the data were stored in a single location.

12. The Non-Subversion Rule:

Description: If a relational DBMS provides low-level access (e.g., for performance


optimization), it should not bypass the integrity rules of the system.

Explanation: In cases where low-level access is provided (such as for tuning performance),
it must not undermine or bypass the relational integrity rules of the system, ensuring that
the database's relational principles are still enforced.

Conclusion:
Codd's 12 rules define the essential properties a database must have to be considered
relational, ensuring data integrity, flexibility, and ease of use. These rules have been
fundamental in shaping the development of relational database management systems
(RDBMS) and are still widely referenced today.

Question:
Explain the different types of database objects in Oracle.
Asked in: S 18, W 17, S 17

Explanation:
In Oracle, a database object is any defined object that stores and organizes data. These
objects are the fundamental building blocks used to store and manage data within the
database. Oracle provides various types of database objects, each serving a different function.
Below is a detailed explanation of the most common database objects in Oracle:

1. Tables:
Page 5 of 141

Description: A table is the most fundamental object in a database. It stores data in rows
and columns, where each row represents a record and each column represents an
attribute of that record.

Explanation: Tables are the primary structure used for storing data. Each table has a name,
and the data is stored in a tabular format with rows and columns. For example, a
"Customers" table might store information like customer ID, name, and address, with each
row representing a different customer.

2. Views:

Description: A view is a virtual table based on the result of a SELECT query. It does not
store data itself, but instead presents data from one or more tables.

Explanation: Views simplify complex queries, providing a way to retrieve and present data
without needing to repeatedly write complicated queries. Views can also be used to restrict
access to certain columns or rows of data. For instance, a view can be created to display
only the names and email addresses of customers from a "Customers" table, hiding other
sensitive information.

3. Indexes:

Description: An index is an object that improves the speed of data retrieval operations on a
table at the cost of additional space and decreased performance on data modification
operations.

Explanation: Indexes are created on one or more columns of a table and allow for faster
searching of data. For example, creating an index on the "customer_id" column of a
"Customers" table can speed up queries that search for a customer by their ID.

4. Synonyms:

Description: A synonym is an alias or shortcut for another database object such as a table,
view, or procedure.

Explanation: Synonyms provide a way to simplify access to database objects by allowing


users to reference an object with a shorter name. For example, a synonym can be created
for a frequently used table, so users don't need to type the full table name each time they
access it.

5. Sequences:

Description: A sequence is an object that generates a series of unique numbers, typically


used for auto-incrementing primary keys.

Explanation: Sequences are used to generate unique identifiers for rows in a table, often
used in situations where a unique ID is required for each row. For example, an
"employee_id" sequence can be used to automatically generate a unique employee ID
when a new employee is added to the "Employees" table.

6. Triggers:

Description: A trigger is a stored procedure that is automatically executed or fired when a


certain event occurs on a table or view.
Page 6 of 141

Explanation: Triggers are often used for enforcing business rules, such as validating data
before it is inserted into a table or automatically updating data in other tables. For
example, a trigger could be used to automatically update a "last_modified" timestamp
column whenever a record in the "Employees" table is updated.

7. Stored Procedures:

Description: A stored procedure is a set of SQL statements stored in the database that can
be executed as a unit.

Explanation: Stored procedures allow for reusable, modular code within the database.
They can be used for tasks such as inserting or updating data, performing calculations, or
handling business logic. For example, a stored procedure can be created to update
employee salary details based on certain conditions.

8. Functions:

Description: A function is similar to a stored procedure, but it returns a single value as


output and is often used in queries.

Explanation: Functions are used to perform calculations or operations that return a value.
They can be used in SQL queries, just like built-in functions such as UPPER() or AVG() . For
example, a function could be created to calculate the total salary of all employees in a
department.

9. Packages:

Description: A package is a collection of related procedures, functions, variables, and other


program elements grouped together.

Explanation: Packages provide a way to organize related PL/SQL code into a single unit. A
package has two parts: the specification (which declares procedures, functions, and
variables) and the body (which contains the actual implementation of those procedures
and functions). For example, a package might contain functions for calculating employee
bonuses and procedures for managing employee records.

10. Constraints:

Description: Constraints are rules applied to columns in tables to enforce data integrity and
consistency.

Explanation: Constraints ensure that the data entered into a table adheres to certain rules.
Some common types of constraints include:

PRIMARY KEY: Ensures that each record in the table is unique.

FOREIGN KEY: Ensures that a value in one table matches a value in another table,
maintaining referential integrity.

CHECK: Ensures that data meets a specified condition.

UNIQUE: Ensures that values in a column are unique.

11. User Defined Types (UDTs):

Description: A user-defined type is a custom data type created by the user.


Page 7 of 141

Explanation: UDTs allow users to define their own complex data types based on standard
data types. For example, a user can define a DATE_RANGE type to represent a range of
dates, consisting of two DATE values (start date and end date).

12. Database Links:

Description: A database link is an object that allows a database to communicate with


another database.

Explanation: Database links are used to query or manipulate data in a remote database.
For example, a database link can be created to access tables in a different Oracle database
from the current session.

These database objects work together to store, organize, and manage data within an Oracle
database system. Each object serves a specific role and helps in maintaining the efficiency,
integrity, and security of the database.

Question:
What are the sub-languages of SQL?
Asked in: S 16

Explanation:
SQL (Structured Query Language) is a standard language used to manage and manipulate
relational databases. It is divided into different sub-languages, each responsible for a specific
type of database operation. These sub-languages provide a structured way to interact with
the database, allowing users to perform a variety of tasks such as querying, modifying, and
managing data. Below are the main sub-languages of SQL:

1. Data Definition Language (DDL):

Purpose: DDL is used for defining and modifying the structure of the database. It deals with
the creation, alteration, and deletion of database objects such as tables, views, indexes,
and schemas.

Commands:

CREATE: Used to create database objects like tables, views, indexes, etc.

Example: CREATE TABLE employees (id INT, name VARCHAR(50));

ALTER: Used to modify existing database objects, such as adding or dropping columns in
a table.

Example: ALTER TABLE employees ADD COLUMN salary INT;

DROP: Used to delete database objects such as tables or views.

Example: DROP TABLE employees;

TRUNCATE: Used to remove all data from a table, but the table structure remains intact.
Page 8 of 141

Example: TRUNCATE TABLE employees;

2. Data Manipulation Language (DML):

Purpose: DML is used for manipulating data within the database. It allows users to query,
insert, update, and delete data in the database.

Commands:

SELECT: Used to retrieve data from one or more tables.

Example: SELECT * FROM employees;

INSERT: Used to insert new data into a table.

Example: INSERT INTO employees (id, name) VALUES (1, 'John Doe');

UPDATE: Used to modify existing data in a table.

Example: UPDATE employees SET salary = 5000 WHERE id = 1;

DELETE: Used to delete data from a table.

Example: DELETE FROM employees WHERE id = 1;

3. Data Query Language (DQL):

Purpose: DQL is used for querying or retrieving data from the database. The primary
command in DQL is the SELECT statement.

Command:

SELECT: This is the only command in DQL and is used to fetch data from the database. It
can be used with various clauses (e.g., WHERE, ORDER BY, GROUP BY) to filter, sort, and
aggregate the data.

Example: SELECT name, salary FROM employees WHERE salary > 4000 ORDER BY salary
DESC;

4. Data Control Language (DCL):

Purpose: DCL is used to control access to the data in the database by granting or revoking
privileges to users.

Commands:

GRANT: Used to give specific privileges to a user or role, such as the ability to query or
modify data.

Example: GRANT SELECT ON employees TO user1;

REVOKE: Used to remove previously granted privileges from a user or role.

Example: REVOKE SELECT ON employees FROM user1;

5. Transaction Control Language (TCL):

Purpose: TCL is used to manage the changes made by DML commands and ensure the
consistency and integrity of the database.

Commands:

COMMIT: Used to save changes made by DML operations to the database permanently.
Page 9 of 141

Example: COMMIT;

ROLLBACK: Used to undo changes made by DML operations since the last COMMIT or
ROLLBACK.

Example: ROLLBACK;

SAVEPOINT: Used to set a point within a transaction to which a ROLLBACK can occur.

Example: SAVEPOINT save1;

SET TRANSACTION: Used to set properties for a transaction, such as isolation level.

Example: SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

Each of these sub-languages plays a vital role in managing a database. DDL is for defining and
modifying database structures, DML for managing data, DQL for querying data, DCL for
controlling user access, and TCL for handling transactions and ensuring data integrity. These
sub-languages together make SQL a powerful tool for interacting with relational databases.

DDL Statements: Creating Tables, Deriving Table from Existing Table, Altering, Dropping
Tables

(a) How will you create a table from an existing table? Explain with an
example.
Asked in: S 17, W 17

To create a table from an existing table, we can use the CREATE TABLE AS SELECT statement.
This allows us to create a new table with the same structure (and optionally the data) as an
existing table.

Example:

Let's say we have a table called employees and we want to create a new table called
new_employees with the same structure and data from the employees table.

sql

CREATE TABLE new_employees AS


SELECT * FROM employees;

This query will create the new_employees table with the same columns as the employees
table, and it will copy all the data from the employees table into new_employees .

If you only want to create the table structure without copying any data, you can add a
WHERE clause that doesn't return any rows:

sql
Page 10 of 141

CREATE TABLE new_employees AS


SELECT * FROM employees WHERE 1=0;

This will create a new empty table with the same structure as the employees table.

(b) Explain how to create a table with constraints. Provide an example.


Asked in: S 16

Constraints are used to specify rules for data in a table. When creating a table, you can define
various constraints to ensure data integrity.

Types of Constraints:

1. PRIMARY KEY: Ensures that a column (or combination of columns) has unique and non-
null values.

2. FOREIGN KEY: Ensures that a value in one table corresponds to a valid value in another
table.

3. UNIQUE: Ensures that all values in a column are unique.

4. CHECK: Ensures that all values in a column satisfy a specific condition.

5. NOT NULL: Ensures that a column does not have NULL values.

Example:

sql

CREATE TABLE employees (


employee_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
department VARCHAR(50),
salary DECIMAL(10, 2),
hire_date DATE,
FOREIGN KEY (department) REFERENCES departments(department_name)
);

In this example:

employee_id is the PRIMARY KEY, ensuring it is unique and not null.

name cannot be NULL.

department has a FOREIGN KEY constraint, linking it to the department_name column in

another table called departments .

(c) Explain the CREATE, ALTER, and DROP table commands with suitable
examples.
Asked in: W 17, S 17

CREATE TABLE:

The CREATE TABLE statement is used to create a new table in the database. You define the
table's name, columns, and data types.

Example:
Page 11 of 141

sql

CREATE TABLE students (


student_id INT PRIMARY KEY,
name VARCHAR(50),
age INT
);

ALTER TABLE:

The ALTER TABLE statement is used to modify an existing table, such as adding, deleting, or
modifying columns.

Example (adding a new column):

sql

ALTER TABLE students ADD address VARCHAR(100);

Example (changing a column's data type):

sql

ALTER TABLE students MODIFY age SMALLINT;

DROP TABLE:

The DROP TABLE statement is used to delete a table from the database. This removes the
table and all of its data permanently.

Example:

sql

DROP TABLE students;

This command will completely remove the students table from the database.

(d) Explain the ALTER table command in brief.


Asked in: W 17

The ALTER TABLE command is used to modify the structure of an existing table in the
database. You can add, modify, or delete columns, constraints, or other properties of the
table using this command.

Common Uses of ALTER TABLE :

1. Adding a column:

sql

ALTER TABLE employees ADD phone_number VARCHAR(15);

2. Modifying a column (e.g., changing data type):

sql
Page 12 of 141

ALTER TABLE employees MODIFY salary DECIMAL(12, 2);

3. Dropping a column:

sql

ALTER TABLE employees DROP COLUMN phone_number;

4. Renaming a column:

sql

ALTER TABLE employees RENAME COLUMN old_column_name TO new_column_name;

The ALTER TABLE command is powerful and can be used to make many changes to an
existing table's structure.

(e) Add a new column to an existing table.


Asked in: S 18, W 18

To add a new column to an existing table, you can use the ALTER TABLE command with the
ADD keyword.

Example:

sql

ALTER TABLE employees ADD email VARCHAR(100);

In this example, we are adding a new column email of type VARCHAR(100) to the employees
table.

(f) Increase the size of a column in an existing table.


Asked in: W 18

To increase the size of a column (for example, changing a VARCHAR column to hold more
characters), you can use the ALTER TABLE command with the MODIFY keyword.

Example:

sql

ALTER TABLE employees MODIFY name VARCHAR(100);

In this example, the size of the name column is being increased from the original size to
VARCHAR(100) to allow for longer names.

Integrity Constraints, Specifying Names for the Constraints, Viewing Integrity Constraints,
Adding and Dropping Constraints
Page 13 of 141

Explain any five integrity constraints with examples:


NOT NULL, UNIQUE, PRIMARY KEY, CHECK, DEFAULT
Asked in: S 16, S 19, W 19

Integrity constraints are rules that help maintain the accuracy and reliability of data in a
database. Here are five important integrity constraints explained with examples:

1. NOT NULL
The NOT NULL constraint ensures that a column cannot have NULL values. This means that
whenever a record is inserted or updated in the table, a value must be provided for this
column.

Example:

sql

CREATE TABLE employees (


employee_id INT NOT NULL,
name VARCHAR(50) NOT NULL,
salary DECIMAL(10, 2)
);

In this example:

The employee_id and name columns cannot have NULL values.

If you try to insert a record without providing values for employee_id or name , the
database will reject the insert operation.

2. UNIQUE
The UNIQUE constraint ensures that all values in a column (or a combination of columns) are
unique. No two rows can have the same value in a column that is defined as UNIQUE .

Example:

sql

CREATE TABLE students (


student_id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
);

In this example:

The email column must contain unique values.

You cannot insert two students with the same email address into the table.
Page 14 of 141

3. PRIMARY KEY
The PRIMARY KEY constraint uniquely identifies each record in a table. A primary key column
cannot have NULL values and must contain unique values. A table can have only one primary
key, but it can consist of one or more columns (composite primary key).

Example:

sql

CREATE TABLE customers (


customer_id INT PRIMARY KEY,
name VARCHAR(100)
);

In this example:

The customer_id column is the primary key.

It must contain unique values for each customer and cannot have NULL values.

No two customers can have the same customer_id .

4. CHECK
The CHECK constraint allows you to specify a condition that must be satisfied for the values in
a column. If the condition is not met, the insert or update operation will be rejected.

Example:

sql

CREATE TABLE employees (


employee_id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2) CHECK (salary > 0)
);

In this example:

The salary column has a CHECK constraint that ensures only positive salary values are
allowed.

If you try to insert a record where the salary is zero or negative, the operation will be
rejected.

5. DEFAULT
Page 15 of 141

The DEFAULT constraint provides a default value for a column if no value is specified during
record insertion. This helps to avoid inserting NULL values when a value is not explicitly
provided.

Example:

sql

CREATE TABLE products (


product_id INT PRIMARY KEY,
product_name VARCHAR(100),
price DECIMAL(10, 2) DEFAULT 0.0
);

In this example:

The price column has a default value of 0.0 .

If a new product is inserted without specifying a price, the database will automatically set
the price to 0.0 .

These integrity constraints help to ensure that the data stored in the database is accurate,
consistent, and adheres to certain rules.

What is a Primary Key constraint? Explain with an example.


Asked in: S 18

The Primary Key constraint is a type of integrity constraint in a relational database that
uniquely identifies each record in a table. It ensures that each row in the table has a unique
value for the specified column(s), and it also ensures that no column(s) defined as a primary
key can contain NULL values.

Key points of a Primary Key:


Uniqueness: The value in the primary key column must be unique for every record in the
table. No two rows can have the same primary key value.

Non-NULL: The primary key column cannot have NULL values. Every row must have a
value for the primary key.

Single or Composite: A primary key can consist of one column (single primary key) or
multiple columns (composite primary key).

Example:
Let's consider a table called students , where we want to store information about students.
The student_id column will serve as the primary key to uniquely identify each student.

sql
Page 16 of 141

CREATE TABLE students (


student_id INT PRIMARY KEY,
name VARCHAR(100),
age INT,
email VARCHAR(100)
);

In this example:

The student_id column is defined as the Primary Key.

Each student_id must be unique, ensuring that no two students can have the same
student_id .

The student_id cannot be NULL, meaning every student must have an ID when inserted
into the table.

Inserting Data Example:

sql

INSERT INTO students (student_id, name, age, email)


VALUES (1, 'John Doe', 20, 'john.doe@example.com');

Here, the student_id value 1 is unique, and it serves as the primary key for identifying the
record for John Doe. If we attempt to insert another student with the same student_id value,
the database will reject the insertion.

sql

-- This will result in an error because the student_id is not unique


INSERT INTO students (student_id, name, age, email)
VALUES (1, 'Jane Smith', 22, 'jane.smith@example.com');

In this case, since student_id 1 already exists, trying to insert another record with the same
student_id will violate the uniqueness rule of the primary key, resulting in an error.

Thus, the Primary Key constraint is essential for maintaining the integrity of the data by
ensuring uniqueness and preventing NULL values in key columns.

What is a CHECK constraint? Explain with an example.


Asked in: S 16, W 19

The CHECK constraint is used to limit the values that can be entered into a column. It ensures
that the values stored in a column satisfy a specific condition or criteria. The condition in the
CHECK constraint can involve comparison operators (like > , < , = , etc.), logical operators

( AND , OR ), and other expressions.

Key points about the CHECK constraint:


Condition Enforcement: The condition defined in the CHECK constraint must be true for
every row in the table.
Page 17 of 141

Flexible: You can use any valid SQL expression or condition to define the check.

Column-specific: It can be applied to a single column or multiple columns in a table.

Row-based: The constraint checks the values for each row as it is inserted or updated.

Example:
Let's consider a table called employees , where we want to store the information of
employees. We will use the CHECK constraint to ensure that the employee's age must be at
least 18, as we don't want to store records for underage employees.

sql

CREATE TABLE employees (


employee_id INT PRIMARY KEY,
name VARCHAR(100),
age INT,
salary DECIMAL(10, 2),
CHECK (age >= 18)
);

In this example:

The CHECK constraint is applied to the age column.

The condition age >= 18 ensures that only employees who are 18 years or older can be
inserted into the table.

If you try to insert an employee with an age less than 18, the insertion will be rejected.

Inserting Valid Data:

sql

INSERT INTO employees (employee_id, name, age, salary)


VALUES (1, 'John Doe', 25, 50000.00);

This insert is valid because John Doe's age (25) satisfies the condition age >= 18 .

Inserting Invalid Data:

sql

-- This will result in an error because the age is less than 18


INSERT INTO employees (employee_id, name, age, salary)
VALUES (2, 'Jane Smith', 16, 45000.00);

In this case, the age value 16 violates the CHECK constraint, and the insertion will fail.

Multiple Conditions with the CHECK constraint:


You can also apply multiple conditions using logical operators.

Example: Ensure that the salary of an employee is greater than 0 and the age is at least 18.
Page 18 of 141

sql

CREATE TABLE employees (


employee_id INT PRIMARY KEY,
name VARCHAR(100),
age INT,
salary DECIMAL(10, 2),
CHECK (age >= 18 AND salary > 0)
);

In this case:

The condition age >= 18 AND salary > 0 ensures that employees must be at least 18 years
old and their salary must be a positive value.

The CHECK constraint is very useful for enforcing business rules or data validation at the
database level, ensuring that only valid data is stored in the table.

How to specify names for constraints?


Asked in: S 17

In SQL, when you define a constraint, you can optionally give it a name. Naming constraints is
useful because it helps you refer to the constraint easily later on, especially when you need to
modify or drop it. By default, if you don't specify a name for a constraint, the database system
will generate a unique name automatically. However, it is often a good practice to name
constraints explicitly for better clarity and management.

Syntax for specifying names for constraints:


When you create or modify a table, you can specify the name of a constraint in the following
way:

1. When Creating a Table:

When defining a table, you can specify the name of the constraint along with the
constraint definition.

sql

CREATE TABLE table_name (


column_name datatype,
column_name datatype,
CONSTRAINT constraint_name constraint_type (column_name)
);

constraint_name : The name you choose for the constraint.

constraint_type : The type of the constraint (e.g., PRIMARY KEY , FOREIGN KEY , CHECK ,

UNIQUE , etc.).

Examples:
1. Naming a Primary Key Constraint:
Page 19 of 141

If you want to create a table employees and name the primary key constraint as
pk_employee_id , you can do it like this:

sql

CREATE TABLE employees (


employee_id INT,
name VARCHAR(100),
age INT,
PRIMARY KEY (employee_id),
CONSTRAINT pk_employee_id PRIMARY KEY (employee_id)
);

In this case:

The constraint PRIMARY KEY is explicitly named pk_employee_id .

2. Naming a Check Constraint:

If you want to create a table students where the age should be at least 18, and you want
to name the check constraint chk_student_age , the SQL command would look like this:

sql

CREATE TABLE students (


student_id INT,
name VARCHAR(100),
age INT,
CONSTRAINT chk_student_age CHECK (age >= 18)
);

In this case:

The CHECK constraint is named chk_student_age .

3. Naming a Foreign Key Constraint:

If you want to add a foreign key to link the students table with a courses table and name
the foreign key constraint fk_student_course , the SQL would look like this:

sql

CREATE TABLE students (


student_id INT,
name VARCHAR(100),
course_id INT,
CONSTRAINT fk_student_course FOREIGN KEY (course_id)
REFERENCES courses (course_id)
);

In this case:

The FOREIGN KEY constraint is named fk_student_course .

2. When Modifying a Table:


You can also specify names for constraints when altering an existing table.
Page 20 of 141

Adding a named constraint:

sql

ALTER TABLE table_name


ADD CONSTRAINT constraint_name constraint_type (column_name);

Example: Adding a unique constraint to a column:

sql

ALTER TABLE employees


ADD CONSTRAINT unique_employee_email UNIQUE (email);

Dropping a named constraint:

sql

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;

Example: Dropping the previously added unique constraint:

sql

ALTER TABLE employees


DROP CONSTRAINT unique_employee_email;

By naming constraints, you create an easier way to manage them, especially when you need
to modify or drop the constraint later.

How to view integrity constraints in Oracle?


Asked in: S 16

In Oracle, integrity constraints such as PRIMARY KEY, FOREIGN KEY, CHECK, UNIQUE, and NOT
NULL ensure the validity and accuracy of the data stored in a database. If you want to view
the integrity constraints that have been defined on a table, Oracle provides system views that
store metadata about these constraints.

System Views to View Integrity Constraints:


1. USER_CONSTRAINTS: Contains information about all the constraints (including integrity
constraints) defined on the tables in your schema.

2. ALL_CONSTRAINTS: Contains information about all constraints on the tables you have
access to, including constraints from other schemas.

3. DBA_CONSTRAINTS: Contains information about all constraints in the entire database


(accessible to DBAs).

The USER_CONSTRAINTS view is the most commonly used to view constraints in a specific
schema.
Page 21 of 141

Steps to view integrity constraints:


1. View All Constraints on a Table: You can query the USER_CONSTRAINTS view to see the
constraints defined on a specific table in your schema.

Example query to view all constraints on a table:

sql

SELECT constraint_name, constraint_type, table_name


FROM user_constraints
WHERE table_name = 'EMPLOYEES';

constraint_name : The name of the constraint.

constraint_type : The type of the constraint (e.g., P for primary key, R for foreign key, C

for check constraint, U for unique constraint).

table_name : The name of the table to which the constraints are applied.

This query will return all the constraints on the EMPLOYEES table, showing their names
and types.

2. View Detailed Information about a Specific Constraint: If you want to see more details
about a specific constraint, such as the columns involved, you can join the
USER_CONS_COLUMNS view with USER_CONSTRAINTS .

Example to view the columns associated with each constraint:

sql

SELECT c.constraint_name, c.constraint_type, col.column_name


FROM user_constraints c
JOIN user_cons_columns col
ON c.constraint_name = col.constraint_name
WHERE c.table_name = 'EMPLOYEES';

In this query:

user_cons_columns : This view contains information about which columns are part of the

constraints.

The JOIN operation links the constraints with the specific columns involved.

This will show the columns associated with each constraint, giving you a deeper
understanding of the constraints defined on the table.

3. View Constraints on Foreign Key Relationships: If you are specifically looking for foreign key
constraints (which establish relationships between tables), you can query the
USER_CONSTRAINTS view and filter by the constraint type R (for foreign keys).

Example query to view foreign key constraints:

sql

SELECT constraint_name, table_name, r_constraint_name


FROM user_constraints
WHERE constraint_type = 'R' AND table_name = 'EMPLOYEES';
Page 22 of 141

r_constraint_name : Refers to the name of the referenced (parent) table's primary key or

unique constraint.

This will list the foreign key constraints on the EMPLOYEES table, along with the referenced
table's constraint name.

4. View Constraints for Other Schemas (if you have privileges): If you want to see constraints in
another schema, you can use the ALL_CONSTRAINTS view instead of USER_CONSTRAINTS ,
which will show constraints across all tables you have access to.

Example:

sql

SELECT constraint_name, constraint_type, owner, table_name


FROM all_constraints
WHERE table_name = 'EMPLOYEES';

owner : The schema (or user) where the table resides.

5. View Constraints in the Entire Database (for DBAs): For DBAs who want to view constraints
across the entire database, the DBA_CONSTRAINTS view can be used.

Example:

sql

SELECT constraint_name, constraint_type, owner, table_name


FROM dba_constraints
WHERE table_name = 'EMPLOYEES';

Summary of Important Columns:


CONSTRAINT_NAME: The name of the constraint.

CONSTRAINT_TYPE: The type of the constraint (e.g., P for Primary Key, R for Foreign Key,
C for Check, U for Unique).

TABLE_NAME: The name of the table on which the constraint is defined.

COLUMN_NAME: The name of the column(s) that are associated with the constraint.

R_CONSTRAINT_NAME: For foreign key constraints, the name of the parent table's primary
or unique constraint.

These queries and views provide a simple way to view integrity constraints in Oracle, which
helps in managing and ensuring data consistency within your database.

How to add and drop constraints in Oracle?


Asked in: S 16

In Oracle, constraints are used to enforce rules on the data in a table, ensuring that the data is
accurate, consistent, and reliable. You can add or drop constraints on a table to manage these
Page 23 of 141

rules as per your requirement. Below is a detailed explanation of how to add and drop
different types of constraints.

1. Adding Constraints:
To add a constraint to an existing table, the ALTER TABLE statement is used with the ADD
CONSTRAINT clause. The syntax for adding constraints depends on the type of constraint you

want to add.

a. Adding a PRIMARY KEY Constraint:

A primary key constraint ensures that each row in a table has a unique value in a specified
column(s), and it does not allow NULL values.

Syntax:

sql

ALTER TABLE table_name


ADD CONSTRAINT constraint_name PRIMARY KEY (column_name);

Example:

sql

ALTER TABLE employees


ADD CONSTRAINT emp_pk PRIMARY KEY (employee_id);

This adds a primary key constraint named emp_pk on the employee_id column of the
employees table.

b. Adding a FOREIGN KEY Constraint:

A foreign key constraint establishes a link between two tables. It ensures that values in the
column(s) of the child table exist in the column(s) of the parent table.

Syntax:

sql

ALTER TABLE child_table


ADD CONSTRAINT constraint_name FOREIGN KEY (child_column) REFERENCES
parent_table (parent_column);

Example:

sql

ALTER TABLE orders


ADD CONSTRAINT fk_emp FOREIGN KEY (employee_id) REFERENCES employees
(employee_id);

This adds a foreign key constraint named fk_emp on the employee_id column of the orders
table, referencing the employee_id column in the employees table.

c. Adding a UNIQUE Constraint:


Page 24 of 141

A unique constraint ensures that all values in a column are distinct.

Syntax:

sql

ALTER TABLE table_name


ADD CONSTRAINT constraint_name UNIQUE (column_name);

Example:

sql

ALTER TABLE employees


ADD CONSTRAINT emp_email_unique UNIQUE (email);

This adds a unique constraint on the email column of the employees table, ensuring no two
rows can have the same email value.

d. Adding a CHECK Constraint:

A check constraint is used to limit the values that can be stored in a column by specifying a
condition.

Syntax:

sql

ALTER TABLE table_name


ADD CONSTRAINT constraint_name CHECK (condition);

Example:

sql

ALTER TABLE employees


ADD CONSTRAINT age_check CHECK (age >= 18);

This adds a check constraint on the age column of the employees table, ensuring that only
employees who are 18 years or older can be added.

e. Adding a NOT NULL Constraint:

A NOT NULL constraint ensures that a column does not accept NULL values.

Syntax:

sql

ALTER TABLE table_name


MODIFY column_name NOT NULL;

Example:

sql

ALTER TABLE employees


Page 25 of 141

MODIFY first_name NOT NULL;

This ensures that the first_name column in the employees table cannot have NULL values.

2. Dropping Constraints:
To remove a constraint from a table, the ALTER TABLE statement is used with the DROP
CONSTRAINT clause.

a. Dropping a Primary Key Constraint:

To drop a primary key constraint, you use the DROP CONSTRAINT clause along with the name
of the primary key constraint.

Syntax:

sql

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;

Example:

sql

ALTER TABLE employees


DROP CONSTRAINT emp_pk;

This removes the primary key constraint named emp_pk from the employees table.

b. Dropping a Foreign Key Constraint:

To drop a foreign key constraint, you specify the name of the foreign key constraint in the
DROP CONSTRAINT clause.

Syntax:

sql

ALTER TABLE child_table


DROP CONSTRAINT constraint_name;

Example:

sql

ALTER TABLE orders


DROP CONSTRAINT fk_emp;

This removes the foreign key constraint named fk_emp from the orders table.

c. Dropping a Unique Constraint:

To drop a unique constraint, specify the constraint name in the DROP CONSTRAINT clause.

Syntax:

sql
Page 26 of 141

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;

Example:

sql

ALTER TABLE employees


DROP CONSTRAINT emp_email_unique;

This removes the unique constraint named emp_email_unique from the employees table.

d. Dropping a Check Constraint:

To drop a check constraint, you use the DROP CONSTRAINT clause, specifying the constraint
name.

Syntax:

sql

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;

Example:

sql

ALTER TABLE employees


DROP CONSTRAINT age_check;

This removes the check constraint named age_check from the employees table.

e. Dropping a NOT NULL Constraint:

To drop a NOT NULL constraint (i.e., allowing NULL values again), you use the MODIFY
clause.

Syntax:

sql

ALTER TABLE table_name


MODIFY column_name NULL;

Example:

sql

ALTER TABLE employees


MODIFY first_name NULL;

This allows the first_name column to accept NULL values once again.

Summary:
Page 27 of 141

Adding Constraints: Use ALTER TABLE with ADD CONSTRAINT for primary key, foreign key,
unique, check, or modify column constraints.

Dropping Constraints: Use ALTER TABLE with DROP CONSTRAINT for removing constraints
like primary key, foreign key, unique, or check constraints.

DML Statements: SELECT Statement, Insert, Update, Delete

Write SQL queries for the following:

1. Insert a record into the Student table.

2. Update a record in the Employee table.

3. Delete a record from the Student table.

Asked in: S 16, W 19

1. Insert a record into the Student table:


To insert a record into the Student table, the INSERT INTO statement is used. This allows us
to specify the values for the respective columns.

Example:

sql

INSERT INTO Student (StudentID, Name, Age, Course)


VALUES (101, 'John Doe', 20, 'BSc Computer Science');

Explanation:

StudentID , Name , Age , and Course are the columns of the Student table.

VALUES specifies the data to be inserted into the respective columns.

The record inserted is:

StudentID: 101

Name: John Doe

Age: 20

Course: BSc Computer Science .

2. Update a record in the Employee table:


To update a record in the Employee table, the UPDATE statement is used. It allows us to
modify existing records by specifying the column to be updated and the condition.

Example:

sql
Page 28 of 141

UPDATE Employee
SET Salary = 55000
WHERE EmployeeID = 5;

Explanation:

UPDATE Employee : Specifies the table to update.

SET Salary = 55000 : Updates the Salary column to 55000 .

WHERE EmployeeID = 5 : Ensures only the record with EmployeeID equal to 5 is updated.

3. Delete a record from the Student table:


To delete a record from the Student table, the DELETE statement is used. It removes rows
based on a specified condition.

Example:

sql

DELETE FROM Student


WHERE StudentID = 101;

Explanation:

DELETE FROM Student : Specifies the table from which the record will be deleted.

WHERE StudentID = 101 : Ensures only the record with StudentID equal to 101 is

removed.

Write a query to find the students whose name begins with the letter 'A'.

Asked in: W 19

Query to Find Students Whose Name Begins with 'A':


To find students whose names start with the letter 'A', the LIKE operator is used in
combination with a wildcard ( % ).

Example:

sql

SELECT *
FROM Student
WHERE Name LIKE 'A%';

Explanation:
SELECT * : This retrieves all columns from the Student table.
Page 29 of 141

FROM Student : Specifies the table to query, i.e., Student .

WHERE Name LIKE 'A%' :

LIKE is used to match patterns in the Name column.

'A%' means the name should start with the letter A and can be followed by zero or

more characters ( % is a wildcard for any sequence of characters).

Example Scenario:
Suppose the Student table contains the following data:

StudentID Name Age Course

101 Alice 20 BSc Computer Science

102 Bob 21 BSc Mathematics

103 Andrew 19 BA English

104 Sophia 22 BCom

Query Output:

The result of the query would be:

StudentID Name Age Course

101 Alice 20 BSc Computer Science

103 Andrew 19 BA English

Write SQL queries to perform the following operations on a SUPPLIER table:

1. Find the supplier's name for a given SUPPLIER_ID.

2. Find suppliers belonging to a specific city.

Asked in: S 17

1. Find the supplier's name for a given SUPPLIER_ID:


To retrieve the supplier's name based on their SUPPLIER_ID , the SELECT statement is used
with a WHERE clause.

Query:

sql

SELECT SupplierName
FROM SUPPLIER
Page 30 of 141

WHERE SUPPLIER_ID = 101;

Explanation:

SELECT SupplierName : Retrieves the SupplierName column from the SUPPLIER table.

FROM SUPPLIER : Specifies the table to query, i.e., SUPPLIER .

WHERE SUPPLIER_ID = 101 : Filters the records to return the name of the supplier with

SUPPLIER_ID equal to 101 . Replace 101 with the desired ID for other queries.

2. Find suppliers belonging to a specific city:


To retrieve all suppliers from a particular city, the SELECT statement is used with a WHERE
clause filtering by City .

Query:

sql

SELECT *
FROM SUPPLIER
WHERE City = 'Mumbai';

Explanation:

SELECT * : Retrieves all columns for the suppliers meeting the condition.

FROM SUPPLIER : Specifies the table to query, i.e., SUPPLIER .

WHERE City = 'Mumbai' : Filters the records to find suppliers located in Mumbai . Replace

'Mumbai' with the name of another city to search for suppliers from different cities.

Example Data in the SUPPLIER Table:

SUPPLIER_ID SupplierName City PhoneNumber

101 ABC Traders Mumbai 1234567890

102 XYZ Supplies Delhi 9876543210

103 PQR Exports Mumbai 1122334455

Results:

1. Query 1: If SUPPLIER_ID = 101 , the result will be:

SupplierName

ABC Traders
Page 31 of 141

2. Query 2: If City = 'Mumbai' , the result will be:

SUPPLIER_ID SupplierName City PhoneNumber

101 ABC Traders Mumbai 1234567890

103 PQR Exports Mumbai 1122334455

Write a query to delete records with fees less than 5000.

Asked in: S 16

Query:
sql

DELETE FROM Student


WHERE Fees < 5000;

Explanation:
DELETE FROM Student : This command is used to remove rows from the Student table.

WHERE Fees < 5000 : Specifies the condition to identify the rows to be deleted. Only records

where the Fees column has a value less than 5000 will be removed.

Example Data in the Student Table:

StudentID StudentName Fees

101 John 4500

102 Alice 6000

103 David 3000

104 Maria 7000

After executing the query:

Records with StudentID 101 and 103 will be deleted because their Fees values are less
than 5000 .
Page 32 of 141

Resulting Table:

StudentID StudentName Fees

102 Alice 6000

104 Maria 7000

Working with Sequences and Synonyms

What are sequences and how do they work in SQL?

Asked in: S 16

Explanation:
A sequence in SQL is a database object used to generate a series of unique numbers, typically
used for primary key values or other unique identifiers. Sequences are independent of tables,
meaning they can be shared across multiple tables or columns. They are especially useful
when inserting new records where a unique value is required.

Key Features of Sequences:


1. Automatic Number Generation: A sequence generates numbers automatically in a defined
order.

2. Customizable Settings: You can specify the starting value, increment, maximum value, and
cycling behavior.

3. Independent of Tables: Sequences are not tied to a specific table and can be reused for
multiple tables.

4. Thread-Safe: Sequences ensure no duplicate values even in concurrent environments.

Syntax to Create a Sequence:


sql

CREATE SEQUENCE sequence_name


START WITH starting_number
INCREMENT BY increment_value
Page 33 of 141

[ MAXVALUE max_value | NOMAXVALUE ]


[ MINVALUE min_value | NOMINVALUE ]
[ CYCLE | NOCYCLE ];

Example:

Creating a Sequence:

sql

CREATE SEQUENCE Student_Seq


START WITH 1
INCREMENT BY 1
MAXVALUE 1000
NOCYCLE;

START WITH 1 : The sequence starts at 1.

INCREMENT BY 1 : Each new value increments by 1.

MAXVALUE 1000 : The sequence stops at 1000.

NOCYCLE : The sequence does not restart after reaching its maximum value.

Using the Sequence:

1. Get the Next Value:

sql

SELECT Student_Seq.NEXTVAL FROM dual;

This returns the next value in the sequence, such as 1 , 2 , 3 , and so on.

2. Insert Values into a Table:

sql

INSERT INTO Student (StudentID, StudentName)


VALUES (Student_Seq.NEXTVAL, 'Alice');

Here, the sequence Student_Seq provides a unique StudentID for each new record.

Viewing Existing Sequences:

To see all the sequences in the database:


Page 34 of 141
sql

SELECT * FROM USER_SEQUENCES;

Dropping a Sequence:

To delete a sequence:

sql

DROP SEQUENCE Student_Seq;

What are Synonyms? Explain with syntax for creating and deleting synonyms.

Asked in: S 18, S 19

Explanation:
A synonym in SQL is an alias or alternative name for a database object such as a table, view,
sequence, or another synonym. Synonyms are used to simplify complex or long object names
and to allow users to refer to an object without needing to know its actual location (schema
or database). They act as a shortcut to accessing the original object.

Synonyms are helpful when you want to provide a different name for a database object that
is easier to reference or when an object resides in a different schema, and you want to avoid
writing the full schema name every time.

Types of Synonyms:
1. Public Synonyms: These are available to all users in the database.

2. Private Synonyms: These are available only to the user who created them.

Syntax to Create a Synonym:

For a Table or View:

sql

CREATE [PUBLIC] SYNONYM synonym_name


FOR schema_name.object_name;
Page 35 of 141

[PUBLIC] : Optional. When specified, the synonym is created for all users. If omitted, the

synonym is private to the creator.

synonym_name : The name you want to give to the synonym.

schema_name.object_name : The fully qualified name of the object (table, view, etc.) that the

synonym refers to.

Example:

Creating a private synonym for a table in another schema:

sql

CREATE SYNONYM emp_synonym


FOR hr.employees;

Here, the synonym emp_synonym refers to the employees table in the hr schema. Now,
users can access the employees table using emp_synonym instead of hr.employees .

Creating a public synonym:

sql

CREATE PUBLIC SYNONYM emp_public_synonym


FOR hr.employees;

Now, any user in the database can use emp_public_synonym to access the employees table
from the hr schema.

Syntax to Drop a Synonym:


To delete a synonym:

sql

DROP [PUBLIC] SYNONYM synonym_name;

[PUBLIC] : Optional. Use this if the synonym is a public synonym.

synonym_name : The name of the synonym to be dropped.

Example:

Dropping a private synonym:

sql

DROP SYNONYM emp_synonym;

Dropping a public synonym:

sql
Page 36 of 141

DROP PUBLIC SYNONYM emp_public_synonym;

Practical Use Case for Synonyms:


Consider you have a large application with multiple schemas. Instead of using the full object
name like hr.employees , you can create a synonym emp_synonym that simplifies references in
SQL queries.

Example Query Using Synonym:

sql

SELECT * FROM emp_synonym;

This query accesses the employees table in the hr schema without directly referencing the
schema name.

1/2

Create a synonym for a table in SQL.

Asked in: W 17, W 19

Explanation:
A synonym in SQL is an alias or alternative name for a table, view, sequence, or other
database objects. Synonyms are particularly useful to simplify object references, especially
when accessing objects from other schemas or databases. They help reduce complexity and
improve readability in SQL queries.

When you create a synonym for a table, you can use the synonym name in queries instead of
the original table name.

Syntax to Create a Synonym for a Table:


sql

CREATE [PUBLIC] SYNONYM synonym_name


FOR schema_name.table_name;

[PUBLIC] : Optional. If specified, the synonym is public and accessible by all database users.

synonym_name : The new name you want to give to the table.


Page 37 of 141

schema_name.table_name : The fully qualified name of the original table.

Example: Private Synonym


Suppose there is a table named employees in the schema hr . You want to create a synonym
emp_table for this table.

sql

CREATE SYNONYM emp_table


FOR hr.employees;

Now, instead of writing hr.employees , you can simply refer to the table as emp_table in
your SQL queries.

Query Using the Synonym:

sql

SELECT * FROM emp_table;

Example: Public Synonym


If you want all users in the database to access the synonym without referring to the schema,
create a public synonym.

sql

CREATE PUBLIC SYNONYM emp_table_public


FOR hr.employees;

Any user in the database can now query the employees table using emp_table_public .

Query Using the Public Synonym:

sql

SELECT * FROM emp_table_public;

How to Drop a Synonym


To remove a synonym, use the DROP SYNONYM statement.

Syntax:
Page 38 of 141

sql

DROP [PUBLIC] SYNONYM synonym_name;

Example: Dropping a Private Synonym

sql

DROP SYNONYM emp_table;

Example: Dropping a Public Synonym

sql

DROP PUBLIC SYNONYM emp_table_public;

Built-in Functions: Arithmetic, Date, Character, Conversion, Single Row, Aggregate, Decode

Explain any two date functions with suitable examples.

Asked in: S 16, W 16, S 19

Explanation:
Date functions in SQL are used to perform operations on date and time values. They help in
retrieving, manipulating, and formatting date data. Two commonly used date functions are
SYSDATE and ADD_MONTHS .

1. SYSDATE Function
The SYSDATE function is used to retrieve the current system date and time based on the
database server's settings. It does not take any arguments and returns a DATE value.

Syntax:

sql

SYSDATE

Example:

Suppose you want to display the current date and time.

sql
Page 39 of 141

SELECT SYSDATE AS current_date_time


FROM dual;

Output (Example):

current_date_time

2025-01-04 15:30:45

In this example, the SYSDATE function retrieves the current date and time, which can vary
depending on when the query is executed.

2. ADD_MONTHS Function
The ADD_MONTHS function is used to add or subtract a specific number of months to/from a
given date. It is useful for calculating future or past dates.

Syntax:

sql

ADD_MONTHS(date, number_of_months)

date : The base date.

number_of_months : The number of months to add (positive value) or subtract (negative

value).

Example:

Suppose you want to calculate the date three months from now.

sql

SELECT ADD_MONTHS(SYSDATE, 3) AS future_date


FROM dual;

Output (Example):

future_date

2025-04-04

Here, the ADD_MONTHS function calculates the date exactly three months ahead of the
current date returned by SYSDATE .

Subtracting Months:

If you want to subtract months, use a negative value for the number_of_months parameter. For
example:
Page 40 of 141
sql

SELECT ADD_MONTHS(SYSDATE, -2) AS past_date


FROM dual;

Output (Example):

past_date

2024-11-04

This query calculates the date two months before the current date.

These two functions ( SYSDATE and ADD_MONTHS ) are powerful tools for handling date-
related operations in SQL.

Write SQL queries using the following functions with examples: TRUNC, ROUND, MOD, CEIL,
POWER

Asked in: W 18

Explanation:
Here we will look at the SQL functions TRUNC , ROUND , MOD , CEIL , and POWER . These
functions are typically used for numerical operations, including rounding, truncating,
calculating remainders, and performing mathematical powers.

1. TRUNC Function
The TRUNC function is used to truncate a number or date to a specified number of decimal
places or to a specific date format. It doesn't round the value; it simply cuts off the decimals
beyond the specified precision.

Syntax:

sql

TRUNC(number, decimal_places)

number : The number you want to truncate.

decimal_places : The number of decimal places to retain.


Page 41 of 141

Example:

Truncate the number 123.4567 to two decimal places.

sql

SELECT TRUNC(123.4567, 2) AS truncated_value


FROM dual;

Output:

truncated_value

123.45

2. ROUND Function
The ROUND function is used to round a number to the nearest value, based on the number
of decimal places you specify. It rounds up or down depending on the value of the next
decimal place.

Syntax:

sql

ROUND(number, decimal_places)

number : The number to be rounded.

decimal_places : The number of decimal places to round to.

Example:

Round the number 123.4567 to two decimal places.

sql

SELECT ROUND(123.4567, 2) AS rounded_value


FROM dual;

Output:

rounded_value

123.46

3. MOD Function
Page 42 of 141

The MOD function is used to return the remainder when one number is divided by another. It
is essentially the modulus operation.

Syntax:

sql

MOD(number1, number2)

number1 : The dividend.

number2 : The divisor.

Example:

Find the remainder when 123 is divided by 10 .

sql

SELECT MOD(123, 10) AS remainder


FROM dual;

Output:

remainder

4. CEIL Function
The CEIL function (short for "ceiling") returns the smallest integer greater than or equal to
the given number. It rounds the number up to the next whole number.

Syntax:

sql

CEIL(number)

number : The number you want to round up.

Example:

Find the ceiling value of 123.456 .

sql

SELECT CEIL(123.456) AS ceiling_value


FROM dual;

Output:
Page 43 of 141

ceiling_value

124

5. POWER Function
The POWER function is used to raise a number to the power of another number (i.e., it
calculates the exponentiation).

Syntax:

sql

POWER(base, exponent)

base : The number to be raised to a power.

exponent : The power to which the base is raised.

Example:

Find the value of 2 raised to the power of 3 .

sql

SELECT POWER(2, 3) AS power_value


FROM dual;

Output:

power_value

These functions are fundamental tools in SQL for numerical and mathematical calculations,
and they are often used in data analysis and reporting.

Explain the use of DECODE function with an example


Asked in: S 16

Explanation of the DECODE Function:


Page 44 of 141

The DECODE function in SQL is a powerful conditional function used to perform an IF-THEN-
ELSE operation. It allows you to return different values based on certain conditions, similar to
a CASE statement or an IF-ELSE statement in other programming languages. The DECODE
function compares a given expression to a series of values and returns a result based on the
match.

The basic syntax of the DECODE function is as follows:

Syntax:

sql

DECODE(expression, search_1, result_1, search_2, result_2, ..., default_value)

expression : The value that you want to compare.

search_n : The value that the expression is compared to.

result_n : The value that is returned if the expression matches search_n .

default_value (optional): The value returned if none of the searches match the expression.

If the expression matches any of the search_n values, the corresponding result_n is returned.
If there is no match, the default_value is returned (if provided). If there is no match and no
default, it returns NULL .

Example:
Consider a table EMPLOYEE with the following columns:

EMP_ID

EMP_NAME

EMP_SALARY

We want to categorize employees based on their salary and return a description of their
salary range using the DECODE function.

SQL Query:

sql

SELECT EMP_NAME, EMP_SALARY,


DECODE(
EMP_SALARY,
10000, 'Low Salary',
20000, 'Medium Salary',
30000, 'High Salary',
'Salary Not Found') AS SALARY_CATEGORY
FROM EMPLOYEE;

In this example:
Page 45 of 141

If an employee's salary is 10000 , it will return 'Low Salary' .

If an employee's salary is 20000 , it will return 'Medium Salary' .

If an employee's salary is 30000 , it will return 'High Salary' .

If the salary is not one of the specified values (i.e., not 10000 , 20000 , or 30000 ), it will
return 'Salary Not Found' .

Output:

EMP_NAME EMP_SALARY SALARY_CATEGORY

John 10000 Low Salary

Alice 20000 Medium Salary

Bob 30000 High Salary

Charlie 15000 Salary Not Found

Conclusion:
The DECODE function is used to check a value against a list of conditions and return a
corresponding result.

It is useful in transforming data and performing conditional logic directly within the SQL
query.

Explain the following aggregate functions with examples: SUM, AVG, COUNT, MAX, MIN
Asked in: W 17

Explanation of Aggregate Functions:


Aggregate functions in SQL are used to perform calculations on a set of rows and return a
single result. These functions are often used in conjunction with the GROUP BY clause to
group rows and perform calculations on each group. Let's look at each aggregate function
with examples:
Page 46 of 141

1. SUM() Function:
The SUM() function is used to calculate the total (sum) of a numeric column.

Syntax:

sql

SELECT SUM(column_name)
FROM table_name;

Example:

Consider the SALES table with the following columns:

SALE_ID

SALE_AMOUNT

To find the total sales amount, we can use the SUM() function:

sql

SELECT SUM(SALE_AMOUNT) AS TOTAL_SALES


FROM SALES;

If the SALES table contains the following data:

SALE_ID SALE_AMOUNT

1 100

2 200

3 300

The result would be:

TOTAL_SALES

600

2. AVG() Function:
The AVG() function is used to calculate the average (mean) of a numeric column.

Syntax:

sql

SELECT AVG(column_name)
FROM table_name;
Page 47 of 141

Example:

Using the same SALES table, we can calculate the average sale amount:

sql

SELECT AVG(SALE_AMOUNT) AS AVERAGE_SALE


FROM SALES;

For the same data:

SALE_ID SALE_AMOUNT

1 100

2 200

3 300

The result would be:

AVERAGE_SALE

200

3. COUNT() Function:
The COUNT() function is used to count the number of rows that match a specified condition.
It can count all rows or only non-NULL rows.

Syntax:

sql

SELECT COUNT(column_name)
FROM table_name;

Example:

To count the number of sales records in the SALES table:

sql

SELECT COUNT(SALE_ID) AS TOTAL_SALES_RECORDS


FROM SALES;

For the same data:

SALE_ID SALE_AMOUNT

1 100
Page 48 of 141

SALE_ID SALE_AMOUNT

2 200

3 300

The result would be:

TOTAL_SALES_RECORDS

4. MAX() Function:
The MAX() function is used to find the maximum value in a numeric or date column.

Syntax:

sql

SELECT MAX(column_name)
FROM table_name;

Example:

To find the highest sale amount from the SALES table:

sql

SELECT MAX(SALE_AMOUNT) AS HIGHEST_SALE


FROM SALES;

For the same data:

SALE_ID SALE_AMOUNT

1 100

2 200

3 300

The result would be:

HIGHEST_SALE

300
Page 49 of 141

5. MIN() Function:
The MIN() function is used to find the minimum value in a numeric or date column.

Syntax:

sql

SELECT MIN(column_name)
FROM table_name;

Example:

To find the lowest sale amount from the SALES table:

sql

SELECT MIN(SALE_AMOUNT) AS LOWEST_SALE


FROM SALES;

For the same data:

SALE_ID SALE_AMOUNT

1 100

2 200

3 300

The result would be:

LOWEST_SALE

100

Conclusion:
SUM() calculates the total of a numeric column.

AVG() calculates the average (mean) value of a numeric column.

COUNT() counts the number of rows in a table or those that meet a condition.

MAX() returns the highest value in a numeric or date column.

MIN() returns the lowest value in a numeric or date column.

These functions are useful for aggregating and summarizing data from large tables. They can
also be used with GROUP BY to perform calculations on subsets of data.

Joins, Set Operators, and Subqueries


Page 50 of 141

Asked in: S 16, W 17

Question: Explain the different types of JOINS in SQL with examples.

In SQL, JOINS are used to combine records from two or more tables based on a related
column between them. There are mainly four types of JOINS: INNER JOIN, LEFT JOIN (LEFT
OUTER JOIN), RIGHT JOIN (RIGHT OUTER JOIN), and FULL OUTER JOIN.

1. INNER JOIN:
The INNER JOIN keyword is used to fetch rows from both tables where there is a match
between the specified columns. If there is no match, the row will not appear in the result set.

Syntax:

sql

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

Example:

Let's consider two tables, Employees and Departments :

plaintext

Employees:
| Employee_ID | Name | Department_ID |
|-------------|-------|---------------|
|1 | John | 10 |
|2 | Alice | 20 |
|3 | Bob | 10 |

Departments:
| Department_ID | Department_Name |
|---------------|-----------------|
| 10 | HR |
| 20 | IT |

To find employees along with their department names, we can use an INNER JOIN :

sql

SELECT Employees.Name, Departments.Department_Name


FROM Employees
INNER JOIN Departments
ON Employees.Department_ID = Departments.Department_ID;

Result:
Page 51 of 141

Name Department_Name

John HR

Alice IT

Bob HR

2. LEFT JOIN (LEFT OUTER JOIN):


The LEFT JOIN (also called LEFT OUTER JOIN) returns all records from the left table (table1)
and the matching records from the right table (table2). If there is no match, the result is NULL
on the side of the right table.

Syntax:

sql

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

Example:

If you want to list all employees along with their department names, even if they don't
belong to any department:

sql

SELECT Employees.Name, Departments.Department_Name


FROM Employees
LEFT JOIN Departments
ON Employees.Department_ID = Departments.Department_ID;

Result:

Name Department_Name

John HR

Alice IT

Bob HR

Dave NULL

In this case, Dave is not assigned to any department, so the department name is NULL.

3. RIGHT JOIN (RIGHT OUTER JOIN):


The RIGHT JOIN (also called RIGHT OUTER JOIN) returns all records from the right table
(table2) and the matching records from the left table (table1). If there is no match, the result
Page 52 of 141

is NULL on the side of the left table.

Syntax:

sql

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Example:

If you want to find all departments along with their employees, even if a department has no
employees:

sql

SELECT Employees.Name, Departments.Department_Name


FROM Employees
RIGHT JOIN Departments
ON Employees.Department_ID = Departments.Department_ID;

Result:

Name Department_Name

John HR

Alice IT

Bob HR

NULL Finance

Here, the Finance department has no employees, so the employee's name is NULL.

4. FULL OUTER JOIN:


The FULL OUTER JOIN returns all records when there is a match in either the left (table1) or
the right (table2) table. If there is no match, the result is NULL for missing matches on both
sides.

Syntax:

sql

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;

Example:
Page 53 of 141

To find all employees and all departments, even if some departments have no employees or
some employees are not assigned to any department:

sql

SELECT Employees.Name, Departments.Department_Name


FROM Employees
FULL OUTER JOIN Departments
ON Employees.Department_ID = Departments.Department_ID;

Result:

Name Department_Name

John HR

Alice IT

Bob HR

Dave NULL

NULL Finance

In this result, all employees and all departments are listed, including those without matches.

Each type of JOIN serves different use cases when dealing with relational data across
multiple tables. Understanding the differences between these JOIN types allows you to write
more efficient SQL queries tailored to your specific requirements.

Asked in: W 17

Question: What are Set Operators? Explain with examples of UNION, INTERSECT, and EXCEPT.

Set operators in SQL are used to combine the results of two or more SELECT queries. These
operators help in combining and comparing the result sets in a specific way. The most
commonly used set operators are UNION, INTERSECT, and EXCEPT.

1. UNION:
The UNION operator combines the result sets of two or more SELECT queries. It returns all
unique rows from both SELECT statements, eliminating duplicates. If you want to include
duplicate rows, you can use UNION ALL.

Syntax:

sql

SELECT column_name(s)
FROM table1
Page 54 of 141

UNION
SELECT column_name(s)
FROM table2;

Example:

Consider two tables, Employees and Contractors , both having columns Employee_ID and
Name .

plaintext

Employees:
| Employee_ID | Name |
|-------------|--------|
|1 | John |
|2 | Alice |

Contractors:
| Employee_ID | Name |
|-------------|--------|
|3 | Bob |
|2 | Alice |

To combine the lists of employees and contractors without duplicates, we use the UNION
operator:

sql

SELECT Employee_ID, Name


FROM Employees
UNION
SELECT Employee_ID, Name
FROM Contractors;

Result:

Employee_ID Name

1 John

2 Alice

3 Bob

In this result, Alice appears only once because UNION removes duplicates.

2. INTERSECT:
The INTERSECT operator returns only the rows that are common to both SELECT queries. It
compares the result sets and returns only the matching rows.

Syntax:

sql
Page 55 of 141

SELECT column_name(s)
FROM table1
INTERSECT
SELECT column_name(s)
FROM table2;

Example:

Using the same Employees and Contractors tables, to find people who are both employees
and contractors (i.e., common entries in both tables), we use INTERSECT:

sql

SELECT Employee_ID, Name


FROM Employees
INTERSECT
SELECT Employee_ID, Name
FROM Contractors;

Result:

Employee_ID Name

2 Alice

In this case, only Alice is present in both tables, so she is the result of the INTERSECT.

3. EXCEPT:
The EXCEPT operator returns the rows from the first SELECT query that do not exist in the
second SELECT query. It essentially subtracts the result of the second query from the first
query.

Syntax:

sql

SELECT column_name(s)
FROM table1
EXCEPT
SELECT column_name(s)
FROM table2;

Example:

If you want to find employees who are not contractors (i.e., records that exist in the
Employees table but not in the Contractors table), you can use the EXCEPT operator:

sql

SELECT Employee_ID, Name


FROM Employees
EXCEPT
Page 56 of 141

SELECT Employee_ID, Name


FROM Contractors;

Result:

Employee_ID Name

1 John

In this case, only John is in the Employees table but not in the Contractors table, so the result
will only show his record.

Key Points:
UNION returns all unique rows from both queries.

INTERSECT returns only the common rows between the queries.

EXCEPT returns rows from the first query that do not exist in the second query.

These operators are useful for comparing data from multiple tables and for handling complex
queries involving data across different datasets.

Asked in: W 17

Question: What is a subquery? Explain with an example.

A subquery in SQL is a query nested inside another query. It is used to retrieve data that will
be used by the main query. Subqueries are enclosed within parentheses and can be used in
various parts of the SQL statement, such as in the SELECT, WHERE, or FROM clauses. They
allow you to perform more complex queries and are particularly useful when you need to
filter data based on another set of data.

Subqueries can be categorized into:

1. Single-row subquery: Returns a single value.

2. Multi-row subquery: Returns multiple values (e.g., a list of values).

3. Correlated subquery: Refers to the outer query for its values.

4. Non-correlated subquery: Independent and does not reference the outer query.

Example 1: Single-row subquery


Suppose we have the following two tables:

Employees:

Employee_ID Name Salary

1 John 5000
Page 57 of 141

Employee_ID Name Salary

2 Alice 6000

3 Bob 4000

Departments:

Department_ID Employee_ID Department_Name

101 1 HR

102 2 IT

103 3 Finance

Now, you want to find the employees whose salary is greater than the average salary of all
employees.

Here, the subquery computes the average salary, and the main query retrieves employees
whose salary is greater than that value.

sql

SELECT Name, Salary


FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);

In this query:

The subquery (SELECT AVG(Salary) FROM Employees) calculates the average salary of all
employees (i.e., 5000).

The main query retrieves the employees whose salary is greater than this average.

Result:

Name Salary

Alice 6000

Example 2: Multi-row subquery


If you want to find employees who work in the departments with a salary greater than 5000,
you can use a multi-row subquery. For example, you want to retrieve employees who work in
departments with a salary greater than 5000.

sql

SELECT Name, Salary


FROM Employees
WHERE Department_ID IN (SELECT Department_ID FROM Departments WHERE
Employee_ID IN (SELECT Employee_ID FROM Employees WHERE Salary > 5000));
Page 58 of 141

In this example:

The innermost subquery retrieves the Employee_IDs of those employees whose salary is
greater than 5000.

The middle subquery retrieves the Department_IDs for those employees.

The main query fetches the names and salaries of employees working in those
departments.

Result:

Name Salary

Alice 6000

Example 3: Correlated Subquery


In a correlated subquery, the subquery references columns from the outer query. For
example, if you want to find employees who earn more than the average salary in their
respective departments, you could write a correlated subquery:

sql

SELECT Name, Salary, Department_ID


FROM Employees E
WHERE Salary > (SELECT AVG(Salary) FROM Employees WHERE Department_ID =
E.Department_ID);

In this case:

The subquery references the Department_ID from the outer query ( E.Department_ID ),
making it a correlated subquery.

The subquery calculates the average salary for each department.

The main query returns employees whose salary is greater than the average salary in their
department.

Result:

Name Salary Department_ID

Alice 6000 102

Key Points:
A subquery is a query inside another query, typically used to return values to be used by
the outer query.

It can be single-row or multi-row depending on the number of values it returns.

A correlated subquery refers to the outer query, while a non-correlated subquery does not.
Page 59 of 141

DCL and TCL Statements: Grant, Revoke, Commit, Rollback, Savepoints

Asked in: S 19, W 16

Question: What is the purpose of GRANT and REVOKE commands in SQL? Explain with
examples.

The GRANT and REVOKE commands in SQL are used to control user access to the database
and its objects (like tables, views, etc.). These commands are part of Data Control Language
(DCL) and are essential for managing permissions.

GRANT Command:
The GRANT command is used to give a user or role specific privileges on a database object,
such as a table or view. This allows the user to perform certain operations (like SELECT,
INSERT, UPDATE, DELETE) on the object.

Syntax for GRANT:

sql

GRANT privilege(s) ON object TO user;

privilege(s): The actions you want to allow (e.g., SELECT, INSERT, UPDATE).

object: The database object you want to give access to (e.g., a table).

user: The user or role to whom you are granting the privilege.

Example 1: Granting SELECT privilege to a user on a table:

sql

GRANT SELECT ON employees TO john;

In this example, the john user is granted the SELECT privilege on the employees table,
meaning he can view data from that table.

Example 2: Granting multiple privileges to a user:

sql

GRANT SELECT, INSERT, UPDATE ON employees TO john;

This gives john the rights to SELECT, INSERT, and UPDATE data in the employees table.

REVOKE Command:
The REVOKE command is used to remove previously granted privileges from a user or role.
This is essential for security purposes when you need to take back permissions.

Syntax for REVOKE:

sql
Page 60 of 141

REVOKE privilege(s) ON object FROM user;

privilege(s): The actions you want to revoke (e.g., SELECT, INSERT, UPDATE).

object: The database object from which you want to remove access.

user: The user or role from whom you are revoking the privilege.

Example 1: Revoking SELECT privilege from a user:

sql

REVOKE SELECT ON employees FROM john;

This removes the SELECT privilege from john on the employees table. After this, john can no
longer view data from the table.

Example 2: Revoking multiple privileges from a user:

sql

REVOKE SELECT, INSERT ON employees FROM john;

This revokes both the SELECT and INSERT privileges from john on the employees table.

Key Differences:
GRANT adds privileges, while REVOKE removes them.

GRANT is used to provide access, while REVOKE is used to restrict or remove access.

Asked in: S 19, W 16

Question: What is the difference between COMMIT, ROLLBACK, and SAVEPOINT? Explain with
examples.

The COMMIT, ROLLBACK, and SAVEPOINT commands are part of Transaction Control
Language (TCL) in SQL. These commands are used to manage database transactions,
ensuring that changes are either fully saved, undone, or partially saved, depending on the
situation.

1. COMMIT:
The COMMIT command is used to save all changes made during the current transaction. Once
a transaction is committed, all changes become permanent and are visible to other users.

Syntax for COMMIT:

sql

COMMIT;

Example:

Let's assume we are updating a record in the employees table.


Page 61 of 141
sql

UPDATE employees
SET salary = 6000
WHERE employee_id = 101;
COMMIT;

In this example, after the UPDATE statement, the COMMIT command is issued to save the
change. After committing, the salary update to the employee with employee_id = 101
becomes permanent, and this change is visible to other transactions.

2. ROLLBACK:
The ROLLBACK command is used to undo all changes made during the current transaction. If
a ROLLBACK is issued, all changes made since the last COMMIT or SAVEPOINT are discarded.
This is helpful in case of errors or if you want to cancel the transaction.

Syntax for ROLLBACK:

sql

ROLLBACK;

Example:

Suppose you update a record and then realize the update was incorrect. You can undo the
changes by using ROLLBACK.

sql

UPDATE employees
SET salary = 6000
WHERE employee_id = 101;
ROLLBACK;

In this example, after the UPDATE, we issue a ROLLBACK. This will undo the salary update for
employee_id = 101, and the original value will be restored.

3. SAVEPOINT:
The SAVEPOINT command allows you to set a point within a transaction that you can later
roll back to. It's useful when you want to partially undo a transaction, rolling back to a certain
point without undoing the entire transaction.

Syntax for SAVEPOINT:

sql

SAVEPOINT savepoint_name;

Example:

Let's assume you are performing multiple updates, and you want to set a point after one
update to be able to roll back to it if needed.

sql
Page 62 of 141

UPDATE employees
SET salary = 6000
WHERE employee_id = 101;
SAVEPOINT before_second_update;

UPDATE employees
SET salary = 7000
WHERE employee_id = 102;

Now, if you decide that the second update (for employee_id = 102) was incorrect, you can roll
back to the SAVEPOINT and undo just that update:

sql

ROLLBACK TO SAVEPOINT before_second_update;

After this, the first update (for employee_id = 101) remains, but the second update (for
employee_id = 102) is undone.

Key Differences:
COMMIT: Makes all changes permanent in the database and cannot be undone.

ROLLBACK: Undoes all changes made in the current transaction, effectively reverting to the
state before the last COMMIT or SAVEPOINT.

SAVEPOINT: Sets a specific point within a transaction to which you can later roll back,
allowing partial undoing of a transaction.

Here's the number "2" represented using special characters in a very bold style:

markdown

██████
██ ██
██
██████
██
██
████████

VIEWS

What is a view? Write the syntax for creating a view and explain the purpose
with an example.
Asked in: S16, S18, S19, W16, W17
Page 63 of 141

What is a View?
A view in SQL is a virtual table that is created based on the result of a SELECT query. It does
not store the data physically but dynamically fetches it from the underlying table(s) whenever
the view is queried. Views provide a way to simplify complex queries, enhance security, and
present data in a customized format.

Syntax for Creating a View


sql

CREATE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;

view_name: Name of the view.

SELECT column1, column2, ...: Specifies the columns to include in the view.

table_name: The name of the table(s) from which data will be fetched.

WHERE condition: (Optional) Filters the data included in the view.

Purpose of a View
1. Simplify Queries: Complex queries can be saved as a view, making it easier to use them
repeatedly.

2. Enhanced Security: Views allow restricting access to specific columns or rows.

3. Data Abstraction: Hides the complexity of the underlying database structure.

4. Customized Presentation: Displays data in a required format.

Example

Creating a View

Consider a STUDENT table:

STUDENT_ID NAME AGE DEPARTMENT GPA

1 Alice 20 Computer 3.8

2 Bob 21 Mathematics 3.2


Page 64 of 141

STUDENT_ID NAME AGE DEPARTMENT GPA

3 Charlie 22 Computer 3.5

4 Diana 20 Physics 3.9

Requirement: Create a view to display students from the Computer department only.

sql

CREATE VIEW Computer_Students AS


SELECT STUDENT_ID, NAME, GPA
FROM STUDENT
WHERE DEPARTMENT = 'Computer';

Using the View

sql

SELECT * FROM Computer_Students;

Result:

STUDENT_ID NAME GPA

1 Alice 3.8

3 Charlie 3.5

This view provides a simplified and filtered representation of the STUDENT table, showing
only relevant columns and rows.

Key Notes
Views can be queried like regular tables.

Any changes made to the underlying table are reflected in the view.

Views cannot include certain elements like ORDER BY unless enclosed in a subquery.

2. What are the advantages of views? Explain the objectives of creating


views.
Asked in: S19, W18

Advantages of Views
Page 65 of 141

1. Data Security:
Views restrict user access to specific columns or rows of a table, hiding sensitive
information.
Example: A view displaying employee names and departments without showing salaries.

2. Simplifies Complex Queries:


Complex SQL queries can be stored as views, making it easier to reuse them without
rewriting.
Example: Joining multiple tables to display combined results.

3. Data Abstraction:
Views hide the complexity of database schemas by presenting data in a simplified and
logical manner.
Example: Renaming columns for clarity in the view output.

4. Customized Data Presentation:


Allows presenting data tailored to user requirements (e.g., filtering, formatting).

5. Consistency:
Ensures consistent data representation by encapsulating common queries within a view.

Objectives of Creating Views


1. Enhancing Security: To control access and safeguard sensitive data.

2. Data Integration: To merge and organize data from multiple tables seamlessly.

3. Query Simplification: To reduce the effort of writing repetitive and complex queries.

4. Logical Independence: To provide independence from physical database schema changes.

Example

Table: EMPLOYEES

EMP_ID NAME DEPT_ID SALARY AGE

101 Alice 004 70000 30

102 Bob 004 50000 28

103 Charlie 035 65000 32

Create a View

sql

CREATE VIEW Employee_Details AS


SELECT NAME, DEPT_ID
Page 66 of 141

FROM EMPLOYEES;

View Output

NAME DEPT_ID

Alice 004

Bob 004

Charlie 035

This view restricts access to only names and departments, ensuring salary and age are not
exposed.

Should I solve the next question?

3. Explain different types of views (read-only and updatable views) with


examples.
Asked in: S19, W17, W19

Types of Views
1. Read-only Views

A read-only view is one where you cannot perform any DML (Data Manipulation
Language) operations like INSERT , UPDATE , or DELETE . These views only allow SELECT
queries.

Read-only views are typically created by joining multiple tables, aggregating data, or
applying complex transformations where updating is not allowed.

Example: If a view is based on a join of several tables or has aggregate functions like
SUM or COUNT , it becomes read-only.

Example

sql

CREATE VIEW Employee_Department AS


SELECT e.NAME, e.SALARY, d.DEPT_NAME
FROM EMPLOYEES e
JOIN DEPARTMENTS d ON e.DEPT_ID = d.DEPT_ID;
Page 67 of 141

In this case, Employee_Department is a read-only view because the data comes from
multiple tables and the view cannot be updated directly.

2. Updatable Views

An updatable view is one that allows INSERT , UPDATE , and DELETE operations,
provided the view is based on a single table and doesn't include complex expressions or
aggregates.

Updatable views can be used for modifying data without directly interacting with the
underlying table.

Example: If the view is a simple projection of a table with no joins or aggregations, it


remains updatable.

Example

sql

CREATE VIEW Simple_Employee AS


SELECT EMP_ID, NAME, SALARY
FROM EMPLOYEES;

Here, Simple_Employee is an updatable view since it's based on a single table, and you
can update the employee data through the view.

Key Differences

Read-only View Updatable View

Cannot perform INSERT , UPDATE , DELETE Supports INSERT , UPDATE , DELETE

Used for presenting data without altering it Used for interacting with underlying data

Typically involves joins or aggregations Based on a single table without joins

Should I solve the next question?

4. Write the syntax and example to drop a view.


Asked in: S18, W17

Dropping a View
Page 68 of 141

To remove a view from the database, we use the DROP VIEW statement. This command
deletes the view definition from the database. It does not affect the underlying tables; it only
removes the view itself.

Syntax
sql

DROP VIEW view_name;

view_name : The name of the view you want to drop.

Example
To drop the Employee_Department view that we created earlier, the SQL command would be:

sql

DROP VIEW Employee_Department;

This command deletes the Employee_Department view, and you can no longer use it to query
data.

Should I solve the next question?

5. Create a view to give access to limited information about employees in


specific departments:
Department No. 004

Department No. 50

Department No. 35

Employees who scored more than 60 marks in Computer Science

Years Asked: S16 (Dept. 004), S18 (Dept. 50), W16 (Dept. 35), W19 (60 marks in Computer
Science)

Creating a View for Limited Employee Information


In SQL, we can create a view that selects only the required data from one or more tables, and
restricts access based on conditions. The goal here is to create a view that will give limited
information about employees in specific departments and those who have scored more than
60 marks in Computer Science.

SQL Syntax to Create the View:


Page 69 of 141

sql

CREATE VIEW Employee_Limited_Info AS


SELECT employee_id, employee_name, department_no, marks_in_computer_science
FROM employees
WHERE department_no IN (004, 50, 35)
AND marks_in_computer_science > 60;

Explanation:
CREATE VIEW Employee_Limited_Info AS : This creates a new view called Employee_Limited_Info .

SELECT employee_id, employee_name, department_no, marks_in_computer_science : This selects

the columns we want to show in the view, which include the employee ID, name,
department number, and marks in Computer Science.

FROM employees : This specifies the table employees where the data is retrieved from.

WHERE department_no IN (004, 50, 35) : This condition limits the records to employees who

belong to departments 004, 50, and 35.

AND marks_in_computer_science > 60 : This condition further restricts the records to

employees who have scored more than 60 marks in Computer Science.

Result:
After executing the above command, a view will be created that contains employee
information (such as ID, name, department number, and marks in Computer Science) for
those in departments 004, 50, and 35, and only for employees who scored more than 60
marks in Computer Science.

Would you like to proceed with the next question?

6. Explain the restrictions/limitations of using DML statements (INSERT,


UPDATE, DELETE) on views.
Years Asked: S17

Restrictions/Limitations of Using DML Statements on Views:


When working with views in SQL, there are certain restrictions and limitations when
performing Data Manipulation Language (DML) operations like INSERT , UPDATE , and
DELETE . These restrictions arise due to the nature of views and how they interact with

underlying base tables.

1. Restrictions on INSERT Statement:


Page 70 of 141

Base Table Requirement: Views that are based on multiple tables (such as those that join
tables) typically do not allow INSERT operations. This is because the database system
cannot determine in which underlying table to insert the new data.

Updatable Views: For a view to be updatable and allow INSERT , it must directly map to
one table, and the view should not contain any aggregate functions ( SUM , COUNT , etc.),
group by clauses, or distinct clauses. If the view contains these, it cannot be used for
INSERT .

Example of Insert Operation on a View:

sql

INSERT INTO Employee_View (employee_id, employee_name)


VALUES (101, 'John Doe');

In this case, Employee_View should be a simple view based on a single table without any
complex joins or aggregate functions.

2. Restrictions on UPDATE Statement:

Updatable View Requirement: A view is only updatable if it directly maps to a single base
table. If the view is based on multiple tables, or if it involves aggregations or computations,
updates to the view may not be allowed.

Non-updatable Views: For views containing expressions, joins, or group functions (e.g.,
SUM ), UPDATE is generally not allowed because the database cannot map the update

operation back to the original base table(s).

Example of an Update Operation on a View:

sql

UPDATE Employee_View
SET employee_name = 'Jane Smith'
WHERE employee_id = 101;

If Employee_View is an updatable view based on a single table (such as employees ), this


query will work. However, if the view joins multiple tables, this might result in an error.

3. Restrictions on DELETE Statement:

Non-Deleteable Views: Views that contain aggregate functions, group by clauses, joins, or
subqueries typically cannot be used for DELETE operations. This is because the system
cannot determine which row in the base table should be deleted based on the view.

Updatable Views for DELETE : Just like INSERT and UPDATE , the view must map to a single
table for the DELETE operation to be allowed. If the view is based on multiple tables or
involves complex logic, it cannot be used to delete rows.

Example of Delete Operation on a View:

sql

DELETE FROM Employee_View


WHERE employee_id = 101;
Page 71 of 141

In this case, Employee_View must map to a single base table for the DELETE operation to
be successful.

Summary of Common Restrictions:

1. Single Table Views: Views that are based on a single table are more likely to support
INSERT , UPDATE , and DELETE .

2. Complex Views: Views that join multiple tables, contain aggregate functions, or have
computations usually do not support DML operations.

3. Read-Only Views: Some views are read-only and cannot be used for DML operations. These
views are typically used for querying purposes only.

Would you like to proceed with the next question?

7. What is a materialized view? Explain its purpose and advantages.


Years Asked: S16, S17, W18

Materialized View:
A materialized view is a database object that stores the result of a query as a physical table.
Unlike a regular view, which is virtual and dynamically computed when queried, a
materialized view stores the data and can be refreshed periodically to keep it in sync with the
underlying base tables. This helps in improving performance, particularly in data warehouses,
where querying large datasets repeatedly can be time-consuming.

Purpose of Materialized Views:

Performance Improvement: Materialized views are typically used to improve performance


for complex queries by storing the results of a frequently run query. Since the data is pre-
computed and stored, the query can be answered much faster when requested.

Data Aggregation: They are helpful when there is a need to aggregate large amounts of
data from one or more tables (e.g., summing, averaging, etc.) over a period of time. Instead
of recalculating aggregates each time, a materialized view can store these values.

Data Consistency: Materialized views ensure that users can access pre-computed data
rather than waiting for the database to process heavy queries, ensuring faster response
times and consistency.

How Materialized Views Work:

When a materialized view is created, it executes the query and stores the result as a table.

This stored data can be periodically refreshed to ensure it reflects changes in the base
tables.
Page 72 of 141

Refreshing can be done on-demand, or at specific intervals (e.g., every hour, every day).

Syntax for Creating a Materialized View:

sql

CREATE MATERIALIZED VIEW sales_summary


AS
SELECT product_id, SUM(sales) AS total_sales
FROM sales_data
GROUP BY product_id;

In this example, a materialized view called sales_summary is created, which stores the total
sales per product by summarizing data from the sales_data table. This will improve
performance when querying the sales summary data.

Advantages of Materialized Views:

1. Faster Query Performance: Since the results are pre-computed and stored, querying a
materialized view is much faster compared to re-executing complex queries over large
datasets.

2. Efficient Use of Resources: Materialized views can help reduce the load on the database by
offloading expensive operations like joins and aggregations, especially for frequently
accessed data.

3. Data Snapshot: Materialized views provide a snapshot of the data at a particular point in
time, which can be useful for reporting or historical analysis. This can be advantageous in
environments where real-time data access is not a strict requirement.

4. Improved Performance for OLAP Queries: Materialized views are highly useful in Online
Analytical Processing (OLAP) systems, where complex aggregation and summary
operations need to be performed frequently. The materialized view stores pre-aggregated
results, significantly improving the response time for such queries.

5. Reduces Complexity: Complex calculations or joins that need to be performed repeatedly


can be simplified by using materialized views. Users can simply query the materialized
view rather than performing the computations again and again.

Disadvantages of Materialized Views:

1. Storage Overhead: Since materialized views store data physically, they require storage
space. This might be an issue if there is limited storage capacity.

2. Refresh Overhead: Periodically refreshing materialized views can be resource-intensive,


especially if the base tables are large or there are multiple materialized views.

3. Data Freshness: Materialized views may not always contain the most up-to-date data
unless they are refreshed frequently. This can cause data staleness if the refresh is not done
in a timely manner.

Refreshing Materialized Views:

There are two types of refresh methods for materialized views:

Complete Refresh: The materialized view is completely rebuilt by re-executing the query.
This is useful when the base data has changed significantly.
Page 73 of 141

Fast Refresh: Only the changes (inserts, updates, deletes) to the base data are reflected in
the materialized view. This is more efficient than a complete refresh but requires
additional setup, such as maintaining logs of changes to the base tables.

Would you like to proceed with the next question?

PL/SQL Programming

8. Differentiate between SQL and PL/SQL programming.


Years Asked: S19, W17, W18

SQL (Structured Query Language) and PL/SQL (Procedural Language/SQL) are both
important languages in database management, but they serve different purposes.

SQL is a declarative language used for querying, updating, inserting, and deleting data in
databases. It is mainly used for retrieving and manipulating data, such as selecting rows or
updating records.

PL/SQL is an extension of SQL, designed to allow procedural programming inside SQL. It


supports control structures like loops, conditions, and variables, allowing you to write
complex logic and reusable code within the database.

Here are some differences:

1. Nature:

SQL is a declarative language. You tell the database what you want, and it figures out
how to do it.

PL/SQL is a procedural language. You tell the database what to do step by step.

2. Usage:

SQL is used for defining, manipulating, and querying data.

PL/SQL is used to write programs (like functions, procedures, and triggers) that perform
complex operations.

3. Control Structures:

SQL does not support loops, conditions, or variables.

PL/SQL supports loops, conditionals, variables, and exception handling.

4. Execution:

SQL is executed one query at a time.

PL/SQL allows multiple SQL statements to be grouped together and executed as a


block.

5. Error Handling:

SQL does not have built-in error handling.


Page 74 of 141

PL/SQL provides error handling using EXCEPTION blocks.

Would you like me to solve the next question?

9. Explain the structure of a PL/SQL block.


Years Asked: S16, S17

A PL/SQL block is the basic unit of code in PL/SQL. It consists of three main sections:

1. Declaration Section (optional):

This section is used to declare variables, constants, cursors, and types.

The declaration section is optional; if not used, you can skip it.

Variables declared here can be used in the execution section.

Syntax:
sql

DECLARE
variable_name datatype [DEFAULT value];

2. Execution Section (mandatory):

This section contains the executable statements, where the actual logic of the program
is written.

The execution section is mandatory, and it is the part where SQL statements (like
SELECT, INSERT, UPDATE, DELETE) and PL/SQL procedural statements (like loops,
conditionals, etc.) are written.

Syntax:
sql

BEGIN
-- executable statements
END;

3. Exception Handling Section (optional):

This section is used to handle any errors (exceptions) that occur during the execution of
the PL/SQL block.

If an error occurs, the control will be passed to the exception handling section where
specific actions can be defined.

Syntax:
sql

EXCEPTION
WHEN exception_name THEN
-- actions to handle the exception

Here is the structure of a PL/SQL block:


Page 75 of 141
sql

DECLARE
-- Declaration of variables
variable_name datatype;
BEGIN
-- Executable statements
-- SQL and PL/SQL statements here
EXCEPTION
-- Exception handling block
WHEN exception_name THEN
-- Handling actions
END;

This structure allows for flexibility in writing complex programs that include error handling
and procedural logic.

Would you like me to solve the next question?

10. Explain PL/SQL data types, identifiers, operators, and expressions.


Years Asked: S17

PL/SQL, like SQL, has its own set of data types, identifiers, operators, and expressions that are
used to write powerful and efficient code. Here's a breakdown of each component:

1. PL/SQL Data Types:


Data types in PL/SQL specify the type of data that can be stored in a variable or constant.
PL/SQL supports various data types including scalar, composite, reference, and large object
types.

Scalar Types: These are basic data types that store a single value.

NUMBER: Used for storing numeric values, such as integers or floating-point numbers.
Example: NUMBER(5,2) can store a number with up to 5 digits, 2 of which can be after
the decimal point.

CHAR: Stores fixed-length strings.


Example: CHAR(10) stores a string of exactly 10 characters.

VARCHAR2: Stores variable-length strings.


Example: VARCHAR2(50) can store strings up to 50 characters long.

DATE: Stores date and time values, including the year, month, day, hour, minute, and
second.

BOOLEAN: Stores a value of TRUE , FALSE , or NULL .

Composite Types: These include Records and Tables:

Records: Group together related data of different types (similar to structures in C).

Tables: Used to store a set of elements (records or variables).

LOB Types: Large Object data types like BLOB , CLOB , BFILE , used to store large amounts
of data, such as images, videos, and text files.
Page 76 of 141

2. PL/SQL Identifiers:
Identifiers are names used to identify variables, constants, subprograms, cursors, exceptions,
and other programmatic elements in PL/SQL.

Naming Rules for Identifiers:

They must begin with a letter.

They can contain letters, digits, and underscores (_).

They should not exceed 30 characters in length.

They must not be Oracle reserved keywords (like SELECT , INSERT , etc.).

Example:

sql

DECLARE
emp_name VARCHAR2(50);
BEGIN
emp_name := 'John Doe';
END;

3. PL/SQL Operators:
Operators are used to perform operations on variables and values. PL/SQL supports several
types of operators:

Arithmetic Operators: Used for mathematical calculations.

+ , - , * , / , % (modulo)

Example:
sql

result := 10 + 5; -- Adds 10 and 5

Comparison Operators: Used to compare two values.

= , != , < , > , <= , >= , BETWEEN , LIKE , IN

Example:
sql

IF salary > 10000 THEN


-- Perform action
END IF;

Logical Operators: Used to combine multiple conditions.

AND , OR , NOT

Example:
sql

IF age > 18 AND age < 65 THEN


-- Perform action
Page 77 of 141

END IF;

4. PL/SQL Expressions:
Expressions are combinations of variables, constants, operators, and function calls that
produce a single value.

Simple Expression: A single value or variable. Example:

sql

salary := 50000; -- Simple assignment

Complex Expression: A combination of literals, variables, operators, and functions.


Example:

sql

total_salary := basic_salary + (bonus * 0.1);

Expressions can be used to assign values to variables or as conditions in IF statements, LOOP


constructs, and other control structures.

By understanding and utilizing PL/SQL's data types, identifiers, operators, and expressions,
you can write efficient and effective programs that interact with the database and perform
various tasks.

Would you like to move on to the next question?

Iterative and Conditional Statements

Asked in: S17, W16, W19

Question: Explain iterative statements (FOR, WHILE, LOOP) in PL/SQL with examples.

In PL/SQL, iterative statements allow you to repeatedly execute a block of code. The three
types of iterative statements in PL/SQL are:

1. FOR Loop: The FOR loop is used when you know the number of iterations in advance. It
runs for a specific number of times, starting from the initial value to the final value.

Syntax:

plsql

FOR counter IN [REVERSE] start_value..end_value LOOP


-- statements
END LOOP;
Page 78 of 141

Example:

plsql

DECLARE
i NUMBER;
BEGIN
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Value of i: ' || i);
END LOOP;
END;

In this example, the loop will iterate 5 times, printing values from 1 to 5.

2. WHILE Loop: The WHILE loop is used when the number of iterations is not known initially.
It continues executing as long as the condition remains true.

Syntax:

plsql

WHILE condition LOOP


-- statements
END LOOP;

Example:

plsql

DECLARE
i NUMBER := 1;
BEGIN
WHILE i <= 5 LOOP
DBMS_OUTPUT.PUT_LINE('Value of i: ' || i);
i := i + 1;
END LOOP;
END;

In this example, the WHILE loop will continue until the value of i exceeds 5.

3. LOOP: The LOOP is an unconditional loop. It will repeat the code block infinitely unless
there is an exit condition specified.

Syntax:

plsql

LOOP
-- statements
EXIT WHEN condition;
END LOOP;

Example:

plsql
Page 79 of 141

DECLARE
i NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Value of i: ' || i);
i := i + 1;
EXIT WHEN i > 5;
END LOOP;
END;

In this example, the LOOP will continue to run until i becomes greater than 5.

Let me know if you'd like me to continue with the next question!

Asked in: S16, S18, S19, W18

Question: Explain the CASE statement in Oracle with a suitable example.

The CASE statement in Oracle is used to evaluate a series of conditions and return a result
based on the first condition that is true. It allows conditional logic within SQL queries and
PL/SQL blocks.

There are two types of CASE statements in Oracle:

1. Simple CASE Expression

2. Searched CASE Expression

1. Simple CASE Expression:


The simple CASE expression compares an expression to a series of values and returns a result
when it finds a match.

Syntax:

sql

CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
...
ELSE result
END;

Example:

sql

SELECT employee_id, salary,


CASE department_id
WHEN 10 THEN 'Accounting'
WHEN 20 THEN 'Research'
WHEN 30 THEN 'HR'
ELSE 'Other'
Page 80 of 141

END AS department_name
FROM employees;

In this example, the CASE statement checks the department_id and returns the
corresponding department name. If no match is found, it returns 'Other'.

2. Searched CASE Expression:


The searched CASE expression allows multiple conditions to be tested, rather than matching
a single expression to values.

Syntax:

sql

CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE result
END;

Example:

sql

SELECT employee_id, salary,


CASE
WHEN salary < 3000 THEN 'Low'
WHEN salary BETWEEN 3000 AND 7000 THEN 'Medium'
WHEN salary > 7000 THEN 'High'
ELSE 'Not Available'
END AS salary_level
FROM employees;

In this example, the CASE statement evaluates the salary and returns 'Low', 'Medium', or
'High' based on the salary value. If no match is found, it returns 'Not Available'.

Let me know if you'd like me to continue with the next question!

Asked in: S17

Question: List and explain conditional statements in PL/SQL with examples.

In PL/SQL, conditional statements are used to make decisions based on certain conditions.
These statements allow the execution of different code depending on whether a condition is
true or false. There are several types of conditional statements in PL/SQL:

1. IF-THEN Statement
The simplest conditional statement in PL/SQL, where a block of code is executed if a
condition is true.

Syntax:

plsql
Page 81 of 141

IF condition THEN
-- statements to execute
END IF;

Example:

plsql

DECLARE
salary NUMBER := 5000;
BEGIN
IF salary > 3000 THEN
DBMS_OUTPUT.PUT_LINE('Salary is above 3000');
END IF;
END;

In this example, the IF statement checks if the salary is greater than 3000 and prints a
message if true.

2. IF-THEN-ELSE Statement
This conditional statement provides an alternative set of statements if the condition is false.

Syntax:

plsql

IF condition THEN
-- statements to execute if true
ELSE
-- statements to execute if false
END IF;

Example:

plsql

DECLARE
salary NUMBER := 2500;
BEGIN
IF salary > 3000 THEN
DBMS_OUTPUT.PUT_LINE('Salary is above 3000');
ELSE
DBMS_OUTPUT.PUT_LINE('Salary is below or equal to 3000');
END IF;
END;

In this example, if the salary is greater than 3000, it prints "Salary is above 3000". Otherwise,
it prints "Salary is below or equal to 3000".

3. IF-THEN-ELSIF Statement
This statement allows for multiple conditions to be evaluated sequentially.

Syntax:
Page 82 of 141

plsql

IF condition1 THEN
-- statements to execute if condition1 is true
ELSIF condition2 THEN
-- statements to execute if condition2 is true
ELSIF condition3 THEN
-- statements to execute if condition3 is true
ELSE
-- statements to execute if all conditions are false
END IF;

Example:

plsql

DECLARE
salary NUMBER := 4500;
BEGIN
IF salary > 7000 THEN
DBMS_OUTPUT.PUT_LINE('Salary is High');
ELSIF salary > 3000 THEN
DBMS_OUTPUT.PUT_LINE('Salary is Medium');
ELSE
DBMS_OUTPUT.PUT_LINE('Salary is Low');
END IF;
END;

Here, the PL/SQL block checks the salary and prints the appropriate message based on
whether it is high, medium, or low.

4. CASE Statement
The CASE statement is a more advanced conditional statement, which works similarly to an
IF-THEN-ELSEIF chain but is more compact and readable when there are multiple conditions

to evaluate.

Syntax:

plsql

CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result3
END CASE;

Example:

plsql

DECLARE
grade CHAR := 'B';
BEGIN
CASE grade
Page 83 of 141

WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent');


WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('Good');
WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('Average');
ELSE DBMS_OUTPUT.PUT_LINE('Poor');
END CASE;
END;

This example evaluates the grade and prints the corresponding message.

These are the main conditional statements in PL/SQL. They provide flexibility and control
over how code is executed based on conditions.

Let me know if you would like me to continue with the next question!

Problem-Solving in PL/SQL

14. Write a PL/SQL block to decide the larger of two numbers.

Years Asked: S17

To solve this, you can use an IF-ELSE condition to compare two numbers and display the
larger one.

Here is the PL/SQL block for that:

plsql

DECLARE
num1 NUMBER := 10; -- First number
num2 NUMBER := 20; -- Second number
largest NUMBER;
BEGIN
IF num1 > num2 THEN
largest := num1;
ELSE
largest := num2;
END IF;

DBMS_OUTPUT.PUT_LINE('The larger number is: ' || largest);


END;

Explanation:

We declare two numbers num1 and num2 .

Then, we use an IF statement to compare both numbers.

The larger number is stored in the variable largest .

Finally, the result is displayed using DBMS_OUTPUT.PUT_LINE .

Should I move on to the next question?

15. Write a PL/SQL block to swap the contents of two variables.


Page 84 of 141

Years Asked: S19, W17

To swap the values of two variables, we can use a temporary variable to hold one of the
values during the swap process. Here's a PL/SQL block to do that:

plsql

DECLARE
var1 NUMBER := 5; -- First variable
var2 NUMBER := 10; -- Second variable
temp NUMBER; -- Temporary variable for swapping
BEGIN
-- Display original values
DBMS_OUTPUT.PUT_LINE('Before swap: var1 = ' || var1 || ', var2 = ' || var2);

-- Swap logic
temp := var1;
var1 := var2;
var2 := temp;

-- Display swapped values


DBMS_OUTPUT.PUT_LINE('After swap: var1 = ' || var1 || ', var2 = ' || var2);
END;

Explanation:

We declare two variables var1 and var2 with initial values.

A temporary variable temp is used to hold the value of var1 while we assign var2 to
var1 .

Then, var2 is assigned the value of temp , effectively swapping their values.

The DBMS_OUTPUT.PUT_LINE function is used to display the values before and after the
swap.

Should I move on to the next question?

16. Write a PL/SQL program to find the factorial of a given number N using a FOR loop.

Years Asked: S18

To calculate the factorial of a given number, we can use a FOR loop to multiply the numbers
from 1 to N. Here's the PL/SQL program to compute the factorial:

plsql

DECLARE
N NUMBER := 5; -- Input number
factorial NUMBER := 1; -- Variable to store factorial result
BEGIN
-- Using a FOR loop to calculate factorial
FOR i IN 1..N LOOP
factorial := factorial * i;
END LOOP;
Page 85 of 141

-- Display the result


DBMS_OUTPUT.PUT_LINE('The factorial of ' || N || ' is: ' || factorial);
END;

Explanation:

We declare a variable N with the number for which we need to find the factorial and a
factorial variable initialized to 1.

A FOR loop iterates through all integers from 1 to N and multiplies them to calculate the
factorial.

The result is printed using DBMS_OUTPUT.PUT_LINE .

Would you like to proceed to the next question?


Page 86 of 141

17. Write a PL/SQL program to find the largest of three numbers.

Years Asked: W18

Here's a PL/SQL program that takes three numbers as input and finds the largest one:

plsql

DECLARE
num1 NUMBER := 10; -- First number
num2 NUMBER := 20; -- Second number
num3 NUMBER := 15; -- Third number
largest NUMBER; -- Variable to store the largest number
BEGIN
-- Using IF-ELSE to find the largest number
IF (num1 >= num2) AND (num1 >= num3) THEN
largest := num1;
ELSIF (num2 >= num1) AND (num2 >= num3) THEN
largest := num2;
ELSE
largest := num3;
END IF;

-- Display the largest number


DBMS_OUTPUT.PUT_LINE('The largest number is: ' || largest);
END;

Explanation:

Three variables num1 , num2 , and num3 are initialized with the values of the three
numbers.

The IF-ELSE condition checks which number is the largest among the three and assigns it
to the largest variable.

The largest number is then printed using DBMS_OUTPUT.PUT_LINE .

Would you like to proceed to the next question?

18. Write a PL/SQL program to find the sum of the digits of a given number.

Years Asked: W16

Here's a PL/SQL program that calculates the sum of the digits of a given number:

plsql

DECLARE
num NUMBER := 1234; -- Given number
digit NUMBER; -- Variable to store individual digits
sum_of_digits NUMBER := 0; -- Variable to store the sum of digits
BEGIN
-- Loop through the digits of the number
WHILE num > 0 LOOP
digit := mod(num, 10); -- Extract the last digit
Page 87 of 141

sum_of_digits := sum_of_digits + digit; -- Add the digit to the sum


num := num / 10; -- Remove the last digit
END LOOP;

-- Display the sum of digits


DBMS_OUTPUT.PUT_LINE('The sum of the digits is: ' || sum_of_digits);
END;

Explanation:

The program uses a WHILE loop to repeatedly extract the last digit of the number using
the MOD function and add it to the sum.

After extracting a digit, the number is divided by 10 to remove the last digit, and this
process continues until the number becomes 0.

The sum of digits is displayed using DBMS_OUTPUT.PUT_LINE .

Would you like to continue to the next question?

19. Write a PL/SQL program to check whether a given number is even or odd.

Years Asked: W19

Here's a PL/SQL program that checks whether a given number is even or odd:

plsql

DECLARE
num NUMBER := 25; -- Given number
BEGIN
-- Check if the number is even or odd
IF MOD(num, 2) = 0 THEN
DBMS_OUTPUT.PUT_LINE('The number ' || num || ' is Even.');
ELSE
DBMS_OUTPUT.PUT_LINE('The number ' || num || ' is Odd.');
END IF;
END;

Explanation:

The program checks whether the number is even or odd using the MOD function.

If the remainder of dividing the number by 2 ( MOD(num, 2) ) is 0, the number is even.


Otherwise, it is odd.

The result is displayed using DBMS_OUTPUT.PUT_LINE .

Let me know if you'd like to move on to the next question!


Page 88 of 141

plaintext

𝗧𝗛𝗥𝗘𝗘

Exception Handling: Predefined Exceptions, User Defined Exceptions

1. What are exceptions? Write a short note on ‘User defined exceptions'.


Year asked: S16, W16, S18, S19

Exceptions in PL/SQL are run-time errors that occur during the execution of a program. When
an exception occurs, the normal flow of execution is interrupted, and PL/SQL handles the
error in a predefined way. Exceptions are categorized into two types: predefined exceptions
and user-defined exceptions.

User-defined exceptions are exceptions that are created by the programmer to handle
specific errors that are not already covered by predefined exceptions in PL/SQL. These
exceptions allow the programmer to handle errors that arise due to application-specific
conditions or business logic.

To create a user-defined exception, we can declare an exception in the declaration section of


a PL/SQL block and then raise it when necessary using the RAISE statement.

Syntax for user-defined exception:


sql

DECLARE
-- Declare the user-defined exception
my_exception EXCEPTION;
BEGIN
-- Trigger the exception condition
IF some_condition THEN
RAISE my_exception;
END IF;
EXCEPTION
-- Handle the user-defined exception
WHEN my_exception THEN
DBMS_OUTPUT.PUT_LINE('Custom exception triggered');
END;

In this example:

my_exception is a user-defined exception.

The exception is raised with the RAISE keyword when a specific condition occurs.

The exception is caught in the EXCEPTION block, and the custom message is displayed.

Should I move on to the next question?


Page 89 of 141

2. What is a predefined exception? Explain the ZERO DIVIDE exception.


Year asked: S16, S17, W16

A predefined exception in PL/SQL is a set of exceptions that Oracle provides to handle


common errors automatically. These exceptions are pre-coded and recognized by PL/SQL, so
developers do not need to define them manually. They help in handling specific error
conditions that occur during the execution of SQL statements or PL/SQL blocks.

One of the predefined exceptions is ZERO_DIVIDE, which occurs when a division by zero is
attempted in PL/SQL. This exception is triggered when the divisor in a division operation
equals zero.

Example:
sql

DECLARE
num1 NUMBER := 10;
num2 NUMBER := 0;
result NUMBER;
BEGIN
result := num1 / num2;
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Error: Division by zero');
END;

In this example:

A division by zero is attempted with num2 = 0 .

The ZERO_DIVIDE exception is raised automatically, and the error message "Error: Division
by zero" is displayed.

Should I continue with the next question?

3. Explain the following predefined exceptions: (i) DUP_VAL_ON_INDEX


(ii) NO_DATA_FOUND
(iii) ZERO_DIVIDE
(iv) VALUE_ERROR
(v) INVALID_NUMBER

Year asked: W16

(i) DUP_VAL_ON_INDEX:
This exception occurs when an attempt is made to insert or update a row in a table, but it
violates a unique constraint or index. Essentially, if you try to insert a duplicate value into a
column that has a unique constraint or a primary key, the DUP_VAL_ON_INDEX exception will
be raised.

Example:

sql
Page 90 of 141

DECLARE
v_emp_id NUMBER := 101;
BEGIN
INSERT INTO employees (emp_id, name) VALUES (v_emp_id, 'John Doe');
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('Error: Duplicate value in unique column');
END;

In this example, if an attempt is made to insert an employee with an emp_id that already
exists in the table, the DUP_VAL_ON_INDEX exception is triggered.

(ii) NO_DATA_FOUND:
This exception occurs when a SELECT INTO statement does not return any rows. It is raised if
a query returns no data when attempting to assign the result to a variable.

Example:

sql

DECLARE
v_employee_name VARCHAR2(50);
BEGIN
SELECT name INTO v_employee_name FROM employees WHERE emp_id = 999;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Error: No data found for the specified ID');
END;

In this example, if no employee is found with emp_id = 999 , the NO_DATA_FOUND exception
will be raised.

(iii) ZERO_DIVIDE:
This exception occurs when there is an attempt to divide a number by zero. It is automatically
raised by PL/SQL if the divisor in a division operation is zero.

(iv) VALUE_ERROR:
This exception is raised when there is an attempt to assign a value that is incompatible with
the variable's data type. It usually occurs when trying to assign a value to a variable that
exceeds its defined size or when the data types do not match.
Page 91 of 141

Example:

sql

DECLARE
v_number VARCHAR2(5);
BEGIN
v_number := '123456'; -- This value exceeds the declared size
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Error: Value exceeds variable size');
END;

In this example, the value '123456' exceeds the length of v_number , which is defined to hold
only 5 characters. Therefore, the VALUE_ERROR exception is raised.

(v) INVALID_NUMBER:
This exception occurs when there is an attempt to convert a string to a number, and the string
does not represent a valid number.

Example:

sql

DECLARE
v_value VARCHAR2(10) := 'abc123';
v_number NUMBER;
BEGIN
v_number := TO_NUMBER(v_value); -- Invalid conversion
EXCEPTION
WHEN INVALID_NUMBER THEN
DBMS_OUTPUT.PUT_LINE('Error: Invalid number format');
END;

In this example, the string 'abc123' cannot be converted to a number, so the


INVALID_NUMBER exception is raised.

Should I continue with the next question?

4. What is exception? Explain any four predefined exceptions supported by PL/SQL.

Year asked: S17, W19

What is an Exception?
Page 92 of 141

An exception in PL/SQL is an error or unexpected event that occurs during the execution of a
program. It represents a problem or an unusual situation that disrupts the normal flow of the
program. When an exception occurs, PL/SQL stops executing the current block of code and
starts executing the code in the exception-handling section, if available. Exceptions can be
predefined (automatically raised by the system) or user-defined (raised by the programmer).

Four Predefined Exceptions in PL/SQL:

1. ZERO_DIVIDE:

The ZERO_DIVIDE exception occurs when a division by zero is attempted in an expression. In


arithmetic operations, if the denominator is zero, this exception is raised.

Example:

sql

DECLARE
v_num1 NUMBER := 10;
v_num2 NUMBER := 0;
v_result NUMBER;
BEGIN
v_result := v_num1 / v_num2; -- Division by zero
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Error: Cannot divide by zero');
END;

In this example, attempting to divide by zero triggers the ZERO_DIVIDE exception.

2. NO_DATA_FOUND:

This exception occurs when a SELECT INTO statement does not return any rows. If a query
that is expected to return exactly one row returns nothing, the NO_DATA_FOUND exception is
triggered.

Example:

sql

DECLARE
v_employee_name VARCHAR2(50);
BEGIN
SELECT name INTO v_employee_name FROM employees WHERE emp_id = 999; -- No
employee with ID 999
EXCEPTION
WHEN NO_DATA_FOUND THEN
Page 93 of 141

DBMS_OUTPUT.PUT_LINE('Error: No employee found with this ID');


END;

Here, the query does not return any data because emp_id = 999 does not exist in the
employees table, so the NO_DATA_FOUND exception is raised.

3. DUP_VAL_ON_INDEX:

This exception occurs when an attempt is made to insert or update a value that violates a
unique constraint or primary key constraint. For example, trying to insert a duplicate value
into a column that requires uniqueness.

Example:

sql

DECLARE
v_emp_id NUMBER := 101;
BEGIN
INSERT INTO employees (emp_id, name) VALUES (v_emp_id, 'John Doe'); -- Duplicate
primary key value
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('Error: Duplicate value in primary key column');
END;

In this example, if the emp_id value already exists in the table, the DUP_VAL_ON_INDEX
exception is triggered.

4. VALUE_ERROR:

The VALUE_ERROR exception is raised when there is a mismatch between the data type of a
variable and the value being assigned to it. For instance, assigning a string to a numeric
variable or exceeding the size of the defined data type.

Example:

sql

DECLARE
v_number NUMBER;
BEGIN
v_number := 'abc'; -- Invalid value for a number variable
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Error: Value is not compatible with the variable data
type');
END;
Page 94 of 141

Here, trying to assign the string 'abc' to a numeric variable v_number triggers the
VALUE_ERROR exception.

Should I continue with the next question?

5. What is exception? Explain user defined exception with example.

Year asked: S18, W18

What is an Exception?
An exception is an error that occurs during the execution of a program in PL/SQL. When
something unexpected happens, like a division by zero or an invalid operation, an exception
is triggered. PL/SQL can handle exceptions using predefined exceptions (which are built-in) or
user-defined exceptions (which are created by the programmer). Exception handling in
PL/SQL allows the program to detect these errors and respond to them gracefully, ensuring
that the program doesn't stop abruptly.

User Defined Exception:


A user-defined exception is one that is created explicitly by the programmer to handle
specific errors or situations that are not covered by the predefined exceptions. It allows more
flexibility in handling custom situations based on the logic of the application.

Steps to define a user-defined exception:

1. Declare an exception.

2. Raise the exception when a certain condition is met.

3. Handle the exception using an exception-handling block.

Example of User-Defined Exception:


Let's say we need to raise an exception when a student's grade is below a certain threshold
(e.g., 40).

Syntax to create and use a user-defined exception:

sql

DECLARE
-- Declare a user-defined exception
grade_below_threshold EXCEPTION;
Page 95 of 141

-- Declare variables
v_grade NUMBER := 30; -- Example grade value
BEGIN
-- Check if grade is below threshold
IF v_grade < 40 THEN
-- Raise the exception if the grade is below 40
RAISE grade_below_threshold;
END IF;

EXCEPTION
-- Handle the user-defined exception
WHEN grade_below_threshold THEN
DBMS_OUTPUT.PUT_LINE('Error: Student grade is below the threshold');
END;

Explanation:
1. Declaration of User-Defined Exception:

grade_below_threshold EXCEPTION; declares the exception.

2. Condition and Raising the Exception:

The IF statement checks if the grade is below 40. If true, the RAISE
grade_below_threshold; statement raises the exception.

3. Handling the Exception:

The EXCEPTION block catches the grade_below_threshold exception and prints the error
message "Error: Student grade is below the threshold".

In this example, a custom exception is created to check if a student's grade falls below the
threshold. If the condition is met, the exception is raised and handled.

Shall I proceed with the next question?

Cursors: Declaring Cursors, Opening and Retrieving Records, Closing Cursors

1. What is a cursor? Explain Attributes of Explicit Cursor.


Year asked: S16

A cursor in SQL is a pointer that helps manage the context of rows processed by a query. It
allows you to retrieve and manipulate data row by row. There are two main types of cursors
in SQL: implicit cursors and explicit cursors. An explicit cursor is one that is declared and
controlled by the programmer.
Page 96 of 141

Attributes of Explicit Cursor:

1. %FOUND: Returns TRUE if the cursor has fetched at least one row, otherwise, it returns
FALSE.

2. %NOTFOUND: Opposite of %FOUND. It returns TRUE if no rows have been fetched.

3. %ROWCOUNT: Returns the number of rows fetched so far by the cursor.

4. %ISOPEN: Returns TRUE if the cursor is open, and FALSE if it is closed.

To explain these attributes, here's a simple example:

plsql

DECLARE
CURSOR emp_cursor IS
SELECT emp_id, emp_name FROM employees;
emp_record emp_cursor%ROWTYPE;
BEGIN
OPEN emp_cursor;
FETCH emp_cursor INTO emp_record;
IF emp_cursor%FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee Found: ' || emp_record.emp_name);
END IF;
CLOSE emp_cursor;
END;

In this example:

%FOUND checks if a record has been fetched.

%ROWCOUNT would show how many records were processed.

%ISOPEN could be used to check the cursor status.

Would you like me to move on to the next question?

2. What is cursor? Explain different types of cursors.


Year asked: S18, W16, S19

A cursor is a mechanism in SQL that allows row-by-row processing of a result set. While SQL
works with entire sets of data at once, sometimes it's necessary to process each row
individually. Cursors help achieve this by maintaining a pointer to the current row in the
result set.

There are two types of cursors:

1. Implicit Cursor:

An implicit cursor is automatically created by Oracle for every SQL DML (Data
Manipulation Language) statement such as INSERT , UPDATE , DELETE , and SELECT
INTO .

You do not need to explicitly declare an implicit cursor. It is handled by Oracle


automatically.
Page 97 of 141

Example: When you execute a query like SELECT * FROM employees; , Oracle creates an
implicit cursor behind the scenes.

2. Explicit Cursor:

An explicit cursor is defined by the programmer. It provides more control over the query
execution and allows row-by-row processing.

You declare, open, fetch, and close an explicit cursor.

Example:
plsql

DECLARE
CURSOR emp_cursor IS
SELECT emp_id, emp_name FROM employees;
emp_record emp_cursor%ROWTYPE;
BEGIN
OPEN emp_cursor;
FETCH emp_cursor INTO emp_record;
CLOSE emp_cursor;
END;

Difference between Implicit and Explicit Cursors:

Implicit Cursor: Automatically created for SQL statements. Cannot be controlled directly.
Works for single-row operations.

Explicit Cursor: Manually defined and controlled. Allows more detailed processing,
including row-by-row handling.

Would you like me to continue to the next question?

3. Differentiate between implicit cursor and explicit cursor.


Year asked: S19

The main difference between implicit and explicit cursors lies in how they are defined and
controlled in PL/SQL. Here's a detailed comparison:

Implicit Cursor:
Definition: Implicit cursors are automatically created by Oracle when you execute a DML
(Data Manipulation Language) statement like SELECT INTO , INSERT , UPDATE , or DELETE .

Usage: Used for single-row SQL queries and simple DML operations where you do not need
to manually manage cursor handling.

Control: You do not have direct control over an implicit cursor. Oracle automatically
handles the opening, fetching, and closing of the cursor.

Declaration: No need for explicit declaration in your PL/SQL code.

Example:

plsql
Page 98 of 141

DECLARE
v_emp_id employees.emp_id%TYPE;
BEGIN
SELECT emp_id INTO v_emp_id FROM employees WHERE emp_name = 'John';
END;

Oracle automatically creates and manages an implicit cursor behind the scenes.

Explicit Cursor:
Definition: Explicit cursors are manually declared by the programmer for SQL queries that
return more than one row or when you need row-by-row processing.

Usage: Used for queries that return multiple rows, where the programmer needs more
control over the cursor operations.

Control: You have complete control over explicit cursors. You explicitly open, fetch, and
close the cursor.

Declaration: Must be explicitly declared in your PL/SQL block before using it.

Example:

plsql

DECLARE
CURSOR emp_cursor IS
SELECT emp_id, emp_name FROM employees;
v_emp_id employees.emp_id%TYPE;
v_emp_name employees.emp_name%TYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO v_emp_id, v_emp_name;
EXIT WHEN emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Emp ID: ' || v_emp_id || ' Emp Name: ' || v_emp_name);
END LOOP;
CLOSE emp_cursor;
END;

In this example, the cursor is explicitly declared and controlled.

Summary of Differences:

Implicit Cursor: Automatically created by Oracle, less control.

Explicit Cursor: Manually declared and controlled by the programmer, more control.

Would you like to proceed to the next question?

4. Write a PL/SQL block that uses the cursor to increment the salary by Rs. 2,500 of the
employees having department number 101.
Year asked: S16
Page 99 of 141

Here's a detailed PL/SQL block that uses an explicit cursor to increment the salary of
employees in department number 101 by Rs. 2,500:

plsql

DECLARE
-- Declare a cursor to fetch employees in department 101
CURSOR emp_cursor IS
SELECT emp_id, salary
FROM employees
WHERE department_id = 101;

-- Declare variables to hold the employee details


v_emp_id employees.emp_id%TYPE;
v_salary employees.salary%TYPE;
BEGIN
-- Open the cursor to fetch the employees
OPEN emp_cursor;

-- Loop through the records


LOOP
FETCH emp_cursor INTO v_emp_id, v_salary; -- Fetch employee id and salary
EXIT WHEN emp_cursor%NOTFOUND; -- Exit when no more records are found

-- Increment the salary by Rs. 2,500


UPDATE employees
SET salary = v_salary + 2500
WHERE emp_id = v_emp_id;

-- Output the updated salary for the employee


DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_emp_id || ' updated salary: ' ||
(v_salary + 2500));
END LOOP;

-- Close the cursor after the loop ends


CLOSE emp_cursor;

-- Commit the changes to the database


COMMIT;
END;

Explanation:
1. Cursor Declaration: The cursor emp_cursor is defined to fetch emp_id and salary of
employees working in department 101.

2. Variable Declaration: The variables v_emp_id and v_salary are declared to store employee
details.

3. Cursor Operations:

The cursor is opened using OPEN emp_cursor .

The FETCH statement retrieves each employee's ID and salary.

The UPDATE statement increments the salary by Rs. 2,500.


Page 100 of 141

The DBMS_OUTPUT.PUT_LINE displays the updated salary for each employee.

4. Loop and Exit Condition: The loop continues to fetch records until the cursor has no more
records ( %NOTFOUND ).

5. Commit: After all records are updated, a COMMIT is issued to save the changes.

Would you like to move on to the next question?

5. Write a PL/SQL block that uses the cursor to add special allowances of Rs. 1,000 to the total
salary of the employees of department number 100.
Year asked: S18

Here's a PL/SQL block that uses an explicit cursor to add Rs. 1,000 as special allowances to
the total salary of employees in department number 100:

plsql

DECLARE
-- Declare a cursor to fetch employees in department 100
CURSOR emp_cursor IS
SELECT emp_id, salary
FROM employees
WHERE department_id = 100;

-- Declare variables to hold the employee details


v_emp_id employees.emp_id%TYPE;
v_salary employees.salary%TYPE;
BEGIN
-- Open the cursor to fetch the employees
OPEN emp_cursor;

-- Loop through the records


LOOP
FETCH emp_cursor INTO v_emp_id, v_salary; -- Fetch employee id and salary
EXIT WHEN emp_cursor%NOTFOUND; -- Exit when no more records are found

-- Add special allowances of Rs. 1,000 to the salary


UPDATE employees
SET salary = v_salary + 1000
WHERE emp_id = v_emp_id;

-- Output the updated salary for the employee


DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_emp_id || ' updated salary: ' ||
(v_salary + 1000));
END LOOP;

-- Close the cursor after the loop ends


CLOSE emp_cursor;

-- Commit the changes to the database


COMMIT;
END;
Page 101 of 141

Explanation:
1. Cursor Declaration: The cursor emp_cursor is defined to fetch emp_id and salary for
employees working in department 100.

2. Variable Declaration: The variables v_emp_id and v_salary are used to store employee
information.

3. Cursor Operations:

The cursor is opened with the OPEN emp_cursor statement.

The FETCH statement retrieves each employee's ID and salary.

The UPDATE statement adds Rs. 1,000 as special allowances to the current salary.

The DBMS_OUTPUT.PUT_LINE prints the updated salary for each employee.

4. Loop and Exit Condition: The loop continues to fetch records until there are no more
records to fetch ( %NOTFOUND ).

5. Commit: A COMMIT is executed to apply the changes permanently.

Would you like to move on to the next question?

6. Write a PL/SQL block that uses the cursor to subtract Rs. 500 from the total salary of the
employees having department number 20.
Year asked: W18

Here's a PL/SQL block that uses an explicit cursor to subtract Rs. 500 from the total salary of
employees in department number 20:

plsql

DECLARE
-- Declare a cursor to fetch employees in department 20
CURSOR emp_cursor IS
SELECT emp_id, salary
FROM employees
WHERE department_id = 20;

-- Declare variables to hold the employee details


v_emp_id employees.emp_id%TYPE;
v_salary employees.salary%TYPE;
BEGIN
-- Open the cursor to fetch the employees
OPEN emp_cursor;

-- Loop through the records


LOOP
FETCH emp_cursor INTO v_emp_id, v_salary; -- Fetch employee id and salary
EXIT WHEN emp_cursor%NOTFOUND; -- Exit when no more records are found

-- Subtract Rs. 500 from the salary


UPDATE employees
SET salary = v_salary - 500
Page 102 of 141

WHERE emp_id = v_emp_id;

-- Output the updated salary for the employee


DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_emp_id || ' updated salary: ' ||
(v_salary - 500));
END LOOP;

-- Close the cursor after the loop ends


CLOSE emp_cursor;

-- Commit the changes to the database


COMMIT;
END;

Explanation:
1. Cursor Declaration: The cursor emp_cursor is defined to fetch emp_id and salary for
employees working in department 20.

2. Variable Declaration: The variables v_emp_id and v_salary store the employee information.

3. Cursor Operations:

The cursor is opened with OPEN emp_cursor .

The FETCH statement retrieves each employee's ID and salary.

The UPDATE statement subtracts Rs. 500 from the employee's salary.

The DBMS_OUTPUT.PUT_LINE prints the updated salary for each employee.

4. Loop and Exit Condition: The loop continues until all records have been processed.

5. Commit: A COMMIT is issued to apply the changes to the database permanently.

Would you like to move on to the next question?

7. Write a PL/SQL block that uses the cursor to increment the salary by Rs. 1,500 of the
employees having department number 30.
Year asked: W19

Here's a PL/SQL block that uses an explicit cursor to increment the salary by Rs. 1,500 for
employees in department number 30:

plsql

DECLARE
-- Declare a cursor to fetch employees in department 30
CURSOR emp_cursor IS
SELECT emp_id, salary
FROM employees
WHERE department_id = 30;

-- Declare variables to hold the employee details


v_emp_id employees.emp_id%TYPE;
v_salary employees.salary%TYPE;
Page 103 of 141

BEGIN
-- Open the cursor to fetch the employees
OPEN emp_cursor;

-- Loop through the records


LOOP
FETCH emp_cursor INTO v_emp_id, v_salary; -- Fetch employee id and salary
EXIT WHEN emp_cursor%NOTFOUND; -- Exit when no more records are found

-- Increment salary by Rs. 1,500


UPDATE employees
SET salary = v_salary + 1500
WHERE emp_id = v_emp_id;

-- Output the updated salary for the employee


DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_emp_id || ' updated salary: ' ||
(v_salary + 1500));
END LOOP;

-- Close the cursor after the loop ends


CLOSE emp_cursor;

-- Commit the changes to the database


COMMIT;
END;

Explanation:
1. Cursor Declaration: The cursor emp_cursor is defined to fetch emp_id and salary for
employees working in department 30.

2. Variable Declaration: The variables v_emp_id and v_salary are used to hold the employee's
ID and salary.

3. Cursor Operations:

The cursor is opened with OPEN emp_cursor .

The FETCH statement retrieves each employee's ID and salary.

The UPDATE statement increments the employee's salary by Rs. 1,500.

The DBMS_OUTPUT.PUT_LINE is used to print the updated salary for each employee.

4. Loop and Exit Condition: The loop continues until all records are processed.

5. Commit: A COMMIT is issued to permanently apply the changes.

Would you like to proceed to the next question?

8. Explain the different attributes of explicit cursors with suitable examples.


Year asked: S17

Explicit cursors in PL/SQL have several built-in attributes that help manage and control the
behavior of the cursor during its lifecycle. These attributes can be used to check the status of
Page 104 of 141

a cursor, whether it has successfully fetched records or reached the end of the result set. Let's
go through the attributes of explicit cursors:

Key Cursor Attributes:


1. %ISOPEN

Description: This attribute is used to check if the cursor is open or not.

Value: It returns TRUE if the cursor is open, and FALSE if it is closed.

Example:

plsql

IF emp_cursor%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE('Cursor is open.');
ELSE
DBMS_OUTPUT.PUT_LINE('Cursor is closed.');
END IF;

2. %FOUND

Description: This attribute is used to check if the most recent fetch operation returned a
row or not.

Value: It returns TRUE if a row was fetched successfully, and FALSE if no row was
fetched.

Example:

plsql

FETCH emp_cursor INTO v_emp_id, v_salary;


IF emp_cursor%FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee found: ' || v_emp_id);
ELSE
DBMS_OUTPUT.PUT_LINE('No employee found.');
END IF;

3. %NOTFOUND

Description: This attribute is the opposite of %FOUND . It checks whether the most
recent fetch operation failed to fetch any rows.

Value: It returns TRUE if the last fetch did not return any rows, and FALSE if a row was
fetched.

Example:

plsql

FETCH emp_cursor INTO v_emp_id, v_salary;


IF emp_cursor%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('No more rows to fetch.');
END IF;

4. %ROWCOUNT
Page 105 of 141

Description: This attribute returns the number of rows that have been fetched by the
cursor so far.

Value: It returns an integer value representing the number of rows fetched.

Example:

plsql

DBMS_OUTPUT.PUT_LINE('Total rows fetched: ' || emp_cursor%ROWCOUNT);

Example Using All Attributes:


plsql

DECLARE
CURSOR emp_cursor IS
SELECT emp_id, salary FROM employees WHERE department_id = 10;
v_emp_id employees.emp_id%TYPE;
v_salary employees.salary%TYPE;
BEGIN
OPEN emp_cursor;

-- Check if the cursor is open


IF emp_cursor%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE('Cursor is open.');
END IF;

LOOP
FETCH emp_cursor INTO v_emp_id, v_salary;
EXIT WHEN emp_cursor%NOTFOUND;

DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_emp_id || ', Salary: ' || v_salary);


END LOOP;

-- Display the number of rows fetched


DBMS_OUTPUT.PUT_LINE('Rows fetched: ' || emp_cursor%ROWCOUNT);

CLOSE emp_cursor;
END;

Explanation:
%ISOPEN: Checks if the cursor is open before fetching.

%FOUND: Used after FETCH to check if a record was successfully fetched.

%NOTFOUND: Used to break the loop when no more rows are available.

%ROWCOUNT: Tracks how many rows have been fetched during the cursor operation.

Would you like to proceed to the next question?


Page 106 of 141

9. What are different attributes of a cursor?


Year asked: S19

Cursors in PL/SQL have several built-in attributes that are helpful for managing the cursor's
state and performing actions based on its status. These attributes can be applied to both
explicit and implicit cursors, although they are more commonly used with explicit cursors.
Let's look at the different attributes of a cursor.

Cursor Attributes:
1. %ISOPEN

Description: This attribute checks whether the cursor is open or closed.

Value: It returns TRUE if the cursor is open, and FALSE if it is closed.

Usage: It is useful to check the cursor's state before performing any fetch operations or
closing the cursor.

Example:

plsql

IF emp_cursor%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE('Cursor is open.');
ELSE
DBMS_OUTPUT.PUT_LINE('Cursor is closed.');
END IF;

2. %FOUND

Description: This attribute returns TRUE if the most recent fetch operation successfully
retrieved a row, and FALSE if no row was retrieved.

Usage: This attribute is typically used after a FETCH operation to check if data was
retrieved.

Example:

plsql

FETCH emp_cursor INTO v_emp_id, v_salary;


IF emp_cursor%FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee found with ID: ' || v_emp_id);
ELSE
DBMS_OUTPUT.PUT_LINE('No employee found.');
END IF;

3. %NOTFOUND

Description: This attribute is the opposite of %FOUND . It returns TRUE if the last FETCH
operation did not return a row, and FALSE if a row was fetched.

Usage: This is commonly used to check for the end of a result set.

Example:

plsql
Page 107 of 141

FETCH emp_cursor INTO v_emp_id, v_salary;


IF emp_cursor%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('No more rows to fetch.');
END IF;

4. %ROWCOUNT

Description: This attribute returns the number of rows that have been fetched from the
cursor so far.

Value: It returns an integer indicating how many rows have been processed by the
cursor.

Usage: It is often used to track the number of rows fetched, especially in loops or for
debugging.

Example:

plsql

DBMS_OUTPUT.PUT_LINE('Total rows fetched: ' || emp_cursor%ROWCOUNT);

Example Using All Cursor Attributes:


plsql

DECLARE
CURSOR emp_cursor IS
SELECT emp_id, salary FROM employees WHERE department_id = 10;
v_emp_id employees.emp_id%TYPE;
v_salary employees.salary%TYPE;
BEGIN
OPEN emp_cursor;

-- Check if the cursor is open


IF emp_cursor%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE('Cursor is open.');
END IF;

LOOP
FETCH emp_cursor INTO v_emp_id, v_salary;
EXIT WHEN emp_cursor%NOTFOUND;

DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_emp_id || ', Salary: ' || v_salary);


END LOOP;

-- Display the number of rows fetched


DBMS_OUTPUT.PUT_LINE('Rows fetched: ' || emp_cursor%ROWCOUNT);

CLOSE emp_cursor;
END;

Summary of Cursor Attributes:


Page 108 of 141

1. %ISOPEN: Check if the cursor is open.

2. %FOUND: Check if a row was fetched.

3. %NOTFOUND: Check if no row was fetched.

4. %ROWCOUNT: Returns the number of rows fetched so far.

Would you like to continue to the next question?

Procedures: Create and Drop Procedure, Creating Procedures with Parameters, Calling
Procedures

1. What is Procedure? State syntax, purpose, and example of the following:


(i) CREATE PROCEDURE
(ii) DROP PROCEDURE
Year asked: S 16

A Procedure in PL/SQL is a stored program that can take parameters, perform operations, and
return results. It is stored in the database and can be executed by a user or another program.
Procedures are used for repetitive tasks to make code more organized, reusable, and efficient.

Syntax for CREATE PROCEDURE:

sql

CREATE [OR REPLACE] PROCEDURE procedure_name [parameters] IS


-- Declarations (optional)
BEGIN
-- Statements
END procedure_name;

CREATE PROCEDURE: Defines a new stored procedure in the database.

parameters: Can be input ( IN ), output ( OUT ), or both ( IN OUT ) parameters.

Statements: The actions the procedure performs, such as queries or updates.

Example of CREATE PROCEDURE:

sql

CREATE PROCEDURE increase_salary


IS
BEGIN
UPDATE employees SET salary = salary * 1.1;
END increase_salary;

Syntax for DROP PROCEDURE:

sql

DROP PROCEDURE procedure_name;


Page 109 of 141

DROP PROCEDURE: Removes an existing stored procedure from the database.

Example of DROP PROCEDURE:

sql

DROP PROCEDURE increase_salary;

Would you like to proceed to the next question?

2. Write a procedure to add a record of a new employee in emp table (emp: ename, empno,
sal, comm, deptno).
Year asked: S 17

To add a new record to the emp table using a stored procedure, the procedure can accept
values like employee name ( ename ), employee number ( empno ), salary ( sal ), commission
( comm ), and department number ( deptno ) as parameters.

Procedure Example:

sql

CREATE OR REPLACE PROCEDURE add_employee(


p_ename IN VARCHAR2,
p_empno IN NUMBER,
p_sal IN NUMBER,
p_comm IN NUMBER,
p_deptno IN NUMBER
)
IS
BEGIN
INSERT INTO emp (ename, empno, sal, comm, deptno)
VALUES (p_ename, p_empno, p_sal, p_comm, p_deptno);
END add_employee;

In this procedure:

p_ename , p_empno , p_sal , p_comm , and p_deptno are the input parameters representing

the employee's name, employee number, salary, commission, and department number,
respectively.

The INSERT statement is used to insert the employee's details into the emp table.

Would you like to proceed to the next question?

3. Write a procedure in PL/SQL to increase the salary of all employees by 7.5%. (employee:
name, age, sex, basic-salary).
Year asked: W 16

To increase the salary of all employees by 7.5%, we can write a procedure that updates the
basic-salary field for each employee in the employee table.
Page 110 of 141

Procedure Example:

sql

CREATE OR REPLACE PROCEDURE increase_salary


IS
BEGIN
UPDATE employee
SET basic_salary = basic_salary * 1.075;
END increase_salary;

In this procedure:

The UPDATE statement updates the basic_salary of all employees by multiplying the
current basic_salary by 1.075 (which is equivalent to a 7.5% increase).

There are no input parameters in this procedure as it updates all records in the employee
table.

Would you like to proceed to the next question?

4. Write a procedure in PL/SQL to increase the salary of all employees in an organisation by


75% (employee: name, age, sex, salary).
Year asked: S 17

To increase the salary of all employees by 75%, the procedure will update the salary field for
each employee in the employee table by multiplying the current salary by 1.75 (which is
equivalent to a 75% increase).

Procedure Example:

sql

CREATE OR REPLACE PROCEDURE increase_salary_75


IS
BEGIN
UPDATE employee
SET salary = salary * 1.75;
END increase_salary_75;

In this procedure:

The UPDATE statement multiplies the salary of every employee by 1.75 to apply the 75%
increase.

Similar to the previous example, this procedure does not take any input parameters and
will update all employees' salary records in the table.

Would you like to proceed with the next question?

5. Define procedure. Give syntax for creating procedure. Explain procedure having parameters
with a suitable example.
Page 111 of 141

Year asked: S 18, S 17

A procedure in PL/SQL is a named block of code that performs a specific task. It can be
invoked (called) to execute when needed. Procedures can take parameters that allow for
passing values into the procedure, making it more flexible.

Syntax for creating a procedure:

sql

CREATE OR REPLACE PROCEDURE procedure_name (parameter1 datatype, parameter2


datatype, ...)
IS
-- Declarations (optional)
BEGIN
-- PL/SQL block code
END procedure_name;

Parameters in a Procedure:

IN parameter: Accepts input values when the procedure is called (default if no type is
specified).

OUT parameter: Returns a value back to the calling program.

IN OUT parameter: Accepts an input value and can also return a value.

Example with Parameters:

This procedure accepts employee information and increases their salary by a given
percentage.

sql

CREATE OR REPLACE PROCEDURE increase_salary(emp_id IN NUMBER, percentage IN


NUMBER)
IS
BEGIN
UPDATE employee
SET salary = salary * (1 + percentage / 100)
WHERE empno = emp_id;
END increase_salary;

In this procedure:

emp_id is an IN parameter that represents the employee number.

percentage is an IN parameter that represents the percentage by which the salary should

be increased.

The UPDATE statement adjusts the salary of the employee specified by emp_id .

Calling the procedure:

sql

BEGIN
increase_salary(101, 10); -- Increase salary by 10% for employee with empno 101
Page 112 of 141

END;

Would you like to move to the next question?

6. Explain calling procedures.


Year asked: S 19

Calling a procedure refers to the process of invoking a procedure that has already been
created. A procedure can be called in different ways, such as from an anonymous PL/SQL
block, another procedure, or a trigger.

Ways to Call a Procedure:


1. Directly from an anonymous PL/SQL block: In this method, you call a procedure directly
inside the BEGIN...END block.

Example:

sql

BEGIN
procedure_name(parameter1, parameter2); -- Call the procedure with necessary
parameters
END;

This approach is commonly used to execute a procedure for a specific task.

2. From another procedure: A procedure can also be invoked from within another procedure,
allowing for modular and reusable code.

Example:

sql

CREATE OR REPLACE PROCEDURE outer_procedure IS


BEGIN
inner_procedure(param1, param2); -- Call another procedure inside this one
END outer_procedure;

3. Using EXECUTE command: You can also use the EXECUTE command in SQL*Plus or other
SQL interfaces to call a procedure.

Example:

sql

EXECUTE procedure_name(parameter1, parameter2);

Example of Calling a Procedure:


Suppose we have a procedure to update the salary of an employee:

sql
Page 113 of 141

CREATE OR REPLACE PROCEDURE increase_salary(emp_id IN NUMBER, percentage IN


NUMBER)
IS
BEGIN
UPDATE employee
SET salary = salary * (1 + percentage / 100)
WHERE empno = emp_id;
END increase_salary;

You can call this procedure as follows:

sql

BEGIN
increase_salary(101, 10); -- Call the procedure to increase the salary by 10% for
employee with empno 101
END;

The procedure will execute the statement within the BEGIN...END block and update the
employee's salary.

Would you like to move to the next question?

7. Write a procedure to display the record of a given employee number.


Year asked: W 18

To write a procedure that displays the record of a given employee number, we need to create
a procedure that accepts the employee number as an input parameter and retrieves the
corresponding details (such as employee name, salary, etc.) from the employee table.

Here's an example of how you can write this procedure in PL/SQL:

Syntax for the procedure:


sql

CREATE OR REPLACE PROCEDURE display_employee_details(emp_id IN NUMBER)


IS
-- Declare local variables to hold employee details
emp_name VARCHAR2(50);
emp_salary NUMBER(10, 2);
BEGIN
-- Retrieve employee details using the input employee number (emp_id)
SELECT ename, sal
INTO emp_name, emp_salary
FROM emp
WHERE empno = emp_id;

-- Display the employee details


DBMS_OUTPUT.PUT_LINE('Employee Name: ' || emp_name);
DBMS_OUTPUT.PUT_LINE('Employee Salary: ' || emp_salary);

EXCEPTION
Page 114 of 141

-- Handle the case if the employee is not found


WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee found with ID ' || emp_id);
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);
END display_employee_details;

Explanation of the procedure:


1. Input Parameter ( emp_id IN NUMBER ):

This accepts the employee number as input when the procedure is called.

2. Variable Declarations:

emp_name is a local variable to store the employee's name.

emp_salary is a local variable to store the employee's salary.

3. SELECT INTO Statement:

This retrieves the employee name ( ename ) and salary ( sal ) from the emp table where
the employee number ( empno ) matches the provided emp_id .

4. DBMS_OUTPUT.PUT_LINE:

This command is used to display the output in SQL*Plus or Oracle SQL Developer. It
prints the employee's name and salary.

5. Exception Handling:

If no employee is found for the given ID ( NO_DATA_FOUND ), it prints an appropriate


message.

Any other exceptions that might occur are caught using OTHERS , and the error message
is displayed using SQLERRM .

How to Call the Procedure:


sql

BEGIN
display_employee_details(101); -- Pass the employee number (e.g., 101) to display the
details
END;

This will display the details of the employee with employee number 101 . If no such
employee exists, it will print a message saying that no employee was found.

Would you like to continue to the next question?

Granting the EXECUTE Permission

Years Asked: S 16, S 18, W 17


Page 115 of 141

Question: State syntax, purpose, and example of granting the EXECUTE permission on a
procedure.

Explanation:

The EXECUTE permission in SQL is used to grant or deny a user the ability to execute a stored
procedure or function. This is a type of security control, allowing only specific users to run a
procedure, thereby preventing unauthorized access to sensitive operations.

Syntax:
The general syntax for granting the EXECUTE permission on a procedure is:

sql

GRANT EXECUTE ON procedure_name TO user_name;

Where:

procedure_name : The name of the procedure for which you want to grant execution rights.

user_name : The username of the person or role you want to grant permission to.

Purpose:
The purpose of granting EXECUTE permission is to provide a specific user or group with the
ability to run a stored procedure.

This permission helps control access to important functions, ensuring that only authorized
users can perform specific tasks that the procedure is designed to handle.

Example:
Suppose we have a procedure called increase_salary in a schema, and we want to grant the
EXECUTE permission to a user named HR_USER . The query would be:

sql

GRANT EXECUTE ON increase_salary TO HR_USER;

This allows the user HR_USER to execute the increase_salary procedure.

Alternatively, if you want to grant the permission to all users:

sql

GRANT EXECUTE ON increase_salary TO PUBLIC;

This allows all users in the database to execute the procedure, but this is usually not
recommended for sensitive operations.

Problems on Exception Handling, Cursors, and Procedures


Page 116 of 141

1. Write a PL/SQL block to handle division by zero exception.


Year asked: S 17

In PL/SQL, division by zero is a common exception that occurs when you try to divide a
number by zero, which is mathematically undefined. To handle this exception, you can use
the EXCEPTION block to catch and manage the error. Here's an example of how you can write
a PL/SQL block to handle the division by zero exception:

sql

DECLARE
num1 NUMBER := 10;
num2 NUMBER := 0;
result NUMBER;
BEGIN
-- Attempting to divide by zero
result := num1 / num2;
DBMS_OUTPUT.PUT_LINE('Result: ' || result);
EXCEPTION
-- Handling division by zero exception
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Error: Division by zero is not allowed!');
END;

Explanation:

In this example, we are attempting to divide num1 (10) by num2 (0).

Since division by zero is not allowed, the ZERO_DIVIDE exception will be raised.

The EXCEPTION block handles the error by printing a custom error message: "Error:
Division by zero is not allowed!".

Would you like to proceed with the next question?

2. Write a procedure in PL/SQL to find the sum of digits of a given number.


Year asked: S 19

Here is a PL/SQL procedure to calculate the sum of the digits of a given number:

sql

CREATE OR REPLACE PROCEDURE sum_of_digits (p_number IN NUMBER) IS


sum NUMBER := 0;
digit NUMBER;
BEGIN
-- Loop to extract and sum the digits
WHILE p_number > 0 LOOP
digit := MOD(p_number, 10); -- Extract the last digit
sum := sum + digit; -- Add the digit to the sum
p_number := FLOOR(p_number / 10); -- Remove the last digit
END LOOP;

DBMS_OUTPUT.PUT_LINE('Sum of digits: ' || sum);


Page 117 of 141

END sum_of_digits;
/

Explanation:

The procedure sum_of_digits accepts a number ( p_number ) as an input parameter.

Inside the procedure, we initialize a variable sum to zero, which will store the sum of the
digits.

A WHILE loop is used to repeatedly extract the last digit of the number using the MOD
function and add it to sum .

The number is then reduced by dividing it by 10 (removing the last digit) using the FLOOR
function.

Once all digits are processed, the total sum is displayed using DBMS_OUTPUT.PUT_LINE .

To call this procedure and find the sum of digits of a number, you can execute:

sql

BEGIN
sum_of_digits(12345);
END;

This will output:


Sum of digits: 15

Would you like to move on to the next question?

Here's a representation of the number 4 using special characters in very large letters:

shell

####
# #
# #
######
#
#
#

Function: Creating and Dropping Functions, Purity Levels in Functions, Executing Functions

1. What is a function? State syntax and purpose of:

(i) Creating function.

(ii) Dropping function.

Years Asked: S16, W17, S19, W19


Page 118 of 141

A function in PL/SQL is a subprogram that accepts input parameters, performs a specific task,
and returns a value. Functions are used to encapsulate repetitive logic and can be called from
SQL queries, PL/SQL blocks, or other functions and procedures.

Syntax for creating a function:


sql

CREATE [OR REPLACE] FUNCTION function_name (parameter_list)


RETURN return_datatype
IS
-- Declare local variables here (optional)
BEGIN
-- Function logic here
RETURN value; -- Return a value of the specified datatype
END;

Syntax for dropping a function:


sql

DROP FUNCTION function_name;

Purpose:
Creating a function allows for modular, reusable code. A function is designed to return a
value based on input parameters, and it can be invoked from anywhere in the program or
SQL.

Dropping a function is used when you want to remove a function from the database
because it is no longer needed or you need to redefine it.

Would you like me to proceed with the next question?

2. Write the syntax and example for creating a function.

Years Asked: S17, W18

Syntax for Creating a Function:


sql

CREATE [OR REPLACE] FUNCTION function_name (parameter_list)


RETURN return_datatype
IS
-- Declare local variables here (optional)
BEGIN
-- Function logic here
RETURN value; -- Return a value of the specified datatype
END;

Example of Creating a Function:


Page 119 of 141

Let's create a function that calculates the square of a number:

sql

CREATE OR REPLACE FUNCTION calculate_square (num IN NUMBER)


RETURN NUMBER
IS
BEGIN
RETURN num * num;
END;

Explanation:
CREATE OR REPLACE FUNCTION: This creates a new function or replaces an existing one if
it already exists.

calculate_square: The name of the function.

(num IN NUMBER): Parameter num is passed to the function as input.

RETURN NUMBER: The function will return a value of type NUMBER .

BEGIN...END: Contains the logic of the function. Here, it multiplies the input num by itself
to calculate its square.

Would you like to continue with the next question?

3. Explain purity level in functions.

Years Asked: S16

Purity Level in Functions:


Purity level refers to how a function interacts with the database and whether it has side
effects. In PL/SQL, functions can be categorized based on their purity level, which determines
how they are treated in the database. The purity level indicates whether a function depends
on or modifies the state of the database.

There are different purity levels for functions:

1. PURE:

A function is considered "pure" if it does not modify or rely on the database state.

It only uses the input parameters to produce a result and does not have side effects like
updating or querying the database.

A pure function is highly predictable because its result depends solely on the input
values.

Example:

sql

CREATE OR REPLACE FUNCTION add_numbers (num1 IN NUMBER, num2 IN NUMBER)


RETURN NUMBER
IS
BEGIN
Page 120 of 141

RETURN num1 + num2;


END;

This function is considered pure because it does not interact with the database; it just
computes the sum of the inputs.

2. IMPURE:

A function is "impure" if it depends on or modifies the database state.

This includes actions such as querying or modifying tables, updating values, or changing
session variables.

Example:

sql

CREATE OR REPLACE FUNCTION update_employee_salary (emp_id IN NUMBER,


new_salary IN NUMBER)
RETURN VARCHAR2
IS
BEGIN
UPDATE employees SET salary = new_salary WHERE employee_id = emp_id;
COMMIT;
RETURN 'Salary updated successfully';
END;

This function is impure because it updates the database.

Importance of Purity Levels:


Performance Optimization: Functions that are marked as pure are more optimized by the
database engine because they are predictable. This allows the system to cache results,
improving performance.

Usage in SQL Queries: Pure functions can be used in SQL queries (e.g., in the SELECT
statement), while impure functions might have restrictions on their usage.

Would you like to move on to the next question?

4. Write a PL/SQL code to create a function that takes a 3-digit number and prints the reverse
of it (example: 496 is to be printed as 694).

Years Asked: W17

PL/SQL Code:
sql

CREATE OR REPLACE FUNCTION reverse_number (num IN NUMBER)


RETURN NUMBER
IS
reversed_num NUMBER := 0;
remainder NUMBER;
BEGIN
Page 121 of 141

-- Loop to reverse the digits


WHILE num > 0 LOOP
remainder := num MOD 10; -- Get the last digit
reversed_num := (reversed_num * 10) + remainder; -- Build the reversed number
num := num / 10; -- Remove the last digit from the number
END LOOP;

RETURN reversed_num; -- Return the reversed number


END;
/

Explanation:
1. Input Parameter: The function takes a 3-digit number ( num ) as input.

2. Reversal Logic:

The WHILE loop continues as long as the number is greater than 0.

The MOD 10 operation is used to get the last digit of the number.

The last digit is then added to the reversed number, which is multiplied by 10 to shift
the digits left.

The original number is divided by 10 to remove the last digit.

3. Return Value: The reversed number is returned.

Example:
For input 496 , the output would be 694 .

Would you like to continue with the next question?

5. What are the advantages of using a function?

Years Asked: W17

Explanation:
Functions in PL/SQL provide several key advantages:

1. Reusability:

Functions can be called multiple times within the same program or from different
programs, which promotes code reusability and reduces redundancy.

Example: A function to calculate the area of a circle can be used anywhere without
rewriting the logic.

2. Modularity:

Functions allow you to divide a complex program into smaller, manageable parts. Each
function can handle a specific task, making the program easier to understand, maintain,
and debug.

Example: A function for user authentication, another for data validation, etc.

3. Code Maintenance:
Page 122 of 141

Functions make maintenance easier because the logic encapsulated in a function is


independent. If the logic inside a function needs to change, it only needs to be updated
in one place.

Example: If a function to calculate taxes needs a formula change, you only need to
update that function rather than every occurrence of the tax calculation in the program.

4. Parameterization:

Functions can accept input parameters and return output, making them versatile for
various tasks. This allows for dynamic behavior based on the input values.

Example: A function that calculates a discount based on the provided price and discount
rate.

5. Better Debugging:

As functions are self-contained, it is easier to isolate and debug problems. You can test
the function separately with different inputs to ensure it works correctly before
integrating it into larger programs.

6. Improved Readability:

By using functions to encapsulate logic, the main program becomes cleaner and more
readable, as the complex logic is abstracted away in functions.

Example: Instead of a long script with detailed logic, you can have short calls to
functions, which are easier to follow.

7. Optimization:

PL/SQL functions can be optimized for performance. Once a function is created, the
database engine can optimize its execution plan, especially for complex operations.

Example: A function to calculate complex mathematical formulas can be optimized to


run faster.

Would you like to continue with the next question?

6. Write a function that returns the updated salary of an employee on the basis of employee
number. Increase the salary by 17%. Employee (emp_no, emp_name, emp_salary).

Years Asked: S18, S19, W19

Explanation:
This PL/SQL function will take the employee number as an input and return the updated
salary after increasing it by 17%.

The function performs the following steps:

Accepts the employee number as a parameter.

Retrieves the employee's current salary from the database.

Increases the salary by 17%.

Returns the updated salary.

Here's the syntax and example:


Page 123 of 141

PL/SQL Function:
sql

CREATE OR REPLACE FUNCTION increase_salary (emp_id IN NUMBER)


RETURN NUMBER
IS
updated_salary NUMBER;
BEGIN
-- Fetch the current salary of the employee using emp_id
SELECT emp_salary INTO updated_salary
FROM employee
WHERE emp_no = emp_id;

-- Increase the salary by 17%


updated_salary := updated_salary * 1.17;

-- Return the updated salary


RETURN updated_salary;
EXCEPTION
-- Handle case where employee number is not found
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee not found.');
RETURN NULL;
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred.');
RETURN NULL;
END increase_salary;

Explanation of the Code:


Function Declaration: The function increase_salary takes emp_id (employee number) as
input and returns a number (the updated salary).

Variable Declaration: updated_salary is declared to hold the calculated salary.

SELECT Query: The current salary of the employee is retrieved using the emp_no from the
employee table.

Salary Update: The salary is increased by 17% ( 1.17 multiplier).

RETURN Statement: The updated salary is returned to the calling program.

Exception Handling:

If no employee is found with the given emp_id , a NO_DATA_FOUND exception is caught


and a message is printed.

Any other errors will be handled by the OTHERS exception.

Example Usage:
sql

DECLARE
updated_salary NUMBER;
BEGIN
Page 124 of 141

updated_salary := increase_salary(101); -- Example with employee number 101


DBMS_OUTPUT.PUT_LINE('Updated Salary: ' || updated_salary);
END;

This will output the updated salary of the employee with the given emp_id . If the employee
number doesn't exist, it will output Employee not found.

Would you like to continue with the next question?

7. What is the purpose of executing functions? Provide an example.

Years Asked: S16

Explanation:
The purpose of executing functions in PL/SQL is to encapsulate logic in a reusable and
modular way. Functions can be executed for various purposes such as:

Calculations: Functions are commonly used to perform specific calculations, such as


computing interest rates, updating salaries, or determining discounts.

Data Retrieval: Functions can be used to retrieve values from the database based on input
parameters.

Code Reusability: By defining a function, you can reuse the code wherever necessary
without rewriting it each time.

Return Specific Values: Functions always return a value, making them suitable for
scenarios where you need to compute and return a result.

When executed, a function can:

1. Accept Input: Functions often take input parameters that allow them to perform
calculations or queries based on dynamic data.

2. Return Results: Functions return results that can be used in SQL queries, other PL/SQL
blocks, or even in the application layer.

3. Execute Logic: Functions contain business logic that can execute a series of operations,
such as retrieving data, performing arithmetic operations, or modifying data.

Example:
Here is an example where a function is executed to calculate the total salary of an employee,
including bonuses and deductions.

PL/SQL Code Example:


sql

CREATE OR REPLACE FUNCTION calculate_total_salary (emp_id IN NUMBER)


RETURN NUMBER
IS
total_salary NUMBER;
basic_salary NUMBER;
bonus NUMBER := 500; -- A fixed bonus amount
Page 125 of 141

deductions NUMBER := 200; -- Fixed deductions


BEGIN
-- Fetch basic salary of employee from the database
SELECT emp_salary INTO basic_salary
FROM employee
WHERE emp_no = emp_id;

-- Calculate total salary (basic salary + bonus - deductions)


total_salary := basic_salary + bonus - deductions;

-- Return total salary


RETURN total_salary;

EXCEPTION
-- Handle exceptions
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee not found.');
RETURN NULL;
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred.');
RETURN NULL;
END calculate_total_salary;

Execution Example:
Now, you can execute the function to calculate the total salary of an employee using their
emp_id (employee number).

sql

DECLARE
total_salary NUMBER;
BEGIN
total_salary := calculate_total_salary(101); -- Example with employee number 101
DBMS_OUTPUT.PUT_LINE('Total Salary: ' || total_salary);
END;

Explanation of the Example:


Function Purpose: This function calculates the total salary of an employee by adding a
fixed bonus and subtracting fixed deductions from their basic salary.

Execution: The function is executed with an employee number ( emp_id ). It retrieves the
basic salary, adds the bonus, subtracts the deductions, and returns the total salary.

Error Handling: If the employee is not found in the database, the function returns NULL
and prints an error message.

Would you like to proceed with the next question?


Page 126 of 141

Triggers: Create Triggers, Type of Triggers, Creating BEFORE and AFTER Triggers, INSTEAD-OF
Triggers, Trigger Predicates

1. What are triggers? Explain the use of before and after triggers with suitable examples.
Year asked: 2016 (w16), 2017 (w17), 2018 (s18), 2019 (s19)

A trigger is a special kind of stored procedure in SQL that automatically executes (or "fires") in
response to specific events on a particular table or view. The event can be an insert, update,
or delete operation.

There are two common types of triggers: BEFORE and AFTER triggers.

BEFORE Trigger: This type of trigger is executed before an insert, update, or delete
operation is performed. It's commonly used to validate or modify data before it is actually
written to the database.

Example:

sql

CREATE OR REPLACE TRIGGER check_salary_before_insert


BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF :NEW.salary < 1000 THEN
RAISE_APPLICATION_ERROR(-20001, 'Salary must be greater than 1000');
END IF;
END;

AFTER Trigger: This type of trigger is executed after the insert, update, or delete operation
has been performed. It's used when we need to take action after the DML operation, such
as auditing or cascading actions.

Example:

sql

CREATE OR REPLACE TRIGGER log_salary_update


AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO salary_log (emp_id, old_salary, new_salary, update_date)
VALUES (:OLD.emp_id, :OLD.salary, :NEW.salary, SYSDATE);
END;

Let me know if you'd like me to move on to the next question!

2. Create a trigger that restricts a user to insert a row on the emp table on Sunday.
Year asked: 2016 (s16)
Page 127 of 141

To create a trigger that prevents the insertion of a row on a specific day, such as Sunday, we
can use the BEFORE INSERT trigger. The trigger will check the current day of the week and if
it's Sunday, it will raise an exception to prevent the insertion.

Example:

sql

CREATE OR REPLACE TRIGGER prevent_insert_on_sunday


BEFORE INSERT ON emp
FOR EACH ROW
DECLARE
current_day VARCHAR2(10);
BEGIN
SELECT TO_CHAR(SYSDATE, 'Day') INTO current_day FROM DUAL;
IF current_day = 'Sunday' THEN
RAISE_APPLICATION_ERROR(-20001, 'Inserting rows on Sunday is not allowed.');
END IF;
END;

This trigger checks if the current day is Sunday and prevents any insert operation on the emp
table if the condition is met.

Should I move on to the next question?

3. Create a trigger that restricts a user from performing a DML on the EMP table on Sunday.
Year asked: 2016 (w16), 2017 (w17)

To create a trigger that prevents any DML (INSERT, UPDATE, DELETE) operation on the emp
table on Sunday, we will use a BEFORE INSERT, BEFORE UPDATE, and BEFORE DELETE
trigger. The trigger will check if the current day is Sunday, and if so, it will raise an exception
to stop the operation.

Example:

sql

CREATE OR REPLACE TRIGGER prevent_dml_on_sunday


BEFORE INSERT OR UPDATE OR DELETE ON emp
FOR EACH ROW
DECLARE
current_day VARCHAR2(10);
BEGIN
SELECT TO_CHAR(SYSDATE, 'Day') INTO current_day FROM DUAL;
IF current_day = 'Sunday' THEN
RAISE_APPLICATION_ERROR(-20001, 'DML operations on Sunday are not allowed.');
END IF;
END;

This trigger prevents INSERT, UPDATE, and DELETE operations on the emp table when the
day is Sunday.

Should I move on to the next question?


Page 128 of 141

4. Create a trigger which will not allow the user to work on the table Employee on Friday.
Year asked: 2018 (w18)

To create a trigger that prevents any operation (INSERT, UPDATE, DELETE) on the Employee
table on Friday, we can use a BEFORE INSERT, BEFORE UPDATE, and BEFORE DELETE trigger.
The trigger will check if the current day is Friday, and if so, it will raise an exception to stop the
operation.

Example:

sql

CREATE OR REPLACE TRIGGER prevent_dml_on_friday


BEFORE INSERT OR UPDATE OR DELETE ON Employee
FOR EACH ROW
DECLARE
current_day VARCHAR2(10);
BEGIN
SELECT TO_CHAR(SYSDATE, 'Day') INTO current_day FROM DUAL;
IF current_day = 'Friday' THEN
RAISE_APPLICATION_ERROR(-20002, 'DML operations on Friday are not allowed.');
END IF;
END;

This trigger ensures that no changes can be made to the Employee table on Fridays.

Shall I proceed with the next question?

5. Create a trigger that fires at the UPDATE statement on the Employee table and records the
employee id, current date, and the new salary in the Emp_salary table.
Year asked: 2018 (s18)

To create a trigger that records the employee id, current date, and the new salary whenever
there is an UPDATE operation on the Employee table, we can define a BEFORE UPDATE
trigger. The trigger will capture the necessary details and insert them into the Emp_salary
table.

Example:

sql

CREATE OR REPLACE TRIGGER record_salary_update


AFTER UPDATE ON Employee
FOR EACH ROW
BEGIN
INSERT INTO Emp_salary (id, edate, new_salary)
VALUES (:NEW.emp_no, SYSDATE, :NEW.emp_salary);
END;

This trigger fires after any UPDATE operation on the Employee table. It inserts the employee
id, current date, and new salary into the Emp_salary table.
Page 129 of 141

Shall I proceed with the next question?

6. What are different types of triggers? Explain.


Year asked: 2017 (s17)

There are several types of triggers in PL/SQL. They can be broadly classified into the following
categories:

1. DML Triggers (Data Manipulation Language Triggers):

These triggers are fired in response to INSERT, UPDATE, or DELETE operations on a table
or view.

Types of DML triggers:

BEFORE Trigger: Fired before the DML operation is executed.

AFTER Trigger: Fired after the DML operation is executed.

INSTEAD OF Trigger: Replaces the DML operation with the code defined in the trigger.

2. DDL Triggers (Data Definition Language Triggers):

These triggers are fired when there are changes to the structure of database objects like
tables, views, or indexes.

Example: CREATE, ALTER, and DROP operations on tables.

Before DDL Trigger: Triggered before a DDL operation.

After DDL Trigger: Triggered after a DDL operation.

3. LOGON and LOGOFF Triggers:

These triggers are fired when a user logs in or logs out of the database.

Example: Logging the user's login or logout time.

4. Compound Triggers:

A compound trigger allows multiple timing points for different actions (BEFORE and
AFTER) to be handled in a single trigger.

5. SYSTEM Triggers:

These triggers respond to certain system-level events, such as STARTUP, SHUTDOWN,


LOGON, and LOGOFF events.

6. INSTEAD-OF Trigger:

Used with views instead of tables. It replaces the action that would normally be
performed (insert/update/delete) on a view with a new set of operations defined in the
trigger.

Shall I move to the next question?

7. What is the difference between BEFORE, AFTER, and INSTEAD-OF triggers? Explain with
examples.
Year asked: 2018 (w18)
Page 130 of 141

In PL/SQL, there are three primary types of triggers based on their timing:

1. BEFORE Trigger:

Fired before the DML operation (INSERT, UPDATE, DELETE) is performed on the table.

Commonly used for validating or modifying data before it is written to the table.

Example:
sql

CREATE OR REPLACE TRIGGER check_before_insert


BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF :NEW.salary < 1000 THEN
RAISE_APPLICATION_ERROR(-20001, 'Salary must be greater than or equal to
1000');
END IF;
END;

Here, the trigger checks if the salary is less than 1000 before inserting a new employee.

2. AFTER Trigger:

Fired after the DML operation is performed on the table.

Useful for performing actions like logging changes or updating related tables.

Example:
sql

CREATE OR REPLACE TRIGGER log_after_update


AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO salary_audit (emp_id, old_salary, new_salary, change_date)
VALUES (:OLD.emp_id, :OLD.salary, :NEW.salary, SYSDATE);
END;

This trigger logs the salary change for an employee after an UPDATE is made to the
employees table.

3. INSTEAD-OF Trigger:

Fired instead of the DML operation when it is performed on a view (not a table).

Used to perform specific actions when an update, insert, or delete is attempted on a


view, especially when the view is based on multiple tables.

Example:
sql

CREATE OR REPLACE TRIGGER update_view_instead_of


INSTEAD OF UPDATE ON emp_view
FOR EACH ROW
BEGIN
UPDATE employees
Page 131 of 141

SET salary = :NEW.salary


WHERE emp_id = :OLD.emp_id;
END;

This trigger replaces the UPDATE operation on the view emp_view with an actual update
on the underlying employees table.

Shall I move to the next question?

8. What is a DDL trigger? Explain with an example.


Year asked: 2018 (w18)

A DDL trigger (Data Definition Language trigger) is a trigger that is fired in response to DDL
statements such as CREATE, ALTER, DROP, TRUNCATE, etc. These triggers help to capture and
control the structural changes made to the database schema, such as changes in tables,
views, or schemas. DDL triggers can be used to track changes, prevent certain actions, or log
DDL operations for auditing purposes.

Types of DDL triggers:

1. BEFORE DDL Trigger – Executes before a DDL operation is carried out.

2. AFTER DDL Trigger – Executes after a DDL operation is performed.

Example:
Let's create an AFTER DROP DDL trigger to log whenever a table is dropped from the
database.

sql

CREATE OR REPLACE TRIGGER log_table_drop


AFTER DROP ON SCHEMA
BEGIN
INSERT INTO ddl_audit_log (operation, object_name, operation_date)
VALUES ('DROP', 'Table ' || :OBJECT_NAME, SYSDATE);
END;

Explanation:

This trigger fires after any DROP statement (like dropping a table) in the schema.

The SCHEMA keyword in the trigger specifies that the trigger should fire on all objects in
the schema.

It logs the operation and the object name (table) into a custom audit log table
ddl_audit_log .

Shall I move to the next question?

9. What are trigger predicates?


Year asked: 2018 (s18)
Page 132 of 141

Trigger predicates are special conditions or logical expressions that can be used in triggers to
provide more control over when the trigger should fire. They allow the trigger to be fired
based on specific conditions, making the trigger more flexible and efficient.

Types of Trigger Predicates:


1. :NEW – Refers to the new value of a column when a record is being inserted or updated. It
is used in INSERT and UPDATE triggers.

2. :OLD – Refers to the old value of a column when a record is being updated or deleted. It is
used in UPDATE and DELETE triggers.

3. :ROWCOUNT – Refers to the number of rows affected by a DML statement.

4. :ACTION – Refers to the type of DML action that triggered the event (INSERT, UPDATE,
DELETE).

5. :WHEN – Allows you to specify additional conditions when the trigger should fire.

Example:
In a BEFORE INSERT trigger, you can use the :NEW predicate to check or modify values
before inserting:

sql

CREATE OR REPLACE TRIGGER check_salary


BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF :NEW.salary < 1000 THEN
RAISE_APPLICATION_ERROR(-20001, 'Salary cannot be less than 1000');
END IF;
END;

In this example, the trigger checks if the salary being inserted is below a certain threshold
and raises an error if the condition is met.

Shall I proceed to the next question?

Enabling, Disabling, and Dropping Triggers

1. Explain how triggers are enabled and disabled.


Year Asked: 2017 (s17)

Triggers in Oracle can be enabled or disabled using the ALTER TRIGGER statement. The
process helps manage whether a trigger should fire or not when an event occurs on a table.

Enabling a Trigger: This activates the trigger so that it will execute when the specified event
(INSERT, UPDATE, DELETE) occurs on the table.

Syntax:

sql
Page 133 of 141

ALTER TRIGGER trigger_name ENABLE;

Example:

sql

ALTER TRIGGER employee_salary_update ENABLE;

Disabling a Trigger: This prevents the trigger from firing when the event occurs. Disabling is
useful when you want to temporarily stop the trigger without removing it from the
database.

Syntax:

sql

ALTER TRIGGER trigger_name DISABLE;

Example:

sql

ALTER TRIGGER employee_salary_update DISABLE;

You can also enable or disable all triggers on a specific table or schema, depending on the
need.

Would you like to proceed with the next question?

2. What is Enabling, Disabling, and Dropping triggers?


Year Asked: 2018 (s18), 2019 (s19)

Enabling a Trigger: This process activates the trigger, making it function whenever the
triggering event (like INSERT , UPDATE , or DELETE ) occurs on the specified table.

Syntax:

sql

ALTER TRIGGER trigger_name ENABLE;

Example:

sql

ALTER TRIGGER salary_update_trigger ENABLE;

Disabling a Trigger: This action stops the trigger from firing when the associated event
happens on the table, though it keeps the trigger defined in the database.

Syntax:

sql
Page 134 of 141

ALTER TRIGGER trigger_name DISABLE;

Example:

sql

ALTER TRIGGER salary_update_trigger DISABLE;

Dropping a Trigger: Dropping a trigger removes it completely from the database. Once
dropped, the trigger cannot be used unless re-created.

Syntax:

sql

DROP TRIGGER trigger_name;

Example:

sql

DROP TRIGGER salary_update_trigger;

Triggers can be enabled or disabled for testing, maintenance, or when you need to perform
certain operations without triggering their actions. Dropping is used when you no longer
need the trigger.

Shall I proceed with the next question?

3. What is Enabling, Disabling, and Dropping Triggers? Provide syntax and examples.
Year Asked: 2019 (w19)

Enabling a Trigger: This action ensures that the trigger will fire when its associated event
occurs on the target table.

Syntax:

sql

ALTER TRIGGER trigger_name ENABLE;

Example:

sql

ALTER TRIGGER employee_salary_trigger ENABLE;

Disabling a Trigger: This action temporarily disables the trigger, so it will not be executed
when its specified event happens on the table.

Syntax:

sql
Page 135 of 141

ALTER TRIGGER trigger_name DISABLE;

Example:

sql

ALTER TRIGGER employee_salary_trigger DISABLE;

Dropping a Trigger: This permanently removes the trigger from the database. Once
dropped, it cannot be used unless re-created.

Syntax:

sql

DROP TRIGGER trigger_name;

Example:

sql

DROP TRIGGER employee_salary_trigger;

These operations are essential for managing triggers in the database as they help control
when triggers should be active or inactive and remove unwanted triggers.

Shall I proceed with the next question?

4. What is the process of replacing and dropping triggers?


Year Asked: 2019 (w19)

Replacing a Trigger: If you want to modify the definition of an existing trigger, you cannot
directly modify it. Instead, you need to drop the existing trigger and then create a new one
with the required changes.

Syntax for Replacing: You can achieve this by dropping the old trigger and then creating a
new one with the same name or a different name if necessary.

1. Drop the old trigger:

sql

DROP TRIGGER trigger_name;

2. Create a new trigger with the updated logic:

sql

CREATE OR REPLACE TRIGGER trigger_name


[trigger_type]
ON table_name
[trigger_body];
Page 136 of 141

Example:

sql

DROP TRIGGER old_employee_salary_trigger;

CREATE TRIGGER new_employee_salary_trigger


BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
:NEW.salary := :NEW.salary + 1000;
END;

Dropping a Trigger: Dropping a trigger removes it from the database permanently. Once
dropped, it cannot be used unless it is re-created.

Syntax for Dropping:

sql

DROP TRIGGER trigger_name;

Example:

sql

DROP TRIGGER employee_salary_trigger;

By replacing a trigger, you ensure that the old trigger's functionality is updated without
needing to create a completely new trigger with a different name. Dropping a trigger
completely removes it from the system.

Shall I move to the next question?

Problems on Functions and Triggers

1. Write a PL/SQL block to find the greater of two numbers using functions.
Year asked: 2017 (s17)

In this problem, we need to create a PL/SQL block where we write a function to compare two
numbers and return the greater one. We can use the IF-ELSE condition in the function to
decide which number is greater.

Solution:
sql

-- Declaring the function to find the greater of two numbers


CREATE OR REPLACE FUNCTION find_greater(num1 IN NUMBER, num2 IN NUMBER)
RETURN NUMBER IS
BEGIN
IF num1 > num2 THEN
Page 137 of 141

RETURN num1; -- Return num1 if it's greater


ELSE
RETURN num2; -- Return num2 if it's greater or equal
END IF;
END;

-- PL/SQL block to call the function and display the result


DECLARE
num1 NUMBER := 15;
num2 NUMBER := 20;
greater_num NUMBER;
BEGIN
greater_num := find_greater(num1, num2); -- Call the function
DBMS_OUTPUT.PUT_LINE('The greater number is: ' || greater_num); -- Display the
result
END;

Explanation:
1. We define a function find_greater that accepts two numbers num1 and num2 as input
parameters.

2. Inside the function, we compare the two numbers using the IF-ELSE condition.

3. Based on the comparison, the function returns the greater number.

4. In the PL/SQL block, we call the find_greater function by passing two numbers and display
the greater number using DBMS_OUTPUT.PUT_LINE .

Let me know if you'd like to proceed with the next question.

Miscellaneous

1. What is a function? State the syntax and purpose of creating and dropping functions.
Year: 2019 (s19)

A function is a PL/SQL subprogram that returns a single value. It can take input parameters
and perform operations based on them to return a result. Functions are commonly used
when you want to perform a calculation or return a result that can be used in a SQL query or
another PL/SQL block.

Syntax for Creating a Function:


sql

CREATE [OR REPLACE] FUNCTION function_name


(parameter1 datatype1, parameter2 datatype2, ...)
RETURN return_datatype IS
BEGIN
-- body of the function
Page 138 of 141

RETURN value; -- result to be returned


END function_name;

Syntax for Dropping a Function:


sql

DROP FUNCTION function_name;

Purpose:
1. Creating Functions: Functions are created to encapsulate a particular task that can return a
value. These are useful for repetitive calculations, data manipulations, and for use in
SELECT statements.

2. Dropping Functions: Dropping a function removes it from the database, making it


unavailable for further use. This is done when the function is no longer needed or needs to
be replaced with an updated version.

Would you like me to solve the next question?

2. Explain the problems on Triggers.


Year: 2018 (w18)

Triggers are special types of stored procedures that are automatically executed or "triggered"
when certain events occur in the database. These events include INSERT, UPDATE, DELETE
operations, or even database schema changes. While triggers are powerful tools for enforcing
business rules, maintaining data integrity, and automating processes, they come with their
own set of challenges or problems.

Problems on Triggers:
1. Performance Issues:

Triggers can slow down database performance because they add additional processing
overhead. Every time a triggering event occurs, the associated trigger is fired, and this
can lead to slower data modifications, especially if there are multiple triggers for a
single event.

2. Complexity in Debugging:

Triggers can be hard to debug because they execute automatically in response to


specific actions. If a trigger contains a bug, identifying and fixing it can be difficult since
the trigger's behavior is not always obvious and may be triggered under specific
conditions.

3. Unintended Consequences:

A poorly designed trigger can result in unintended consequences, such as infinite loops
or cascading operations. For example, an AFTER INSERT trigger that updates a record
might inadvertently trigger another INSERT, causing the trigger to fire repeatedly,
potentially leading to performance degradation or system failure.
Page 139 of 141

4. Interdependencies:

Triggers may create interdependencies between tables and other database objects. If
triggers are not managed properly, they can cause conflicts or unexpected results when
modifying the structure of tables or changing business logic.

5. Difficulty in Managing and Maintaining:

As the number of triggers in a database grows, managing and maintaining them can
become challenging. Keeping track of which triggers are dependent on which
operations, ensuring that they do not conflict with one another, and updating or
removing triggers when business rules change requires careful planning and
documentation.

6. Triggers Can Mask Errors:

If an error occurs in a trigger and the exception handling is not done properly, it might
suppress the error message, causing it to go unnoticed. This can lead to incorrect data
being inserted or updated in the database.

7. Limited Support for DDL Operations:

Triggers are generally designed to respond to DML (Data Manipulation Language)


operations, such as INSERT, UPDATE, and DELETE. Although some databases support
DDL triggers, they are not as widely used or supported as DML triggers, and the syntax
and behavior can vary between database systems.

Would you like me to solve the next question?

1. What is a function? State the syntax and purpose of creating and dropping functions.
Year: 2019 (s19)

A function in PL/SQL is a named block of code that performs a specific task and returns a
value. Functions are used to encapsulate business logic that can be executed multiple times.
They are similar to procedures but differ in that they return a value to the caller. Functions
can be used in SELECT statements, where clauses, and other SQL expressions.

Purpose of Creating Functions:


Modularity: Functions allow you to break down complex logic into smaller, manageable
pieces. This makes your code more readable and maintainable.

Reusability: Functions can be reused in multiple places, saving time and effort in writing
repetitive code.

Abstraction: Functions help abstract away complex operations. The caller does not need to
understand the inner workings of the function, just the result it provides.

Better Performance: Functions can be used for optimization by minimizing redundant


operations. They are often used for computations and complex transformations.

Syntax for Creating a Function:


sql
Page 140 of 141

CREATE [OR REPLACE] FUNCTION function_name (parameter1 datatype, parameter2


datatype, ...)
RETURN return_datatype
IS
-- Declarations (optional)
BEGIN
-- Function logic
RETURN result;
END;

Explanation:

function_name: Name of the function.

parameter1, parameter2, ...: Input parameters for the function (optional).

return_datatype: The data type of the value the function will return.

IS: Keyword that marks the beginning of the function body.

BEGIN: Begins the function's logic.

RETURN: Specifies the value that the function will return.

Example of Creating a Function:


Let's create a simple function that takes two numbers as input and returns their sum:

sql

CREATE OR REPLACE FUNCTION add_numbers (num1 IN NUMBER, num2 IN NUMBER)


RETURN NUMBER
IS
BEGIN
RETURN num1 + num2;
END;

In this example:

The function add_numbers accepts two numbers as input parameters.

It returns the sum of these numbers.

Dropping a Function:
If you no longer need a function, you can remove it from the database using the DROP
FUNCTION command. The syntax is:

sql

DROP FUNCTION function_name;

Example of Dropping a Function:

sql

DROP FUNCTION add_numbers;


Page 141 of 141

This will remove the function add_numbers from the database.

Would you like me to solve the next question?

You're welcome! Feel free to reach out if you have any more questions. Have a great day! 😊

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy