0% found this document useful (0 votes)
24 views18 pages

Dbms EXPERIMENT NO-4,5,6,7,8,9

The document outlines various SQL and PL/SQL functions including conversion, string manipulation, date functions, and mathematical operations. It also describes how to create a simple PL/SQL program with exception handling, data insertion, and transaction control using COMMIT, ROLLBACK, and SAVEPOINT. Additionally, it covers advanced programming concepts like nested IF statements, CASE expressions, NULLIF, and COALESCE functions, along with examples demonstrating their usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views18 pages

Dbms EXPERIMENT NO-4,5,6,7,8,9

The document outlines various SQL and PL/SQL functions including conversion, string manipulation, date functions, and mathematical operations. It also describes how to create a simple PL/SQL program with exception handling, data insertion, and transaction control using COMMIT, ROLLBACK, and SAVEPOINT. Additionally, it covers advanced programming concepts like nested IF statements, CASE expressions, NULLIF, and COALESCE functions, along with examples demonstrating their usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

EXPERIMENT NO:4

4. AIM: Queries using Conversion functions (to_char, to_number and to_date),


stringfunctions (Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length,
substrand instr), date functions (Sysdate, next_day, add_months, last_day,
months_between,least, greatest, trunc, round, to_char, to_date)

DATE AND NUMBER FORMATTING FUNCTIONS

1. FORMAT CURRENT DATE

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY') AS FORMATTEDDATE FROM DUAL;

o DEFINITION: CONVERTS THE CURRENT SYSTEM DATE (SYSDATE) INTO A


STRING IN THE FORMAT DD-MON-YYYY (E.G., 06-FEB-2025).
o OUTPUT:

FORMATTEDDATE
-------------
06-FEB-2025

2. CONVERT STRING TO NUMBER

SELECT TO_NUMBER('12345') AS NUMERICVALUE FROM DUAL;

o DEFINITION: CONVERTS THE STRING '12345' INTO A NUMERIC VALUE.


o OUTPUT:

NUMERICVALUE
------------
12345

3. CONVERT STRING TO DATE

SELECT TO_DATE('2025-02-06', 'YYYY-MM-DD') AS DATEVALUE FROM DUAL;

o DEFINITION: CONVERTS A STRING '2025-02-06' INTO A DATE TYPE.


o OUTPUT:

DATEVALUE
---------
06-FEB-25

STRING FUNCTIONS

4. CONCATENATION

SELECT CONCAT('HELLO', ' WORLD') AS CONCATENATEDTEXT FROM DUAL;


o DEFINITION: JOINS 'HELLO' AND ' WORLD' INTO A SINGLE STRING.
o OUTPUT:

CONCATENATEDTEXT
----------------
HELLO WORLD

5. PADDING

SELECT LPAD('123', 5, '0') AS LEFTPADDED, RPAD('123', 5, '0') AS RIGHTPADDED FROM DUAL;

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

SELECT LTRIM(' HELLO') AS LEFTTRIMMED, RTRIM('HELLO ') AS RIGHTTRIMMED FROM DUAL;

o DEFINITION:
 LTRIM REMOVES LEADING SPACES.
 RTRIM REMOVES TRAILING SPACES.
o OUTPUT:

LEFTTRIMMED RIGHTTRIMMED
----------- ------------
HELLO HELLO

7. CASE CONVERSION

SELECT LOWER('HELLO'), UPPER('HELLO'), INITCAP('HELLO WORLD') AS PROPERCASE FROM DUAL;

o DEFINITION:
 LOWER CONVERTS TO LOWERCASE ('HELLO').
 UPPER CONVERTS TO UPPERCASE ('HELLO').
 INITCAP CAPITALIZES EACH WORD ('HELLO WORLD').
o OUTPUT:

LOWER UPPER PROPERCASE


----- ----- ----------
HELLO HELLO HELLO WORLD
8. STRING LENGTH AND SUBSTRING

SELECT LENGTH('HELLO WORLD') AS STRINGLENGTH, SUBSTR('HELLO WORLD', 1, 5) AS SUBSTRING


