0% found this document useful (0 votes)
6 views15 pages

SQL PL SQL Queries q1 To q13

The document provides a comprehensive overview of SQL and PL/SQL queries, including examples of DDL, DML, and DCL commands, as well as advanced SQL operators and aggregate functions. It also covers PL/SQL programming concepts such as exception handling, transaction control, loops, cursors, procedures, functions, and triggers. Each section includes explanations and expected outputs to illustrate the concepts effectively.
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)
6 views15 pages

SQL PL SQL Queries q1 To q13

The document provides a comprehensive overview of SQL and PL/SQL queries, including examples of DDL, DML, and DCL commands, as well as advanced SQL operators and aggregate functions. It also covers PL/SQL programming concepts such as exception handling, transaction control, loops, cursors, procedures, functions, and triggers. Each section includes explanations and expected outputs to illustrate the concepts effectively.
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/ 15

SQL and PL/SQL Queries with Explanation and Expected Output

1. Simple Queries (DDL, DML, DCL commands)

DDL (Data Definition Language) is used to define and manage database structures such
as tables and indexes.

 Example - Creating a Table:

CREATE TABLE Students (


StudentID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
Gender VARCHAR(10)
);

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.

 Example - Inserting Data:

INSERT INTO Students (StudentID, Name, Age, Gender)


VALUES (1, 'John Doe', 21, 'Male');

Explanation: Adds a new student record to the "Students" table.

 Example - Updating Data:

UPDATE Students
SET Age = 23
WHERE StudentID = 1;
Explanation: Updates the age of the student with ID 1 to 23.

 Example - Deleting Data:

DELETE FROM Students


WHERE StudentID = 3;

Explanation: Deletes the student record with ID 3.

DCL (Data Control Language) is used to control access to data in the database.

 Example - Granting Permissions:

GRANT SELECT, INSERT ON Students TO user_name;

Explanation: Grants SELECT and INSERT privileges on the "Students" table to a


specific user.

 Example - Revoking Permissions:

REVOKE INSERT ON Students FROM user_name;

Explanation: Revokes the INSERT privilege from the user.

Expected Output:

After insertion and update:


| StudentID | Name | Age | Gender |
|-----------|-------------|-----|--------|
|1 | John Doe | 23 | Male |
|2 | Jane Smith | 20 | Female |

After deletion of StudentID 3, only remaining students will be displayed.


2. Creating, Altering, and Dropping Tables

This section covers how to create, alter, and drop tables in SQL.

 Example - Creating a Table with Constraints:

CREATE TABLE Employees (


EmpID INT PRIMARY KEY,
EmpName VARCHAR(50) NOT NULL,
Department VARCHAR(50),
Salary DECIMAL(10, 2) CHECK (Salary > 0)
);

Explanation: This creates a table "Employees" with constraints to ensure salary is greater
than 0 and that "EmpID" is unique.

 Example - Altering a Table:

ALTER TABLE Employees ADD Email VARCHAR(50);

Explanation: Adds a new column "Email" to the "Employees" table.

 Example - Dropping a Table:

DROP TABLE Employees;

Explanation: Permanently removes the "Employees" table from the database.

Expected Output:

After creating and inserting data:


| EmpID | EmpName | Department | Salary |
|-------|---------|------------|----------|
| 101 | Alice | HR | 15000.00 |
| 102 | Bob | IT | 18000.00 |
| 103 | Charlie | Finance | 12000.00 |
After altering, a new column "Email" is added.
After dropping, the table "Employees" no longer exists.

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.

 Example - Using ANY:

SELECT * FROM Employees


WHERE Salary > ANY (SELECT Salary FROM Employees WHERE Department =
'HR');

Explanation: Returns employees with salary greater than any one of the salaries in the HR
department.

 Example - Using IN:

SELECT * FROM Employees


WHERE Department IN ('HR', 'IT');

Explanation: Retrieves all employees from the HR or IT departments.

 Example - Using EXISTS:

SELECT * FROM Employees


WHERE EXISTS (SELECT 1 FROM Employees WHERE Department = 'Finance');

Explanation: Returns all employees if at least one employee exists in the Finance
department.

 Example - Using UNION:

SELECT EmpName FROM Employees WHERE Department = 'HR'


UNION
SELECT EmpName FROM Employees WHERE Department = 'IT';

Explanation: Combines the names of employees from HR and IT departments, removing


duplicates.

 Example - Using INTERSECT:

SELECT EmpName FROM Employees WHERE Department = 'HR'


INTERSECT
SELECT EmpName FROM Employees WHERE Salary > 10000;

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:

| EmpID | EmpName | Department | Salary |


|-------|---------|------------|----------|
| 101 | Alice | HR | 15000.00 |
| 102 | Bob | IT | 18000.00 |
| 103 | Charlie | Finance | 12000.00 |
| 104 | David | IT | 16000.00 |

ANY: Returns Bob, Charlie, David (salary > any in HR).


IN: Returns Alice, Bob, David.
EXISTS: Returns all employees if Finance has at least one member.
UNION: Alice, Bob, David (distinct names).
INTERSECT: Alice (in HR and salary > 10000).

4. Aggregate Functions, GROUP BY, HAVING, Views

This section demonstrates how to summarize and group data using aggregate functions,
and how to create and use views.

 Example - Using Aggregate Functions:


SELECT COUNT(EmpID) AS TotalEmployees, AVG(Salary) AS AverageSalary,
SUM(Salary) AS TotalSalary, MAX(Salary) AS MaxSalary, MIN(Salary) AS
MinSalary
FROM Employees;

Explanation: Calculates the total number of employees, average salary, total salary,
maximum salary, and minimum salary.

 Example - Using GROUP BY and HAVING:

SELECT Department, COUNT(EmpID) AS NumEmployees, AVG(Salary) AS


AvgSalary
FROM Employees
GROUP BY Department
HAVING AVG(Salary) > 15000;

Explanation: Groups employees by department and displays departments where average


salary is greater than 15000.

 Example - Creating a View:

CREATE VIEW HighSalaryEmployees AS


SELECT EmpName, Salary FROM Employees WHERE Salary > 15000;

Explanation: Creates a virtual table containing employees with salary greater than 15000.

 Example - Selecting from a View:

SELECT * FROM HighSalaryEmployees;

Explanation: Retrieves all data from the view "HighSalaryEmployees".

Expected Output:

Assuming the Employees table contains:

| EmpID | EmpName | Department | Salary |


|-------|---------|------------|----------|
| 101 | Alice | HR | 15000.00 |
| 102 | Bob | IT | 18000.00 |
| 103 | Charlie | Finance | 12000.00 |
| 104 | David | IT | 16000.00 |

Aggregate Output:
| TotalEmployees | AverageSalary | TotalSalary | MaxSalary | MinSalary |
|----------------|---------------|-------------|-----------|-----------|
|4 | 15250.00 | 61000.00 | 18000.00 | 12000.00 |

GROUP BY Output (departments with AvgSalary > 15000):


| Department | NumEmployees | AvgSalary |
|------------|---------------|-----------|
| IT |2 | 17000.00 |

View Output:
| EmpName | Salary |
|---------|---------|
| Bob | 18000.00|
| David | 16000.00|

5. Conversion, String, and Date Functions

This section demonstrates how to use SQL functions for data conversion, string
manipulation, and date operations.

 Example - TO_CHAR (Date to String):

SELECT TO_CHAR(SYSDATE, 'DD-MM-YYYY') AS CurrentDate FROM DUAL;

Explanation: Converts the current system date to a string in DD-MM-YYYY format.

 Example - TO_NUMBER (String to Number):

SELECT TO_NUMBER('123.45') AS ConvertedNumber FROM DUAL;


Explanation: Converts the string '123.45' into a numeric format.

 Example - TO_DATE (String to Date):

SELECT TO_DATE('10-04-2025', 'DD-MM-YYYY') AS ConvertedDate FROM DUAL;

Explanation: Converts the string '10-04-2025' into a DATE format using the specified
pattern.

 Example - UPPER, LOWER, LENGTH, INITCAP:

SELECT
UPPER('oracle') AS UpperCase,
LOWER('ORACLE') AS LowerCase,
LENGTH('Oracle') AS Length,
INITCAP('john doe') AS InitCap
FROM DUAL;

Explanation: Demonstrates various string functions for case conversion, measuring


length, and capitalizing words.

 Example - SYSDATE, NEXT_DAY, ADD_MONTHS, LAST_DAY:

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 |

String Functions Output:


| UpperCase | LowerCase | Length | InitCap |
|-----------|-----------|--------|-----------|
| ORACLE | oracle | 6 | John Doe |

Date Functions Output (Example):


| Today | NextMonday | NextMonth | MonthEnd |
|--------------------|--------------------|---------------------|--------------------|
| 10-APR-25 10:30:00 | 14-APR-25 00:00:00 | 10-MAY-25 10:30:00 | 30-APR-25
00:00:00 |

6. Simple PL/SQL Program

PL/SQL is Oracle's procedural extension to SQL. It allows embedding procedural logic


within SQL using variables, loops, and conditions.

 Example - Display Employee Name Using SELECT INTO:

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:

Employee Name: Alice

7. Exception Handling in PL/SQL

PL/SQL provides exception handling to manage run-time errors gracefully using


predefined and user-defined exceptions.

 Example - Handling NO_DATA_FOUND Exception:

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.

8. COMMIT, ROLLBACK, and SAVEPOINT in PL/SQL

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.

 Example - Using COMMIT, ROLLBACK, SAVEPOINT:

BEGIN
INSERT INTO Employees (EmpID, EmpName, Department, Salary)
VALUES (104, 'David', 'IT', 16000);

SAVEPOINT BeforeSecondInsert;

INSERT INTO Employees (EmpID, EmpName, Department, Salary)


VALUES (105, 'Eva', 'HR', 14000);

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.

| EmpID | EmpName | Department | Salary |


|-------|---------|------------|----------|
| 104 | David | IT | 16000.00 |

9. Nested IF, CASE, and CASE Expressions

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.

 Example - Using Nested IF:


DECLARE
v_salary NUMBER := 9000;
v_bonus NUMBER;
BEGIN
IF v_salary > 15000 THEN
v_bonus := v_salary * 0.10;
ELSIF v_salary > 10000 THEN
v_bonus := v_salary * 0.07;
ELSE
v_bonus := v_salary * 0.05;
END IF;
DBMS_OUTPUT.PUT_LINE('Bonus: ' || v_bonus);
END;

Explanation: Determines bonus based on salary using nested IF conditions.

Expected Output:

Bonus: 450.0

10. Loops and Exception Handling in PL/SQL

Loops in PL/SQL allow executing a block of code multiple times. When combined with
exception handling, it enables robust and controlled iterative processing.

 Example - WHILE Loop with DBMS_OUTPUT:

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

11. Cursor Example in PL/SQL

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.

 Example - Using Explicit Cursor:

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:

Name: Alice, Salary: 15000


Name: Bob, Salary: 18000
Name: Charlie, Salary: 12000
Name: David, Salary: 16000
12. Procedures and Functions in PL/SQL

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.

 Example - Creating a Procedure to Raise Salary:

CREATE OR REPLACE PROCEDURE RaiseSalary (


p_EmpID IN NUMBER,
p_Percent IN NUMBER
) AS
BEGIN
UPDATE Employees
SET Salary = Salary + (Salary * p_Percent / 100)
WHERE EmpID = p_EmpID;
DBMS_OUTPUT.PUT_LINE('Salary Updated.');
END;

Explanation: This procedure increases the salary of an employee by a given percentage.

 Example - Calling the Procedure:

BEGIN
RaiseSalary(101, 10);
END;

Explanation: Calls the RaiseSalary procedure for employee 101 with a 10% increment.

Expected Output:

Salary Updated.

13. Triggers in PL/SQL

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:

CREATE OR REPLACE TRIGGER PreventSalaryReduction


BEFORE UPDATE OF Salary ON Employees
FOR EACH ROW
BEGIN
IF :NEW.Salary < :OLD.Salary THEN
RAISE_APPLICATION_ERROR(-20001, 'Salary reduction is not allowed!');
END IF;
END;

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:

ORA-20001: Salary reduction is not allowed!

You might also like