Dbms EXPERIMENT NO-4,5,6,7,8,9
Dbms EXPERIMENT NO-4,5,6,7,8,9
FORMATTEDDATE
-------------
06-FEB-2025
NUMERICVALUE
------------
12345
DATEVALUE
---------
06-FEB-25
STRING FUNCTIONS
4. CONCATENATION
CONCATENATEDTEXT
----------------
HELLO WORLD
5. PADDING
o DEFINITION:
→ PADS '123' WITH 0S ON THE LEFT UNTIL THE TOTAL
LPAD('123', 5, '0')
LENGTH IS 5 ('00123').
RPAD('123', 5, '0') → PADS '123' WITH 0S ON THE RIGHT ('12300').
o OUTPUT:
LEFTPADDED RIGHTPADDED
---------- -----------
00123 12300
6. TRIMMING SPACES
o DEFINITION:
LTRIM REMOVES LEADING SPACES.
RTRIM REMOVES TRAILING SPACES.
o OUTPUT:
LEFTTRIMMED RIGHTTRIMMED
----------- ------------
HELLO HELLO
7. CASE CONVERSION
o DEFINITION:
LOWER CONVERTS TO LOWERCASE ('HELLO').
UPPER CONVERTS TO UPPERCASE ('HELLO').
INITCAP CAPITALIZES EACH WORD ('HELLO WORLD').
o OUTPUT:
o DEFINITION:
LENGTH GIVES THE LENGTH OF THE STRING (11).
SUBSTR('HELLO WORLD', 1, 5) EXTRACTS THE FIRST FIVE CHARACTERS
('HELLO').
o OUTPUT:
STRINGLENGTH SUBSTRING
------------ ---------
11 HELLO
POSITION
--------
5
DATE FUNCTIONS
o DEFINITION:
SYSDATE RETURNS THE CURRENT DATE.
NEXT_DAY(SYSDATE, 'MONDAY') FINDS THE NEXT
MONDAY.
o OUTPUT (ASSUMING TODAY IS FEB 6, 2025 - THURSDAY):
CURRENTDATE NEXTMONDAY
----------- ----------
06-FEB-25 10-FEB-25
o DEFINITION:
ADD_MONTHS(SYSDATE, 3) ADDS 3 MONTHS.
LAST_DAY(SYSDATE) RETURNS THE LAST DAY OF THE CURRENT MONTH.
o OUTPUT:
THREEMONTHSLATER LASTDAYOFMONTH
---------------- --------------
06-MAY-25 28-FEB-25
MONTHSBETWEEN
-------------
1.19
MATHEMATICAL FUNCTIONS
o DEFINITION:
LEAST RETURNS THE SMALLEST VALUE (5).
GREATEST RETURNS THE LARGEST VALUE (20).
o OUTPUT:
SMALLEST LARGEST
-------- -------
5 20
o DEFINITION:
TRUNC(SYSDATE, 'MONTH') GIVES THE FIRST DAY OF THE CURRENT MONTH
(01-FEB-25).
ROUND(SYSDATE, 'MONTH') ROUNDS TO THE NEAREST MONTH BOUNDARY
(01-FEB-25 IF BEFORE 15TH, ELSE 01-MAR-25).
o OUTPUT:
TRUNCATEDDATE ROUNDEDDATE
------------- -----------
01-FEB-25 01-FEB-25
EXPERIMENT NO:5
AIM: i.Create a simple PL/SQL program which includes declaration section,executable section and
exception –Handling section (Ex. Student marks can be selected from the table and printed for those who
secured first class and anexception can be raised if no records were found)
STEP1:
v_name student.name%TYPE;
v_marks student.marks%TYPE;
no_data_found EXCEPTION;
v_count NUMBER := 0;
BEGIN
-- Open cursor
OPEN c_student;
LOOP
FETCH c_student INTO v_name, v_marks;
CLOSE c_student;
EXCEPTION
WHEN no_data_found THEN
DBMS_OUTPUT.PUT_LINE('No students found with first class marks.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An unexpected error occurred: ' || SQLERRM);
END;
/
OUTPUT:
Scenario 1: When students with first class exist (marks >= 60)
101 Alice 75
102 Bob 55
Charli
103 88
e
Expected Output
Name: Alice, Marks: 75
Name: Charlie, Marks: 88
If the table contains only students with marks below 60, the program will raise an exception:
Updated Table
DELETE FROM student WHERE marks >= 60;
COMMIT;
Expected Output
No students found with first class marks.
ii. Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL block.
DECLARE
v_id NUMBER := 104;
v_name VARCHAR2(50) := 'David';
v_marks NUMBER := 82;
BEGIN
-- Insert a student record
INSERT INTO student (student_id, name, marks) VALUES (v_id, v_name, v_marks);
DBMS_OUTPUT.PUT_LINE('Inserted: ' || v_name);
-- Savepoint after first insert
SAVEPOINT sp1;
-- Insert another student
INSERT INTO student (student_id, name, marks) VALUES (105, 'Eve', 90);
DBMS_OUTPUT.PUT_LINE('Inserted: Eve');
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('Duplicate ID error. Rolling back to last savepoint.');
ROLLBACK TO sp2; -- Undo last insert but keep first
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
ROLLBACK; -- Undo all changes
END;
OUTPUT:
101 Alice 75
102 Bob 55
Charli
103 88
e
104 David 82
105 Eve 90
If an attempt is made to insert another student with student_id = 105 (which already exists):
Inserted: David
Inserted: Eve
Duplicate ID error. Rolling back to last savepoint.
101 Alice 75
102 Bob 55
Charli
103 88
e
104 David 82
105 Eve 90
EXPERIMENT NO:6
AIM:
Develop a program that includes the features NESTED IF, CASE and CASEexpression. The program can be
extended using the NULLIF and COALESCE functions.
DESCRIPTION:
1. NESTED IF
Definition:
NESTED IF is a conditional statement used in procedural SQL (like PL/SQL or T-SQL) that allows
multiple IF statements inside one another to test for different conditions.
IF condition_1 THEN
-- statements
-- statements
ELSE
-- statements
END IF;
Definition:
The CASE expression in SQL allows for conditional logic directly in the query. It can be used in the
SELECT, UPDATE, or WHERE clauses.
It evaluates conditions in a sequential manner.
CASE
ELSE result_3
END
The CASE Expression is similar to the simple CASE but allows you to compare each condition to
an arbitrary expression.
You can compare the expression with multiple conditions and return a result based on the first
condition that is met.
CASE expression
ELSE result_3
END
4. NULLIF
Definition:
The NULLIF function compares two expressions. If the expressions are equal, it returns NULL;
otherwise, it returns the first expression.
This function is useful when you want to avoid division by zero or handle specific cases where a
value might need to be replaced by NULL.
Syntax:
NULLIF(expression_1, expression_2)
5. COALESCE
Definition:
The COALESCE function returns the first non-NULL value in a list of expressions. It is typically
used to replace NULL values with a default or alternative value.
It can handle multiple values in a sequence and returns the first one that isn't NULL.
Syntax:
Program:
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(100),
salary DECIMAL(10, 2),
department_id INT
);
INSERT INTO employees (emp_id, emp_name, salary, department_id)
VALUES
(1, 'John Doe', 4500.00, 1),
(2, 'Jane Smith', 3500.00, 2),
(3, 'Jim Brown', 5000.00, 1),
(4, 'Emily White', 5500.00, 3),
(5, 'Michael Green', NULL, 2); -- Salary is NULL for demonstration
Output
salary_with_
emp_id emp_name salary salary_category salary_status salary_if_not_zero
default
1 John Doe 4500.00 Average Salary Other Salary 4500.00 4500.00
2 Jane Smith 3500.00 Average Salary Other Salary 3500.00 3500.00
3 Jim Brown 5000.00 High Salary Exact 5000 5000.00 5000.00
4 Emily White 6000.00 High Salary Exact 6000 6000.00 6000.00
Michael
5 NULL Salary Missing Other Salary NULL 4000.00
Green
EXPERIMENT NO:7
AIM: Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops
using ERROR Handling, BUILT –IN Exceptions, USE defined Exceptions,
RAISEAPPLICATION ERROR.
WHILE LOOP:
A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax: WHILE condition LOOP sequence_of_statements END LOOP;
PL/SQL Code: A PL/SQL Program to find sum of ODD number upto given number using
While loop
DECLARE
inval NUMBER; -- Variable for iterating over odd numbers
endval NUMBER := 10; -- Hardcoded upper bound for the sum
s NUMBER DEFAULT 0; -- Variable to store the sum
BEGIN
-- Initialize the starting odd number
inval := 1;
FOR Loop:
A FOR LOOP is a repetition control structure that allows us to efficiently write a loop set
serveroutput on; declare inval number; endval number; s number default 0; begin inval:=1;
endval:=&endval; while inval
Syntax :
FOR counter IN initial_value .. final_value LOOP sequence_of_statements; END LOOP;
PL/SQL CODE: A PL/SQL code to print multiplication table using for loop
DECLARE
VAR1 NUMBER: = 5; -- Set the number for multiplication table
VAR2 NUMBER; -- Counter for loop
BEGIN
-- Print a message for the table
dbms_output.put_line('Multiplication table for ' || VAR1);
OUTPOUT:
Statement processed.
Multiplication table for 5
5X1=5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
NESTED LOOP:
PL/SQL allows using one loop inside another loop. It may be either basic, while or
for loop.
Syntax:
WHILE condition1 LOOP
sequence_of_statements1
WHILE condition2 LOOP
sequence_of_statements2
END LOOP;
END LOOP;
A PL/SQL program to print n prime number using nested loop.
DECLARE
i NUMBER(3); -- To store the number we are checking
j NUMBER(3); -- To store the potential divisors
BEGIN
i := 2; -- Starting number to check
LOOP
-- Start the inner loop with j set to 2
j := 2;
LOOP
-- Exit condition when a divisor is found (mod == 0) or j becomes greater than i/2
EXIT WHEN (MOD(i, j) = 0) OR (j > i / 2);
j := j + 1; -- Increase j to check the next potential divisor
END LOOP;
-- If j is greater than i/2, that means no divisor was found, hence i is prime
IF j > i / 2 THEN
DBMS_OUTPUT.PUT_LINE(i || ' is prime');
END IF;
Description:
Creates a stored procedure with IN and OUT parameters.
Calls the procedure to calculate the sum of two numbers.
Displays the result.
Program:
-- Step 1: Create the stored procedure
CREATE OR REPLACE PROCEDURE CalculateSum (
num1 IN INT,
num2 IN INT,
result OUT INT
) AS
BEGIN
-- Calculate the sum and store it in the OUT parameter
result := num1 + num2;
END;
/
-- Step 2: Declare a variable to store the result and call the procedure
DECLARE
sum_result INT;
BEGIN
-- Call the procedure with input parameters (5 and 10)
CalculateSum(5, 10, sum_result);
Output:
Procedure created.
Statement processed.
The sum is: 15
EXPERIMENT NO:9
Description:
1. Create Stored Functions: We will create some stored functions that perform
calculations or operations.
2. Invoke Functions in SQL Statements: We will show how to invoke these functions in
SQL queries.
3. Write Complex Functions: We will write a more complex function that includes loops,
conditional logic, and multiple operations.
We will create a function to calculate a discount for a product price based on a percentage. If
the price exceeds a certain value (e.g., 1000), we apply a higher discount (e.g., 20%).
Otherwise, a 10% discount is applied.
product_name VARCHAR2(100),
price FLOAT
);
INSERT INTO products (product_id, product_name, price) VALUES (1, 'Laptop', 1200);
INSERT INTO products (product_id, product_name, price) VALUES (2, 'Phone', 800);
INSERT INTO products (product_id, product_name, price) VALUES (3, 'Tablet', 600);
RETURN FLOAT
IS
discount_amount FLOAT;
BEGIN
-- Simple condition to apply higher discount if price exceeds 1000
ELSE
discount_percentage := 10; -- Apply 10% discount if price is less than or equal to 1000
END IF;
RETURN discount_amount;
END;
-- Use the CalculateDiscount function in a query to calculate the discount for each product
SELECT
product_id,
product_name,
price,
FROM
products;
output: