PL SQL
PL SQL
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).
UNIT - II:
Views: Create, Drop, Insert, Update, Delete, Types of Views.
UNIT - III:
Exception Handling: Predefined and User-defined Exceptions.
UNIT - IV:
Functions: Creating/Dropping, Purity Levels, Executing Functions.
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:
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.
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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
5. Sequences:
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:
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:
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:
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:
FOREIGN KEY: Ensures that a value in one table matches a value in another table,
maintaining referential integrity.
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).
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:
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.
ALTER: Used to modify existing database objects, such as adding or dropping columns in
a table.
TRUNCATE: Used to remove all data from a table, but the table structure remains intact.
Page 8 of 141
Purpose: DML is used for manipulating data within the database. It allows users to query,
insert, update, and delete data in the database.
Commands:
Example: INSERT INTO employees (id, name) VALUES (1, 'John Doe');
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;
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.
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.
SET TRANSACTION: Used to set properties for a transaction, such as isolation level.
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
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
This will create a new empty table with the same structure as the employees table.
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.
5. NOT NULL: Ensures that a column does not have NULL values.
Example:
sql
In this example:
(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
ALTER TABLE:
The ALTER TABLE statement is used to modify an existing table, such as adding, deleting, or
modifying columns.
sql
sql
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
This command will completely remove the students table from the database.
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.
1. Adding a column:
sql
sql
Page 12 of 141
3. Dropping a column:
sql
4. Renaming a column:
sql
The ALTER TABLE command is powerful and can be used to make many changes to an
existing table's structure.
To add a new column to an existing table, you can use the ALTER TABLE command with the
ADD keyword.
Example:
sql
In this example, we are adding a new column email of type VARCHAR(100) to the employees
table.
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
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
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
In this example:
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
In this example:
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
In this example:
It must contain unique values for each customer and cannot have NULL values.
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
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
In this example:
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.
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.
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
In this example:
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.
sql
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
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.
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
Flexible: You can use any valid SQL expression or condition to define the check.
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
In this example:
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.
sql
This insert is valid because John Doe's age (25) satisfies the condition age >= 18 .
sql
In this case, the age value 16 violates the CHECK constraint, and the insertion will fail.
Example: Ensure that the salary of an employee is greater than 0 and the age is at least 18.
Page 18 of 141
sql
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.
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.
When defining a table, you can specify the name of the constraint along with the
constraint definition.
sql
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
In this case:
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
In this case:
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
In this case:
sql
sql
sql
sql
By naming constraints, you create an easier way to manage them, especially when you need
to modify or drop the constraint later.
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.
2. ALL_CONSTRAINTS: Contains information about all constraints on the tables you have
access to, including constraints from other schemas.
The USER_CONSTRAINTS view is the most commonly used to view constraints in a specific
schema.
Page 21 of 141
sql
constraint_type : The type of the constraint (e.g., P for primary key, R for foreign key, C
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 .
sql
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).
sql
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
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
CONSTRAINT_TYPE: The type of the constraint (e.g., P for Primary Key, R for Foreign Key,
C for Check, U for Unique).
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.
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 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
Example:
sql
This adds a primary key constraint named emp_pk on the employee_id column of the
employees table.
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
Example:
sql
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.
Syntax:
sql
Example:
sql
This adds a unique constraint on the email column of the employees table, ensuring no two
rows can have the same email value.
A check constraint is used to limit the values that can be stored in a column by specifying a
condition.
Syntax:
sql
Example:
sql
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.
A NOT NULL constraint ensures that a column does not accept NULL values.
Syntax:
sql
Example:
sql
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.
To drop a primary key constraint, you use the DROP CONSTRAINT clause along with the name
of the primary key constraint.
Syntax:
sql
Example:
sql
This removes the primary key constraint named emp_pk from the employees table.
To drop a foreign key constraint, you specify the name of the foreign key constraint in the
DROP CONSTRAINT clause.
Syntax:
sql
Example:
sql
This removes the foreign key constraint named fk_emp from the orders table.
To drop a unique constraint, specify the constraint name in the DROP CONSTRAINT clause.
Syntax:
sql
Page 26 of 141
Example:
sql
This removes the unique constraint named emp_email_unique from the employees table.
To drop a check constraint, you use the DROP CONSTRAINT clause, specifying the constraint
name.
Syntax:
sql
Example:
sql
This removes the check constraint named age_check from the employees table.
To drop a NOT NULL constraint (i.e., allowing NULL values again), you use the MODIFY
clause.
Syntax:
sql
Example:
sql
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.
Example:
sql
Explanation:
StudentID , Name , Age , and Course are the columns of the Student table.
StudentID: 101
Age: 20
Example:
sql
Page 28 of 141
UPDATE Employee
SET Salary = 55000
WHERE EmployeeID = 5;
Explanation:
WHERE EmployeeID = 5 : Ensures only the record with EmployeeID equal to 5 is updated.
Example:
sql
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
Example:
sql
SELECT *
FROM Student
WHERE Name LIKE 'A%';
Explanation:
SELECT * : This retrieves all columns from the Student table.
Page 29 of 141
'A%' means the name should start with the letter A and can be followed by zero or
Example Scenario:
Suppose the Student table contains the following data:
Query Output:
Asked in: S 17
Query:
sql
SELECT SupplierName
FROM SUPPLIER
Page 30 of 141
Explanation:
SELECT SupplierName : Retrieves the SupplierName column from the SUPPLIER table.
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.
Query:
sql
SELECT *
FROM SUPPLIER
WHERE City = 'Mumbai';
Explanation:
SELECT * : Retrieves all columns for the suppliers meeting the condition.
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.
Results:
SupplierName
ABC Traders
Page 31 of 141
Asked in: S 16
Query:
sql
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.
Records with StudentID 101 and 103 will be deleted because their Fees values are less
than 5000 .
Page 32 of 141
Resulting Table:
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.
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.
Example:
Creating a Sequence:
sql
NOCYCLE : The sequence does not restart after reaching its maximum value.
sql
This returns the next value in the sequence, such as 1 , 2 , 3 , and so on.
sql
Here, the sequence Student_Seq provides a unique StudentID for each new record.
Dropping a Sequence:
To delete a sequence:
sql
What are Synonyms? Explain with syntax for creating and deleting synonyms.
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.
sql
[PUBLIC] : Optional. When specified, the synonym is created for all users. If omitted, the
schema_name.object_name : The fully qualified name of the object (table, view, etc.) that the
Example:
sql
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 .
sql
Now, any user in the database can use emp_public_synonym to access the employees table
from the hr schema.
sql
Example:
sql
sql
Page 36 of 141
sql
This query accesses the employees table in the hr schema without directly referencing the
schema name.
1/2
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.
[PUBLIC] : Optional. If specified, the synonym is public and accessible by all database users.
sql
Now, instead of writing hr.employees , you can simply refer to the table as emp_table in
your SQL queries.
sql
sql
Any user in the database can now query the employees table using emp_table_public .
sql
Syntax:
Page 38 of 141
sql
sql
sql
Built-in Functions: Arithmetic, Date, Character, Conversion, Single Row, Aggregate, Decode
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:
sql
Page 39 of 141
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)
value).
Example:
Suppose you want to calculate the date three months from now.
sql
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
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)
Example:
sql
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)
Example:
sql
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)
Example:
sql
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)
Example:
sql
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)
Example:
sql
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.
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.
Syntax:
sql
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
In this example:
Page 45 of 141
If the salary is not one of the specified values (i.e., not 10000 , 20000 , or 30000 ), it will
return 'Salary Not Found' .
Output:
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
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:
SALE_ID
SALE_AMOUNT
To find the total sales amount, we can use the SUM() function:
sql
SALE_ID SALE_AMOUNT
1 100
2 200
3 300
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
SALE_ID SALE_AMOUNT
1 100
2 200
3 300
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:
sql
SALE_ID SALE_AMOUNT
1 100
Page 48 of 141
SALE_ID SALE_AMOUNT
2 200
3 300
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:
sql
SALE_ID SALE_AMOUNT
1 100
2 200
3 300
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:
sql
SALE_ID SALE_AMOUNT
1 100
2 200
3 300
LOWEST_SALE
100
Conclusion:
SUM() calculates the total of a numeric column.
COUNT() counts the number of rows in a table or those that meet a condition.
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.
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:
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
Result:
Page 51 of 141
Name Department_Name
John HR
Alice IT
Bob HR
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
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.
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
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.
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
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
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
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
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.
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
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.
4. Non-correlated subquery: Independent and does not reference the outer query.
Employees:
1 John 5000
Page 57 of 141
2 Alice 6000
3 Bob 4000
Departments:
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
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
sql
In this example:
The innermost subquery retrieves the Employee_IDs of those employees whose salary is
greater than 5000.
The main query fetches the names and salaries of employees working in those
departments.
Result:
Name Salary
Alice 6000
sql
In this case:
The subquery references the Department_ID from the outer query ( E.Department_ID ),
making it a correlated subquery.
The main query returns employees whose salary is greater than the average salary in their
department.
Result:
Key Points:
A subquery is a query inside another query, typically used to return values to be used by
the outer query.
A correlated subquery refers to the outer query, while a non-correlated subquery does not.
Page 59 of 141
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.
sql
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.
sql
In this example, the john user is granted the SELECT privilege on the employees table,
meaning he can view data from that table.
sql
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.
sql
Page 60 of 141
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.
sql
This removes the SELECT privilege from john on the employees table. After this, john can no
longer view data from the table.
sql
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.
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.
sql
COMMIT;
Example:
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.
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.
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
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.
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.
Purpose of a View
1. Simplify Queries: Complex queries can be saved as a view, making it easier to use them
repeatedly.
Example
Creating a View
Requirement: Create a view to display students from the Computer department only.
sql
sql
Result:
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.
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.
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.
5. Consistency:
Ensures consistent data representation by encapsulating common queries within a view.
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.
Example
Table: EMPLOYEES
Create a View
sql
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.
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
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
sql
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
Used for presenting data without altering it Used for interacting with underlying data
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
Example
To drop the Employee_Department view that we created earlier, the SQL command would be:
sql
This command deletes the Employee_Department view, and you can no longer use it to query
data.
Department No. 50
Department No. 35
Years Asked: S16 (Dept. 004), S18 (Dept. 50), W16 (Dept. 35), W19 (60 marks in Computer
Science)
sql
Explanation:
CREATE VIEW Employee_Limited_Info AS : This creates a new view called Employee_Limited_Info .
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
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.
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 .
sql
In this case, Employee_View should be a simple view based on a single table without any
complex joins or aggregate functions.
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
sql
UPDATE Employee_View
SET employee_name = 'Jane Smith'
WHERE employee_id = 101;
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.
sql
In this case, Employee_View must map to a single base table for the DELETE operation to
be successful.
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.
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.
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.
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).
sql
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.
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.
1. Storage Overhead: Since materialized views store data physically, they require storage
space. This might be an issue if there is limited storage capacity.
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.
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.
PL/SQL Programming
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.
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:
PL/SQL is used to write programs (like functions, procedures, and triggers) that perform
complex operations.
3. Control Structures:
4. Execution:
5. Error Handling:
A PL/SQL block is the basic unit of code in PL/SQL. It consists of three main sections:
The declaration section is optional; if not used, you can skip it.
Syntax:
sql
DECLARE
variable_name datatype [DEFAULT value];
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;
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
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.
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:
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.
DATE: Stores date and time values, including the year, month, day, hour, minute, and
second.
Records: Group together related data of different types (similar to structures in C).
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.
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:
+ , - , * , / , % (modulo)
Example:
sql
Example:
sql
AND , OR , NOT
Example:
sql
END IF;
4. PL/SQL Expressions:
Expressions are combinations of variables, constants, operators, and function calls that
produce a single value.
sql
sql
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.
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
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
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.
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.
Syntax:
sql
CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
...
ELSE result
END;
Example:
sql
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'.
Syntax:
sql
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE result
END;
Example:
sql
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'.
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
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
To solve this, you can use an IF-ELSE condition to compare two numbers and display the
larger one.
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;
Explanation:
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;
Explanation:
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.
16. Write a PL/SQL program to find the factorial of a given number N using a FOR loop.
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
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.
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;
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.
18. Write a PL/SQL program to find the sum of the digits of a given number.
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
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.
19. Write a PL/SQL program to check whether a given number is even or odd.
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.
plaintext
𝗧𝗛𝗥𝗘𝗘
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.
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:
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.
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:
The ZERO_DIVIDE exception is raised automatically, and the error message "Error: Division
by zero" is displayed.
(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;
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).
1. ZERO_DIVIDE:
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;
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
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.
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.
1. Declare an 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:
The IF statement checks if the grade is below 40. If true, the RAISE
grade_below_threshold; statement raises 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.
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
1. %FOUND: Returns TRUE if the cursor has fetched at least one row, otherwise, it returns
FALSE.
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:
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.
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 .
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.
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;
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.
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.
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;
Summary of Differences:
Explicit Cursor: Manually declared and controlled by the programmer, more control.
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;
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:
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.
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;
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 UPDATE statement adds Rs. 1,000 as special allowances to the current salary.
4. Loop and Exit Condition: The loop continues to fetch records until there are no more
records to fetch ( %NOTFOUND ).
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;
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 UPDATE statement subtracts Rs. 500 from the employee's salary.
4. Loop and Exit Condition: The loop continues until all records have been processed.
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;
BEGIN
-- Open the cursor to fetch the employees
OPEN emp_cursor;
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 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.
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:
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
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
4. %ROWCOUNT
Page 105 of 141
Description: This attribute returns the number of rows that have been fetched by the
cursor so far.
Example:
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;
LOOP
FETCH emp_cursor INTO v_emp_id, v_salary;
EXIT WHEN emp_cursor%NOTFOUND;
CLOSE emp_cursor;
END;
Explanation:
%ISOPEN: Checks if the cursor is open before fetching.
%NOTFOUND: Used to break the loop when no more rows are available.
%ROWCOUNT: Tracks how many rows have been fetched during the cursor operation.
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
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
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
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
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;
LOOP
FETCH emp_cursor INTO v_emp_id, v_salary;
EXIT WHEN emp_cursor%NOTFOUND;
CLOSE emp_cursor;
END;
Procedures: Create and Drop Procedure, Creating Procedures with Parameters, Calling
Procedures
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.
sql
sql
sql
sql
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
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.
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
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.
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
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.
5. Define procedure. Give syntax for creating procedure. Explain procedure having parameters
with a suitable example.
Page 111 of 141
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.
sql
Parameters in a Procedure:
IN parameter: Accepts input values when the procedure is called (default if no type is
specified).
IN OUT parameter: Accepts an input value and can also return a value.
This procedure accepts employee information and increases their salary by a given
percentage.
sql
In this procedure:
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 .
sql
BEGIN
increase_salary(101, 10); -- Increase salary by 10% for employee with empno 101
Page 112 of 141
END;
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.
Example:
sql
BEGIN
procedure_name(parameter1, parameter2); -- Call the procedure with necessary
parameters
END;
2. From another procedure: A procedure can also be invoked from within another procedure,
allowing for modular and reusable code.
Example:
sql
3. Using EXECUTE command: You can also use the EXECUTE command in SQL*Plus or other
SQL interfaces to call a procedure.
Example:
sql
sql
Page 113 of 141
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.
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.
EXCEPTION
Page 114 of 141
This accepts the employee number as input when the procedure is called.
2. Variable Declarations:
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:
Any other exceptions that might occur are caught using OTHERS , and the error message
is displayed using SQLERRM .
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.
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
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
sql
This allows all users in the database to execute the procedure, but this is usually not
recommended for sensitive operations.
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:
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!".
Here is a PL/SQL procedure to calculate the sum of the digits of a given number:
sql
END sum_of_digits;
/
Explanation:
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;
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
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.
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.
sql
Explanation:
CREATE OR REPLACE FUNCTION: This creates a new function or replaces an existing one if
it already exists.
BEGIN...END: Contains the logic of the function. Here, it multiplies the input num by itself
to calculate its square.
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
This function is considered pure because it does not interact with the database; it just
computes the sum of the inputs.
2. IMPURE:
This includes actions such as querying or modifying tables, updating values, or changing
session variables.
Example:
sql
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.
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).
PL/SQL Code:
sql
Explanation:
1. Input Parameter: The function takes a 3-digit number ( num ) as input.
2. Reversal Logic:
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.
Example:
For input 496 , the output would be 694 .
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
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.
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).
Explanation:
This PL/SQL function will take the employee number as an input and return the updated
salary after increasing it by 17%.
PL/SQL Function:
sql
SELECT Query: The current salary of the employee is retrieved using the emp_no from the
employee table.
Exception Handling:
Example Usage:
sql
DECLARE
updated_salary NUMBER;
BEGIN
Page 124 of 141
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.
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:
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.
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.
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;
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.
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
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
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
This trigger checks if the current day is Sunday and prevents any insert operation on the emp
table if the condition is met.
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
This trigger prevents INSERT, UPDATE, and DELETE operations on the emp table when the
day is Sunday.
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
This trigger ensures that no changes can be made to the Employee table on Fridays.
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
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
There are several types of triggers in PL/SQL. They can be broadly classified into the following
categories:
These triggers are fired in response to INSERT, UPDATE, or DELETE operations on a table
or view.
INSTEAD OF Trigger: Replaces the DML operation with the code defined in the trigger.
These triggers are fired when there are changes to the structure of database objects like
tables, views, or indexes.
These triggers are fired when a user logs in or logs out of the database.
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:
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.
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
Here, the trigger checks if the salary is less than 1000 before inserting a new employee.
2. AFTER Trigger:
Useful for performing actions like logging changes or updating related tables.
Example:
sql
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).
Example:
sql
This trigger replaces the UPDATE operation on the view emp_view with an actual update
on the underlying employees table.
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.
Example:
Let's create an AFTER DROP DDL trigger to log whenever a table is dropped from the
database.
sql
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 .
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.
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.
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
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.
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
Example:
sql
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
Example:
sql
You can also enable or disable all triggers on a specific table or schema, depending on the
need.
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
Example:
sql
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
Example:
sql
Dropping a Trigger: Dropping a trigger removes it completely from the database. Once
dropped, the trigger cannot be used unless re-created.
Syntax:
sql
Example:
sql
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.
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
Example:
sql
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
Example:
sql
Dropping a Trigger: This permanently removes the trigger from the database. Once
dropped, it cannot be used unless re-created.
Syntax:
sql
Example:
sql
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.
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.
sql
sql
Example:
sql
Dropping a Trigger: Dropping a trigger removes it from the database permanently. Once
dropped, it cannot be used unless it is re-created.
sql
Example:
sql
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.
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
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.
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 .
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.
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.
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:
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.
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.
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.
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.
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.
Explanation:
return_datatype: The data type of the value the function will return.
sql
In this example:
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
sql
You're welcome! Feel free to reach out if you have any more questions. Have a great day! 😊