SQL_PL
SQL_PL
Codd’s Rules:-
Codd's twelve rules are a set of thirteen rules(number from 0 to 12)
proposed by Edgar F.Codd,a pioneer of relational model for databases
CHARACTER(n):
This data type represents a fixed length string of exactly 'n' characters
where 'n' is greater than zero and should be an integer.
Storage: n bytes (fixed).
Max Size: 255 characters
Use Case: Storing fixed-length strings like country codes ('IN', 'US').
INTEGER:
INTEGER is a numeric data type used for storing whole numbers (both
positive and negative).
Storage: 4 bytes
Range:
Signed: -2,147,483,648 to 2,147,483,647
Unsigned: 0 to 4,294,967,295
SMALLINT:
SMALLINT is a numeric data type used to store whole numbers (integers),
but it takes less storage than INT. It is used when you don’t need large
numbers, helping to save storage space in a database.
Storage: 2 bytes
Range:
Signed: -32,768 to 32,767
Unsigned: 0 to 65,535
DATE:
Description: Stores only the date in the format YYYY-MM-DD.
Storage: 3 bytes
Use Case: Storing birthdates, event dates.
DATETIME:
Description: Stores both date and time in the format YYYY-MM-DD
HH:MM:SS.
Storage: 8 bytes
Use Case: Storing timestamps for records, such as when a user registered.
TIMESTAMP:
Description: Similar to DATETIME, but it automatically updates to the
current timestamp when the row is modified.
Storage: 4 bytes
Use Case: Storing last updated times.
TIME:
Description: Stores time values in the format HH:MM:SS.
Storage: 3 bytes
Use Case: Storing durations, working hours.
YEAR:
Description: Stores only a year in YYYY format.
Storage: 1 byte
Use Case: Storing manufacturing years, admission years.
FLOAT:
Description: The FLOAT data type is used to store approximate decimal
values with floating-point precision. It is best used when exact precision is
not required, such as scientific calculations or large-scale measurements.
Storage: 4 bytes
Use Case: Storing measurements like temperature, height, or percentages.
Que 3) What are the different types of constraints that are used in oracle?
Explain any two constraints in details
Two constraints
1. NOT NULL Constraint
2. PRIMARY KEY Constraint
In Oracle, constraints are rules applied to table columns to maintain the
accuracy, integrity, and consistency of data. Constraints enforce specific
conditions to prevent invalid data entry, ensuring the database remains
structured and reliable.
Example:
CREATE TABLE Employees (
emp_id NUMBER PRIMARY KEY,
emp_name VARCHAR2(100) NOT NULL,
salary NUMBER
);
In this example, the emp_id column is the primary key, meaning each
employee must have a unique emp_id, and NULL values are not allowed.
3. UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are distinct.
Unlike the PRIMARY KEY, a UNIQUE constraint allows NULL values, but all
non-NULL values must be unique.
5. CHECK Constraint
The CHECK constraint ensures that values in a column meet a specific
condition.
6. DEFAULT Constraint
The DEFAULT constraint assigns a default value to a column when no value
is specified.
Que 1) What is view? What are the uses of view? Write syntax to update and
delete view.
1. Introduction to Views
A view in SQL is a virtual table that represents the result of a stored
query. Unlike a table, a view does not store data permanently but
dynamically fetches data from one or more underlying tables whenever it
is accessed. Views are commonly used to simplify complex queries, enhance
security, and ensure data consistency.
1. Characteristics of Views
A view is a virtual table, meaning it does not store data but retrieves it
dynamically from base tables.
It can be used like a regular table in SELECT statements.
It simplifies query execution by hiding complex joins and aggregations.
Views can restrict access to sensitive data by displaying only selected
columns or rows.
Some views allow updates, but modifications must meet certain conditions
Updating a View
If you need to modify an existing view, use the CREATE OR REPLACE VIEW
statement:
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example:
CREATE OR REPLACE VIEW HighSalaryEmployees AS
SELECT emp_id, emp_name, salary
FROM Employees
WHERE salary > 60000;
Deleting a View
To remove a view, use the DROP VIEW statement:
Advantages of Views
Enhanced Security
Views restrict user access to specific columns and rows, helping enforce
data privacy.
Query Optimization
By encapsulating complex queries, views improve query efficiency and
reduce redundancy.
Data Independence
Users can access consistent data through views, even if the underlying
database structure changes.
1. Basic LOOP
The LOOP statement repeatedly executes a block of code until explicitly
exited using the EXIT or EXIT WHEN statement.
It does not have an automatic termination condition; you must explicitly
exit the loop.
LOOP
-- Statements
EXIT WHEN condition;
END LOOP;
Example
DECLARE
counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || counter);
counter := counter + 1;
EXIT WHEN counter > 5; -- Exit when counter exceeds 5
END LOOP;
END;
2. WHILE LOOP
The WHILE loop executes as long as the given condition evaluates to TRUE.
The condition is checked before executing the loop body.
Example
DECLARE
counter NUMBER := 1;
BEGIN
WHILE counter <= 5 LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || counter);
counter := counter + 1;
END LOOP;
END;
3. FOR LOOP
The FOR loop executes a block of statements for a fixed number of
iterations.
It uses an implicit counter that automatically increments/decrements.
Syntax
FOR counter_variable IN start_value .. end_value LOOP
-- Statements
END LOOP;
Example
BEGIN
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Iteration: ' || i);
END LOOP;
END
Syntax
FOR record_variable IN (SELECT column_name FROM table_name) LOOP
-- Statements
END LOOP;
Example
BEGIN
FOR emp_rec IN (SELECT emp_name FROM employees) LOOP
DBMS_OUTPUT.PUT_LINE('Employee: ' || emp_rec.emp_name);
END LOOP;
END;
5. NESTED LOOPS
PL/SQL supports nested loops, meaning you can place a loop inside another
loop.
Example:
BEGIN
FOR i IN 1..3 LOOP
FOR j IN 1..2 LOOP
DBMS_OUTPUT.PUT_LINE('i=' || i || ', j=' || j);
END LOOP;
END LOOP;
END;
EXIT and CONTINUE Statements
EXIT – Terminates the loop immediately.
EXIT WHEN condition – Exits when a condition is met.
CONTINUE – Skips the remaining statements in the loop and starts the
next iteration.
CONTINUE WHEN condition – Skips the remaining statements only if the
condition is met.
BEGIN
FOR i IN 1..5 LOOP
IF i = 3 THEN
CONTINUE; -- Skips the iteration when i = 3
END IF;
DBMS_OUTPUT.PUT_LINE('Iteration: ' || i);
END LOOP;
END;
Example:
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No record found!');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Some other error occurred.');
4. End Section
The END keyword is used to mark the end of the PL/SQL block.
It does not have a separate keyword but is necessary for closing the block.
Unit 3
Que 1) What is cursor ? Explain attributes of Explicit cursor
A cursor in PL/SQL is a pointer to a result set of a SQL query. It allows
row-by-row processing of query results. There are two types of cursors in
PL/SQL:
Types of Cursor:
1 Implicit Cursor – Automatically created by Oracle for single-row queries
(e.g., SELECT INTO).
2 Explicit Cursor – Defined explicitly by the programmer for multi-row
queries.
Attributes of Explicit Cursor in PL/SQL
Explicit cursors in PL/SQL have four important attributes:
%FOUND
Returns TRUE if a row is fetched successfully.
Returns FALSE if no row is fetched.
Example:
IF cursor_name%FOUND THEN
DBMS_OUTPUT.PUT_LINE('Row fetched successfully.');
END IF;
%NOTFOUND
Returns TRUE if no row is fetched.
Returns FALSE if a row is fetched.
Example:
IF cursor_name%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('No more rows left to fetch.');
END IF;
%ISOPEN
Returns TRUE if the cursor is open.
Returns FALSE if the cursor is closed.
Example
IF cursor_name%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE('Cursor is still open.');
END IF;
%ROWCOUNT
Returns the number of rows fetched so far.
Example:
DBMS_OUTPUT.PUT_LINE('Rows fetched: ' || cursor_name%ROWCOUNT);
DECLARE
CURSOR emp_cursor IS SELECT emp_id, emp_name FROM employees;
emp_record employees%ROWTYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO emp_record;
EXIT WHEN emp_cursor%NOTFOUND; -- Exit loop when no more rows
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_record.emp_id || ',
Name: ' || emp_record.emp_name);
END LOOP;
DBMS_OUTPUT.PUT_LINE('Total Rows Fetched: ' ||
emp_cursor%ROWCOUNT);
CLOSE emp_cursor;
END;
Que 2) Write a procedure to find the minimum of three numbers in PL/SQL
How to Execute:
SET SERVEROUTPUT ON;
BEGIN
FIND_MINIMUM(10, 5, 8);
END;
/
Output:
The minimum value is: 5
Que 3) How will you create,call and remove a stored procedure ?Exaplin in PL/SQL
In PL/SQL, a stored procedure is a named block of PL/SQL code that
performs a specific task and can be called multiple times. Below is a
detailed explanation of how to create, call, and remove a stored procedure
in PL/SQL.
Unit 4
Que 1) What are triggers? Explain BEFORE and AFTER trigger in PL/SQL
Triggers in PL/SQL
A trigger is a special type of stored procedure in PL/SQL that is
automatically executed (fired) when a specific event occurs in the
database. Triggers are commonly used to enforce business rules, maintain
data integrity, and perform auditing tasks.
Explanation:
This trigger fires after an INSERT operation on the employees table.
It logs the insertion event in an employee_audit table with a timestamp.
Que 2) What is function?write a function to find factorial of given number in PL/
SQL
What is a Function?
A function in PL/SQL is a named PL/SQL block that returns a single value.
Functions are used to perform calculations and return a result. They help
in code reusability and modularity.
DECLARE
num NUMBER := 5;
fact NUMBER;
FUNCTION factorial(n IN NUMBER) RETURN NUMBER
IS
result NUMBER := 1;
BEGIN
IF n < 0 THEN
RETURN NULL;
END IF;
FOR i IN 1..n LOOP
result := result * i;
END LOOP;
RETURN result;
END factorial;
BEGIN
fact := factorial(num);
DBMS_OUTPUT.PUT_LINE('Factorial of ' || num || ' is: ' || fact);
END;
/
Example:
CREATE OR REPLACE FUNCTION get_salary(emp_id NUMBER)
RETURN NUMBER
IS
emp_salary NUMBER;
BEGIN
SELECT salary INTO emp_salary FROM employees WHERE employee_id =
emp_id;
RETURN emp_salary;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN 0;
END get_salary;