FROM DUAL;

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

9. FIND POSITION OF A CHARACTER

SELECT INSTR('HELLO WORLD', 'O') AS POSITION FROM DUAL;

o DEFINITION: RETURNS THE POSITION OF THE FIRST OCCURRENCE OF 'O' IN


'HELLO WORLD' (5).
o OUTPUT:

POSITION
--------
5

DATE FUNCTIONS

10. GET CURRENT DATE AND NEXT MONDAY

SELECT SYSDATE AS CURRENTDATE, NEXT_DAY(SYSDATE, 'MONDAY') AS NEXTMONDAY FROM


DUAL;

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

11. ADD MONTHS AND FIND LAST DAY OF MONTH


SELECT ADD_MONTHS(SYSDATE, 3) AS THREEMONTHSLATER, LAST_DAY(SYSDATE) AS
LASTDAYOFMONTH FROM DUAL;

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

12. MONTHS BETWEEN TWO DATES

SELECT MONTHS_BETWEEN(SYSDATE, TO_DATE('2025-01-01', 'YYYY-MM-DD')) AS MONTHSBETWEEN


FROM DUAL;

o DEFINITION: COMPUTES THE FRACTIONAL MONTHS BETWEEN SYSDATE (FEB 6,


2025) AND 2025-01-01.
o OUTPUT:

MONTHSBETWEEN
-------------
1.19

MATHEMATICAL FUNCTIONS

13. FIND MINIMUM AND MAXIMUM VALUES

SELECT LEAST(10, 20, 5) AS SMALLEST, GREATEST(10, 20, 5) AS LARGEST FROM DUAL;

o DEFINITION:
 LEAST RETURNS THE SMALLEST VALUE (5).
 GREATEST RETURNS THE LARGEST VALUE (20).
o OUTPUT:

SMALLEST LARGEST
-------- -------
5 20

14. TRUNCATE AND ROUND DATES

SELECT TRUNC(SYSDATE, 'MONTH') AS TRUNCATEDDATE, ROUND(SYSDATE, 'MONTH') AS


ROUNDEDDATE FROM DUAL;

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:

CREATE TABLE student (


student_id NUMBER PRIMARY KEY,
name VARCHAR2(50),
marks NUMBER(5,2)
);
STEP2:

INSERT INTO student VALUES (101, 'Alice', 75);


INSERT INTO student VALUES (102, 'Bob', 55);
INSERT INTO student VALUES (103, 'Charlie', 88);
COMMIT;
STEP3:
DECLARE
CURSOR c_student IS
SELECT name, marks FROM student WHERE marks >= 60;

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;

EXIT WHEN c_student%NOTFOUND;

DBMS_OUTPUT.PUT_LINE('Name: ' || v_name || ', Marks: ' || v_marks);


v_count := v_count + 1;
END LOOP;

CLOSE c_student;

-- If no student found with first class


IF v_count = 0 THEN
RAISE no_data_found;
END IF;

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)

Input Data in student Table


SELECT * FROM student;
student_i mark
name
d s

101 Alice 75

102 Bob 55

Charli
103 88
e

Expected Output
Name: Alice, Marks: 75
Name: Charlie, Marks: 88

Scenario 2: When no students have first-class marks

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');

-- Savepoint after second insert


SAVEPOINT sp2;

-- Intentionally create an error (duplicate ID)


INSERT INTO student (student_id, name, marks) VALUES (105, 'Frank', 70);

-- Commit if all good


COMMIT;
DBMS_OUTPUT.PUT_LINE('Transaction Committed');

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:

Scenario 1: Successful Insert

If all inserts are successful, output will be:


Inserted: David
Inserted: Eve
Transaction Committed

Updated student Table


SELECT * FROM student;
student_i mark
name
d s

101 Alice 75

102 Bob 55

Charli
103 88
e

104 David 82

105 Eve 90

Scenario 2: Duplicate Student ID Error (Triggers Rollback to Savepoint)

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.

Updated student Table (After ROLLBACK TO sp2)


SELECT * FROM student;
student_i mark
name
d s

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

ELSEIF condition_2 THEN

-- statements

ELSE

-- statements

END IF;

2. CASE (Simple CASE Expression)

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

WHEN condition_1 THEN result_1

WHEN condition_2 THEN result_2

ELSE result_3

END

CASE Expression (Searched CASE Expression)


Definition:

 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

WHEN value_1 THEN result_1

WHEN value_2 THEN result_2

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:

COALESCE(expression_1, expression_2, ..., expression_n)

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

SELECT emp_id, emp_name, salary,


-- Using CASE to categorize salary (this replaces NESTED IF)
CASE
WHEN salary IS NULL THEN 'Salary Missing'
WHEN salary >= 5000 THEN 'High Salary'
WHEN salary BETWEEN 3000 AND 4999 THEN 'Average Salary'
ELSE 'Low Salary'
END AS salary_category,

-- Using CASE Expression for exact salary matching


CASE salary
WHEN 5000 THEN 'Exact 5000'
WHEN 6000 THEN 'Exact 6000'
ELSE 'Other Salary'
END AS salary_status,

-- Using NULLIF to return NULL if salary is 0


NULLIF(salary, 0) AS salary_if_not_zero,

-- Using COALESCE to replace NULL salary with 4000


COALESCE(salary, 4000) AS salary_with_default
FROM employees;

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;

-- While loop to sum odd numbers from 1 to endval


WHILE inval <= endval LOOP
s := s + inval; -- Add current odd number to the sum
inval := inval + 2; -- Move to the next odd number
END LOOP;

-- Output the result


DBMS_OUTPUT.PUT_LINE('Sum of odd numbers between 1 and ' || endval || ' is ' || s);
END;
/

OUTPUT: Statement processed.


Sum of odd numbers between 1 and 10 is 25

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);

-- Loop to print multiplication table


FOR VAR2 IN 1..10 LOOP
dbms_output.put_line(VAR1 || ' X ' || VAR2 || ' = ' || VAR1 * VAR2);
END LOOP;
END;
/

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;

-- Increment i to check the next number


i := i + 1;

-- Exit the outer loop when i reaches 50


EXIT WHEN i > 50;
END LOOP;
END;
/
OUTPUT:
Statement processed.
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
EXPERIMENT NO:8
AIM:Programs development using creation of procedures, passing parameters IN and OUT of
PROCEDURES

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 the result


DBMS_OUTPUT.PUT_LINE('The sum is: ' || sum_result);
END;
/

Output:
Procedure created.

Statement processed.
The sum is: 15
EXPERIMENT NO:9

AIM:Program development using creation of stored functions, invoke functions in SQL


Statements and write complex functions.

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.

-- Create the products table

CREATE TABLE products (

product_id INT PRIMARY KEY,

product_name VARCHAR2(100),

price FLOAT

);

-- Insert sample data into the products table

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);

-- Create a function to calculate a discount based on price

CREATE OR REPLACE FUNCTION CalculateDiscount(price IN FLOAT, discount_percentage IN


FLOAT)

RETURN FLOAT

IS

discount_amount FLOAT;

BEGIN
-- Simple condition to apply higher discount if price exceeds 1000

IF price > 1000 THEN

discount_percentage := 20; -- Apply 20% discount if price is greater than 1000

ELSE

discount_percentage := 10; -- Apply 10% discount if price is less than or equal to 1000

END IF;

-- Calculate the discount amount

discount_amount := price * (discount_percentage / 100);

-- Return the discount amount

RETURN discount_amount;

END;

-- Use the CalculateDiscount function in a query to calculate the discount for each product

SELECT

product_id,

product_name,

price,

CalculateDiscount(price, 0) AS discount_amount -- The second argument is just a


placeholder since the function overrides it

FROM

products;

output:

product_id product_name price


1 Laptop 1200
2 Phone 800
3 Tablet 600

The result of the query would be:

product_id product_name Price discount_amount


1 Laptop 1200 240
2 Phone 800 80
product_id product_name Price discount_amount
3 Tablet 600 60

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy