SQL PL SQL Queries q1 To q13
SQL PL SQL Queries q1 To q13
DDL (Data Definition Language) is used to define and manage database structures such
as tables and indexes.
Explanation: This creates a table named "Students" with four columns. "StudentID" is the
primary key.
DML (Data Manipulation Language) is used to manage data within schema objects.
UPDATE Students
SET Age = 23
WHERE StudentID = 1;
Explanation: Updates the age of the student with ID 1 to 23.
DCL (Data Control Language) is used to control access to data in the database.
Expected Output:
This section covers how to create, alter, and drop tables in SQL.
Explanation: This creates a table "Employees" with constraints to ensure salary is greater
than 0 and that "EmpID" is unique.
Expected Output:
3. Queries using ANY, ALL, IN, EXISTS, NOT EXISTS, UNION, INTERSECT,
Constraints
This section includes queries that use advanced SQL operators to filter and combine data.
Explanation: Returns employees with salary greater than any one of the salaries in the HR
department.
Explanation: Returns all employees if at least one employee exists in the Finance
department.
Explanation: Returns the names of employees who are both in HR and have salary greater
than 10000.
Expected Output:
For the above queries, assuming the Employees table has the following data:
This section demonstrates how to summarize and group data using aggregate functions,
and how to create and use views.
Explanation: Calculates the total number of employees, average salary, total salary,
maximum salary, and minimum salary.
Explanation: Creates a virtual table containing employees with salary greater than 15000.
Expected Output:
Aggregate Output:
| TotalEmployees | AverageSalary | TotalSalary | MaxSalary | MinSalary |
|----------------|---------------|-------------|-----------|-----------|
|4 | 15250.00 | 61000.00 | 18000.00 | 12000.00 |
View Output:
| EmpName | Salary |
|---------|---------|
| Bob | 18000.00|
| David | 16000.00|
This section demonstrates how to use SQL functions for data conversion, string
manipulation, and date operations.
Explanation: Converts the string '10-04-2025' into a DATE format using the specified
pattern.
SELECT
UPPER('oracle') AS UpperCase,
LOWER('ORACLE') AS LowerCase,
LENGTH('Oracle') AS Length,
INITCAP('john doe') AS InitCap
FROM DUAL;
SELECT
SYSDATE AS Today,
NEXT_DAY(SYSDATE, 'MONDAY') AS NextMonday,
ADD_MONTHS(SYSDATE, 1) AS NextMonth,
LAST_DAY(SYSDATE) AS MonthEnd
FROM DUAL;
Explanation: Performs operations on date values such as getting the next Monday, next
month’s date, and the last day of the month.
Expected Output:
TO_CHAR Output:
| CurrentDate |
|-------------|
| 10-04-2025 |
TO_NUMBER Output:
| ConvertedNumber |
|-----------------|
| 123.45 |
TO_DATE Output:
| ConvertedDate |
|----------------------|
| 10-APR-25 00:00:00 |
DECLARE
v_name Employees.EmpName%TYPE;
BEGIN
SELECT EmpName INTO v_name FROM Employees WHERE EmpID = 101;
DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_name);
END;
Explanation: This block declares a variable v_name, retrieves the name of the employee
with ID 101, and prints it using DBMS_OUTPUT.
Expected Output:
DECLARE
v_salary Employees.Salary%TYPE;
BEGIN
SELECT Salary INTO v_salary FROM Employees WHERE EmpID = 999; -- Invalid
ID
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No Employee Found.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred.');
END;
Explanation: This block attempts to fetch salary for an employee who does not exist
(EmpID = 999), triggering the NO_DATA_FOUND exception, which is then handled
with a custom message.
Expected Output:
No Employee Found.
Transaction control statements in PL/SQL are used to manage changes made by DML
statements. COMMIT makes changes permanent, ROLLBACK undoes changes, and
SAVEPOINT marks a point to which you can roll back.
BEGIN
INSERT INTO Employees (EmpID, EmpName, Department, Salary)
VALUES (104, 'David', 'IT', 16000);
SAVEPOINT BeforeSecondInsert;
ROLLBACK TO BeforeSecondInsert;
COMMIT;
END;
Explanation: This block inserts two records but rolls back only the second one (Eva) to a
savepoint, then commits the remaining transaction.
Expected Output:
Only the record for David (EmpID = 104) will be committed. The record for Eva (EmpID
= 105) is rolled back.
Conditional statements in PL/SQL allow the execution of different blocks of code based
on conditions. The IF...ELSIF...ELSE construct and the CASE statement are commonly
used.
Expected Output:
Bonus: 450.0
Loops in PL/SQL allow executing a block of code multiple times. When combined with
exception handling, it enables robust and controlled iterative processing.
DECLARE
i NUMBER := 1;
BEGIN
WHILE i <= 3 LOOP
DBMS_OUTPUT.PUT_LINE('Iteration: ' || i);
i := i + 1;
END LOOP;
END;
Explanation: This block uses a WHILE loop to print iteration numbers from 1 to 3.
Expected Output:
Iteration: 1
Iteration: 2
Iteration: 3
Cursors in PL/SQL are used to retrieve multiple rows from a SELECT query one row at a
time. They are especially useful for processing each row individually.
DECLARE
CURSOR emp_cursor IS SELECT EmpName, Salary FROM Employees;
v_name Employees.EmpName%TYPE;
v_salary Employees.Salary%TYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO v_name, v_salary;
EXIT WHEN emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Name: ' || v_name || ', Salary: ' || v_salary);
END LOOP;
CLOSE emp_cursor;
END;
Explanation: This block declares a cursor to fetch name and salary from the Employees
table and processes each row inside a loop.
Expected Output:
Procedures and functions are named PL/SQL blocks that perform specific tasks.
Procedures may or may not return a value, while functions must return a value.
BEGIN
RaiseSalary(101, 10);
END;
Explanation: Calls the RaiseSalary procedure for employee 101 with a 10% increment.
Expected Output:
Salary Updated.
Triggers are special PL/SQL blocks that are automatically executed (or "fired") when
certain events occur, such as INSERT, UPDATE, or DELETE on a table.
Example - BEFORE UPDATE Trigger to Prevent Salary Reduction:
Explanation: This trigger prevents updating the salary to a lower value. It raises an error
if the new salary is less than the old salary.
Expected Output:
If someone tries to reduce the salary of an employee, the following error will be raised: