SQL Notes
SQL Notes
🎯 Course Goal:
To introduce learners to Oracle SQL, enabling them to write queries, manipulate data, and understand
Oracle-specific database features.
📘 Key Topics:
1. Introduction to Oracle SQL
○ SQL vs PL/SQL
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
○ DUAL table
○ ROWNUM, SYSDATE
✅ Outcome:
By the end, learners will be able to:
💾 1. Database
● A database is a structured collection of interrelated data.
● Example: A database might store customer details, sales data, or employee records.
👉 Think of a DBMS as the manager of the warehouse (database), handling everything inside.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
👉 Think of SQL as the instructions or commands you give to the DBMS manager to get work done in
the warehouse.
🧱 Types of DBMS
DBMSs are categorized based on how they store and manage data. There are four main types:
● Characteristics:
● Characteristics:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● Characteristics:
🧠 Think of: A social network where one person can be connected to many people.
4. 📊 Relational DBMS (RDBMS)
● Structure: Table format (rows and columns).
● Characteristics:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🧠 Simple Definition:
"Metadata is data about data."
📄 A Word Document File name, author, word count, creation date, file size
📷 A Photo Camera model, resolution, date taken, GPS location, file format
📊 A Table in a Database Table name, column names, data types, primary key, row count
Actual Data:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Metadata:
📌 This metadata tells how the data is stored and how it can be used, but not the data itself.
✅ How to Install Oracle Database (Step-by-Step Guide)
Here’s a beginner-friendly guide to installing Oracle Database on your system. This covers the Oracle
Database 21c or 19c Express Edition (XE), which is free and ideal for learning purposes.
3.Click “Download”, accept the license agreement, and sign in or create an Oracle account.
3. Installation Complete
○ Oracle Listener
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
○ Oracle SQL*Plus
bash
○ Username: system
○ Hostname: localhost
○ Port: 1521
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🚀 You're Ready!
Now you can start creating tables, writing queries, and learning Oracle SQL!
📘 Sub-Languages in SQL
SQL (Structured Query Language) is divided into five main sub-languages, each serving a specific
function in interacting with the database.
DML (Data Manipulation Manipulate data INSERT, UPDATE, INSERT INTO dept
Language) DELETE VALUES (1, 'HR');
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Datatypes:
● They help Oracle enforce rules like constraints, sorting, and indexing.
4.Large Object (LOB) Datatypes – Store large data like files or documents.
5.Long and raw datatype – Stores very large text data (like long descriptions or articles).
🔢 Numeric Datatypes
Oracle provides several numeric datatypes to store numbers—both integers and floating-point numbers.
Here's a breakdown:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✅ 1. NUMBER
The most commonly used numeric datatype.
sql
NUMBER(p, s)
Example Description
NUMBER(8,2) 6 digits before the decimal, 2 after ● These are just different
names for whole numbers.
NUMBER(*,0) Any number with 0 digits after ● All are the same as
decimal (integer) NUMBER without decimal part.
Example:
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✅ 3. FLOAT
Stores approximate numeric values.
sql
FLOAT(p)
Example Description
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✔ Use these for performance-critical calculations where approximate values are acceptable.
🔤 Character Datatypes
These are used to store text — like names, addresses, or messages.
✅ 1. CHAR(n)
● Stores fixed-length text.
Example:
sql
CHAR(5)
-- 'Hi' is stored as 'Hi '
✅ 2. VARCHAR2(n)
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Example:
sql
VARCHAR2(5)
-- 'Hi' is stored as 'Hi'
✅ 3. NCHAR(n)
● Like CHAR, but supports Unicode (multi-language).
✅ 4. NVARCHAR2(n)
● Like VARCHAR2, but supports Unicode.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
These are used to store dates and times, like birth dates, timestamps, or event times.
✅ 1. DATE
● Stores date and time (year, month, day, hour, minute, second).
Example:
sql
DATE
-- '08-JUL-2025 10:30:00'
✅ 2. TIMESTAMP
● Like DATE but also stores fractions of a second.
● Example:
sql
TIMESTAMP
-- '08-JUL-2025 10:30:00.123456
Example:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
INTERVAL '2-6' YEAR TO MONTH
-- 2 years and 6 months
Example:
sql
INTERVAL '3 04:30:15' DAY TO SECOND
-- 3 days, 4 hours, 30 minutes, 15 seconds
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔍 Explanation of Each:
1. CLOB (Character Large Object)
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● Purpose: Stores very large text data (like long descriptions or articles).
● Limitations:
sql
book_id NUMBER,
summary LONG
);
[Link] Datatype
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● Purpose: Stores binary data, not readable as text (like images, encrypted data).
● Type: Binary
Example:
sql
file_id NUMBER,
file_data RAW(1000)
);
✅ Summary Table
Datatype Type Stores Max Status Modern Alternative
Size
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
○ Block number
○ File number
✅ Key Points:
● Each row in a table has a unique ROWID.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● Used especially for tables with object types or index-organized tables (IOTs).
Why UROWID?
● UROWID can also handle rows that don’t have a fixed physical location, such as:
○ Rows in IOTs
🔹 What is DDL
In SQL (Structured Query Language), DDL stands for Data Definition Language. It's one of the key
sublanguages of SQL, used to define and manage the structure of database objects such as tables, indexes,
DDL commands create, modify, and delete database structures—but not the data stored in them.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Flashback Used to recover data from a previous point in time without restoring from backup.
TRUNCATE Removes all rows from a table quickly, without logging individual row deletions.
CREATE
⁕Syntax:
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
...
);
⁕Example:
sql
Name VARCHAR(50),
Age INT
);
Notes: Defines the structure (columns, datatypes, constraints) of a new table or other object.
Fails if the object already exists unless specified otherwise (e.g., IF NOT EXISTS).
ALTER
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
⁕Syntax:
sql
EXAMPLES:
⁕Add a column:
sql
sql
⁕Drop a column:
sql
⁕Rename a column:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
TRUNCATE
● Purpose: Removes all rows from a table, resetting it to an empty state while
preserving its structure (columns, constraints, indexes).
● Syntax:
sql
⁕Example:
sql
RENAME
● Purpose: Changes the name of an existing database object, such as a table or column.
● Syntax (varies by database):
⁕For tables:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
sql
DROP
● Definition: Removes a database object (e.g., table, index, schema) from the database.
● Why DDL?: Modifies the database structure by deleting object metadata.
⁕Syntax:
sql
⁕Example:
sql
Deletes the Students table, moving it to the recycle bin (in Oracle, if enabled).
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
FLASHBACK
⁕Syntax:
sql
or
sql
⁕EXAMPLE:
sql
PURGE
● Definition: Permanently deletes a dropped object or clears the recycle bin, preventing
recovery (Oracle-specific).
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
⁕Syntax:
sql
or
sql
PURGE RECYCLEBIN;
⁕Example:
sql
🔹 What is DML
Data Manipulation Language (DML) in SQL refers to a set of commands used to manipulate
data within a database's tables. Unlike Data Definition Language (DDL), which manages
database structure (e.g., tables, schemas), DML focuses on inserting, updating, deleting, and
retrieving data in tables.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
INSERT
INSERT is a DML command that adds one or more rows of data to a specified table in a
database.
Syntax
sql
INSERT INTO table_name (column1, column2, ..., columnN)
VALUES (value1, value2, ..., valueN);
✅ Example:
Suppose you have a table called employees:
sql
CREATE TABLE employees (
employee_id NUMBER,
first_name VARCHAR2(50),
last_name VARCHAR2(50),
hire_date DATE,
salary NUMBER
);
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
INSERT INTO employees (employee_id, first_name, last_name, hire_date, salary)
VALUES (101, 'John', 'Doe', TO_DATE('2025-07-10', 'YYYY-MM-DD'), 50000);
If you're inserting values into all columns in the correct order, you can omit the column list:
sql
INSERT INTO employees
VALUES (102, 'Jane', 'Smith', TO_DATE('2025-07-01', 'YYYY-MM-DD'), 60000);
Example :
sql
Example :
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Update
In Oracle SQL, the UPDATE statement is a DML (Data Manipulation Language) command
used to modify existing records in a table.
Syntax:
sql
UPDATE table_name
SET column1 = value1,
column2 = value2,
...
WHERE condition;
🔸 Important: Always use a WHERE clause to avoid updating all rows unless that is your
intention.
Example:
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Commit:
The COMMIT statement is used to permanently save those changes to the database.
Syntax:
sql
UPDATE table_name
SET column1 = value1,
column2 = value2
WHERE condition;
COMMIT;
Delete
In SQL, the DELETE statement is a DML (Data Manipulation Language) command used to remove one
or more rows from a table.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
WHERE condition;
🔴 Important: Always use a WHERE clause unless you want to delete all rows from the table.
Example:
sql
employee_id NUMBER,
first_name VARCHAR2(50),
last_name VARCHAR2(50),
department VARCHAR2(50)
);
sql
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
🔔 This deletes all rows from the table but keeps the table itself.
Example 4: Use with COMMIT
sql
COMMIT;
Insert all
In SQL, INSERT ALL is a DML statement that allows you to insert multiple rows into one or more
tables using a single SQL statement. It is very useful when you want to insert multiple records efficiently.
INSERT ALL
...
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔸 DUAL is a special one-row, one-column table used in Oracle when a SELECT is required
syntactically.
sql
INSERT ALL
✅ This inserts three rows into the employees table in one SQL command.
Insert into Multiple Tables (Advanced Usage)
sql
INSERT ALL
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔹 Key Notes
● INSERT ALL is not the same as BULK INSERT or INSERT INTO ... SELECT.
● Use INSERT FIRST if you want to insert into only one table based on conditions (first match
only).
● You must use SELECT * FROM dual at the end, even if inserting hardcoded values.
sql
INSERT ALL
FROM source_table
WHERE condition;
🔸 The subquery pulls data from a source table and the INSERT ALL pushes the same data (or
different parts of it) into one or more destination tables.
Merge
In Oracle SQL, the MERGE statement is a DML command used to combine INSERT and UPDATE
(or DELETE) in a single operation.
It's also called "UPSERT", because it will insert new rows or update existing rows depending on whether a
match is found.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
USING source_table s
ON (t.key_column = s.key_column)
Example Tables:
sql
-- Target table
name VARCHAR2(50),
salary NUMBER
);
-- Source table
emp_id NUMBER,
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
name VARCHAR2(50),
salary NUMBER
);
sql
USING new_employees n
ON (e.emp_id = n.emp_id)
[Link] = [Link]
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
CopyEdit
CREATE TABLE employees (
emp_id NUMBER,
first_name VARCHAR2(50),
last_name VARCHAR2(50),
department VARCHAR2(50),
salary NUMBER
);
With data:
sql
CopyEdit
INSERT INTO employees VALUES (101, 'Alice', 'Smith', 'HR', 50000);
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Operators in sql
+, -, *, /
||
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
1. + (Addition)
sql
SELECT salary, salary + 1000 AS increased_salary
FROM employees;
🔹 2. - (Subtraction)
Subtracts the second number from the first.
sql
SELECT salary, salary - 500 AS adjusted_salary
FROM employees;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔹 3. * (Multiplication)
Multiplies two numbers.
sql
SELECT salary, salary * 2 AS double_salary
FROM employees;
🔹 4. / (Division)
Divides the first number by the second.
sql
SELECT salary, salary / 2 AS half_salary
FROM employees;
🔹 Combined Example
You can use multiple arithmetic operators in the same query:
sql
SELECT
salary,
salary + 1000 - 200 AS bonus_adjusted_salary,
salary * 1.1 AS salary_with_10_percent_raise,
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
salary / 12 AS monthly_salary
FROM employees;
✅ This query:
● Adds 1000 and subtracts 200 (bonus logic),
1. Equality
sql
SELECT * FROM employees
WHERE department_id = 10;
2. Not Equal
sql
SELECT * FROM employees
WHERE job_id <> 'IT_PROG';
3. Greater Than
sql
SELECT * FROM employees
WHERE salary > 6000;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔹 1. AND
● Returns TRUE if both conditions are true.
Example:
sql
SELECT * FROM employees
WHERE department_id = 10 AND salary > 5000;
🔹 2. OR
● Returns TRUE if either condition is true.
Example:
sql
SELECT * FROM employees
WHERE department_id = 10 OR salary > 5000;
🔹 3. NOT
● Negates a condition; returns TRUE if the condition is false.
Example:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
SELECT * FROM employees
WHERE NOT department_id = 10;
Example:
sql
SELECT * FROM employees
WHERE department_id IN (10, 20, 30);
Note: Be careful with IN and NULL — if the list contains NULL, the result may be unknown.
Example:
sql
3. LIKE
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Example:
sql
Example:
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
UNION ALL Combines all results from two queries including duplicates
MINUS Returns rows from the first query that are not in the second
4.Set operators must appear outside of subqueries, not inside them directly.
UNION
UNION ALL
INTERSECT
MINUS
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✅ Syntax:
sql
string1 || string2 [|| string3 ...]
sql
Result:
markdown
GREETING
---------
Hello World
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Command Description
COMMIT Saves all changes made in the transaction to the database permanently
SAVEPOINT Sets a point within a transaction to which you can later roll back
1. COMMIT
✅ Example:
sql
COMMIT;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
2. ROLLBACK
Cancels all changes made in the current transaction (since the last COMMIT or SAVEPOINT).
✅ Example:
sql
ROLLBACK;
3. SAVEPOINT
Creates a named point in a transaction you can roll back to without undoing the entire transaction.
✅ Example:
sql
SAVEPOINT sp1;
SAVEPOINT sp2;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
SAVEPOINT after_alice_deduction;
-- Oops! Let's say there's a mistake (e.g., wrong account or wrong amount)
ROLLBACK TO after_alice_deduction;
-- Now fix the mistake and re-add the correct amount to Bob
COMMIT;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Step Action
● Bob: 1700
🛑 Note:
If you had used ROLLBACK without a savepoint, both updates (to Alice and Bob) would have been
undone.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Command Description
✅ Syntax:
sql
GRANT privilege_type ON object TO user_or_role;
✅ This allows hr_user to select and insert into the employees table.
sql
GRANT CREATE SESSION TO hr_user;
✅ Syntax:
sql
REVOKE privilege_type ON object FROM user_or_role;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
⚠️ Notes:
● Only a DBA or a user with GRANT ANY PRIVILEGE can grant system privileges.
● Revoking a privilege with WITH GRANT OPTION can cascade and remove access from users
who received it indirectly.
🔹 GROUP BY
In SQL, the GROUP BY clause is used to aggregate data based on one or more columns. It groups rows
that have the same values in specified columns into summary rows, typically in combination with
aggregate functions like SUM(), COUNT(), AVG(), MAX(), or MIN().
🔹 Syntax
sql
SELECT column1, column2, AGGREGATE_FUNCTION(column3)
FROM table_name
GROUP BY column1, column2;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
1 Math 85
1 English 78
2 Math 92
2 English 81
3 Math 75
3 English 88
sql
FROM marks
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
GROUP BY student_id;
Output:
student_id total_marks
1 163
2 173
3 163
sql
FROM marks
GROUP BY subject;
Output:
subject avg_marks
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Math 84.0
English 82.3
sql
FROM marks
GROUP BY subject;
Output:
subject student_count
Math 3
English 3
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
GROUP BY subject
HAVING AVG(marks) > 83;
Output:
subject avg_marks
Math 84.0
🎓 Table: marks
student_id subject marks semester
1 Math 85 1
1 English 78 1
2 Math 92 1
2 English 81 1
3 Math 75 2
3 English 88 2
4 Math 60 2
4 English 72 2
🔹 SQL Query:
sql
SELECT subject, AVG(marks) AS avg_marks
FROM marks
WHERE semester = 1
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
GROUP BY subject
ORDER BY avg_marks DESC;
🔸 Step-by-Step Explanation:
Clause Purpose
🔹 Output:
subject avg_marks
Math 88.5
English 79.5
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔹 Output:
student_id total_marks
3 163
4 132
🔹 HAVING CLAUSE
The HAVING clause in SQL is used to filter groups of rows after applying the GROUP BY clause. It's like
a WHERE clause, but specifically for aggregate results (like SUM(), AVG(), COUNT(), etc.).
🔹 Syntax
sql
SELECT column1, AGGREGATE_FUNCTION(column2)
FROM table_name
WHERE condition
GROUP BY column1
HAVING AGGREGATE_FUNCTION(column2) condition;
1 Math 85 1
1 English 78 1
2 Math 92 1
2 English 81 1
3 Math 75 2
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
3 English 88 2
4 Math 60 2
4 English 72 2
Result:
subject avg_marks
Math 78.0
English 79.75
✅ Example 2: Total Marks per Student in Semester 2, Only If Total > 150
sql
SELECT student_id, SUM(marks) AS total_marks
FROM marks
WHERE semester = 2
GROUP BY student_id
HAVING SUM(marks) > 150;
Result:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
student_id total_marks
3 163
OFFSET
In Oracle SQL, the OFFSET clause is used to skip a specific number of rows in the result set. It is
typically used in combination with ORDER BY and optionally FETCH to implement pagination.
✅ Syntax
sql
SELECT columns
FROM table_name
ORDER BY column
OFFSET n ROWS;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
1 Alice 90
2 Bob 85
3 Carol 88
4 David 92
5 Emma 84
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
FROM students
OFFSET 3 ROWS;
Result:
2 Bob 85
5 Emma 84
FETCH
The FETCH clause in Oracle SQL is used to limit the number of rows returned by a query. It is
commonly paired with OFFSET to implement pagination.
🔹 Syntax
sql
SELECT columns
FROM table_name
ORDER BY column
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
or with pagination:
sql
SELECT columns
FROM table_name
ORDER BY column
OFFSET x ROWS
1 Alice 90
2 Bob 85
3 Carol 88
4 David 92
5 Emma 84
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
FROM students
Result:
4 David 92
1 Alice 90
3 Carol 88
FROM students
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
OFFSET 3 ROWS
🔹 FETCH Variants
Clause Description
FETCH FIRST n ROWS WITH TIES Includes all rows that tie with the last row
In Oracle SQL, JOIN operations are used to combine rows from two or more tables based on a related
column. This is essential for working with relational data.
Here's clear example of a JOIN operation in Oracle SQL using two tables.
📘 Tables
employees table:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
emp_id emp_name
1 Alice
2 Bob
3 Carol
departments table:
10 1 HR
20 2 Finance
FROM employees e
JOIN departments d
ON e.emp_id = d.emp_id;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔍 Result:
emp_name dept_name
Alice HR
Bob Finance
🔸 Explanation:
● This is an INNER JOIN: it returns only employees who have a matching department.
● Carol is not included because she doesn't belong to any department in the departments table.
INNER JOIN Returns rows that have matching values in both tables
OUTERJOIN An outer join returns all matching rows plus non-matching rows from one or
both tables, with NULL for missing values.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
INNER JOIN:
An inner join (sometimes called a simple join) is a join of two or more tables that returns only those rows
that satisfy the join condition.
1. Equijoin
2. Nonequijoin
An Equijoin is a type of JOIN that combines rows from two or more tables based on an equality
condition between specified columns—usually using the = operator.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🎓 Example Tables
Table: students
student_id name
1 Alice
2 Bob
3 Carol
Table: marks
1 Math 90
2 Science 85
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✅ Output:
student_id name subject marks
1 Alice Math 90
2 Bob Science 85
🔍 Explanation:
● The WHERE s.student_id = m.student_id is the equijoin condition.
● This is functionally the same as using INNER JOIN ... ON, but written in Oracle’s legacy syntax.
Note: It changes the orders of records in result each time. It follows the join column order sometimes and
first column order sometimes so on…if you want specific order then use order by.
ANSI syntax:
🔹 Example Scenario
Let's say we have two tables:
employees table:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
emp_id emp_name
1 Alice
2 Bob
3 Carol
departments table:
10 1 HR
20 2 Finance
FROM employees e
JOIN departments d
ON e.emp_id = d.emp_id;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔍 Result:
emp_name dept_name
Alice HR
Bob Finance
[Link]:
A Nonequijoin is a join with a join condition containing all operators other than equality operator.
Nonequi Conditions
● >
● <
● >=
● <=
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● Explanation: Join employees with all tiers having a min_salary less than employee's salary.
Scenario: Products matched to price categories where product price is less than
the category max price.
sql
● Explanation: Join products with categories where price is below max price.
Scenario: Find all pairs of students where student IDs are not equal (i.e.,
different students).
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Summary
Band join:
A Band join is a special type of nonequi join in which key values in one data set must fall with in the
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
css
This is the band join condition because the join matches rows where [Link] lies within the band
(range) defined by B.
● Useful for mapping values to ranges (e.g., employee salaries to salary grades, transaction
amounts to discount tiers).
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Important Notes
● Because the join condition is not equality, the result can have multiple matches per row from
the first table (if ranges overlap).
● Oracle style uses the WHERE clause, not the ANSI JOIN syntax.
● You can also express the band join using two conditions:
sql
OUTER JOIN :
An outer join returns all matching rows plus non-matching rows from one or both tables, with
NULL for missing values.
Returns all rows from the left table, even if there’s no match in the right table.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Syntax:
sql
Returns all rows from the right table, even if there’s no match in the left table.
Syntax:
sql
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
UNION
🔍 Explanation
● The first query gets all employees (even if they have no department).
● The second query gets all departments (even if they have no employees).
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔸 2. Ansi style
➤ Left Outer Join:
Returns all rows from the left table and matching rows from the right table. If no match, fills with
NULL.
syntax:
sql
FROM employees e
ON e.dept_id = d.dept_id;
Returns all rows from the right table and matching rows from the left table.
syntax:
sql
FROM employees e
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
ON e.dept_id = d.dept_id;
Returns all rows from both tables. Where there's no match, NULL fills the missing side.
syntax:
sql
FROM employees e
ON e.dept_id = d.dept_id;
● Supports all outer join types (Oracle's (+) style does not support FULL OUTER JOIN)
Self Join:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
A self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by
table aliases that qualify column names in the join condition.
○ Comparing rows excluding self (e.g., pairing students who aren't the same person).
sql
s2.student_name AS student2
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
1 Alice
2 Bob
3 Charlie
Alice Bob
Alice Charlie
Bob Alice
Bob Charlie
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Charlie Alice
Charlie Bob
🔍 Explanation
● The self join creates all possible row combinations.
● The condition s1.student_id != s2.student_id ensures that a student is not paired with themselves.
🔸 Ansi style
🔸 Example: Compare Students Who Are Not the Same
🎓 Table: students
sql
student_id NUMBER,
student_name VARCHAR2(50)
);
📌 Sample Data
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
student_id student_name
1 Alice
2 Bob
3 Charlie
s2.student_name AS student2
FROM students s1
JOIN students s2
ON s1.student_id != s2.student_id;
🧾 Output
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
STUDENT STUDENT
1 2
Alice Bob
Alice Charlie
Bob Alice
Bob Charlie
Charlie Alice
Charlie Bob
🔍 Explanation
● The table students is joined to itself using aliases s1 and s2.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
If two tables in a join query have no join condition, then oracle database returns their cartesian product.
✅ What It Does
● No join condition is used.
🧾 Example Scenario
Let's say we want to generate all combinations of colors and sizes for a product catalog.
color VARCHAR2(20)
);
size VARCHAR2(20)
);
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
FROM colors c
🔹 Output
COLOR SIZE
Red Small
Red Medium
Red Large
Blue Small
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Blue Medium
Blue Large
✅ This is the Oracle-style (non-ANSI) cross join — same result, but written with comma-separated tables and
no WHERE clause.
⚠️ If you forget a WHERE clause when doing normal joins using Oracle-style, you might accidentally
perform a cross join.
✅ Summary
Style Syntax Supported in Oracle?
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✅ What Is a Subquery?
A subquery is a SQL query nested inside another query’s SELECT, FROM, or WHERE clause.
🔹 Basic Structure
sql
SELECT column1
FROM table
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
FROM employees
sql
GROUP BY dept_id;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
SELECT emp_name,
FROM employees e;
📝 Summary
Feature Description
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
You need a value that depends on another table Subqueries return scalar or tabular values dynamically
You want to filter based on an aggregated value Use subquery in WHERE to compare with MAX(), etc.
You want to compare across tables Use subquery with IN, EXISTS, =, ANY, ALL
You want to simplify complex joins Use subqueries in FROM to isolate logic
● To define the set of rows to be inserted into the target table of an insert or create table statement.
Syntax:
sql
FROM source_table
WHERE condition;
● To define the set of rows to be inserted in a view or materialized view in a create view or create
materialized view statement
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Syntax:
sql
FROM table1
WHERE condition;
sql
FROM employees
📌 The subquery (SELECT ...) defines the rows included in the view.
sql
UPDATE employees e
SET dept_name = (
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
SELECT d.dept_name
FROM departments d
);
✅ This subquery pulls the correct department name for each employee based on dept_id.
● To provide values for conditions in a whare clause, having clause, or start with clause of select, update
and delete statements
sql
SELECT emp_name
FROM employees
WHERE dept_id IN (
SELECT dept_id
FROM departments
);
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Example: Get departments where the average salary is greater than the company-wide average
sql
FROM employees
GROUP BY dept_id
);
Example: Get all employees under the same manager as the one with the highest salary
sql
FROM employees
SELECT emp_id
FROM employees
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
📌 The subquery in START WITH finds the employee who has the highest salary — then Oracle follows the
hierarchy down from that employee.
sql
WHERE dept_id IN (
SELECT dept_id
FROM departments
);
Types of subquries :
A subquery is a query nested inside another SQL query — used to return data that helps the main (outer) query
make decisions. Subqueries are powerful tools that help you write modular, readable, and efficient SQL.
1. Non-correlated :
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
A non-correlated subquery is a subquery that does not reference any column from the outer query.
It is self-contained and executes only once, and its result is then used by the main (outer) query.
🔹 Key Characteristics
Feature Description
2. Correlated :
A correlated subquery is a subquery that references columns from the outer query.
It is executed once for every row processed by the outer query — making it dependent on the outer
query's current row.
🔹 Key Characteristics
Feature Description
Depends on outer query Uses a value from the outer query inside itself
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Executes repeatedly Runs once for each row in the outer query
Non-correlated subqueries:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
In Oracle SQL, a non-correlated subquery is a subquery that is independent of the outer query — it can be
executed on its own without referencing any columns from the outer query.
🔸 Syntax Example
sql
FROM employees
WHERE department_id = (
SELECT department_id
FROM departments
);
Explanation:
The subquery:
sql
SELECT department_id FROM departments WHERE department_name = 'IT'
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● is non-correlated because it doesn't use any columns from the outer employees query.
● It returns the department ID for 'IT' once, and that result is used to filter the outer query.
Types of subqueries:
In Oracle SQL, a single-row subquery is a type of subquery that returns only one row and one or more
columns. It's often used in places where only a single value is expected, such as in a WHERE, SELECT, or SET
clause.
● Typically used with comparison operators like =, <, >, <=, >=, or <>.
🔸 Example
sql
FROM employees
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
SELECT salary
FROM employees
);
Explanation:
The subquery:
sql
SELECT salary FROM employees WHERE employee_id = 100
● The outer query finds employees whose salary is higher than that salary.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔸 Important Notes:
If the subquery returns more than one row, Oracle will throw an error:
sql
ORA-01427: single-row subquery returns more than one row
● To avoid this, ensure the subquery is limited to one row (e.g., using WHERE, ROWNUM, or
MAX/MIN).
FROM employees
WHERE salary = (
SELECT MAX(salary)
FROM employees
);
In Oracle SQL, a multiple-row subquery is a subquery that returns more than one row. It’s used when the
outer query needs to compare a value against a set of values.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
○ IN
○ ANY / SOME
○ ALL
🔸 Example 1: Using IN
sql
FROM employees
WHERE department_id IN (
SELECT department_id
FROM departments
);
Explanation:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● The outer query finds employees who belong to any of those departments.
FROM employees
SELECT salary
FROM employees
WHERE department_id = 50
);
Explanation:
● Returns employees who earn more than at least one person in department 50.
FROM employees
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
SELECT salary
FROM employees
WHERE department_id = 50
);
Explanation:
● Finds employees whose salary is greater than all salaries in department 50.
❗ Caution
Using a comparison operator like = with a multi-row subquery will result in an error:
sql
SELECT first_name
FROM employees
WHERE department_id = (
SELECT department_id
FROM departments
);
If the subquery returns more than one row, Oracle will raise:
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
A multiple-column subquery in Oracle SQL returns more than one column per row. You typically use it when
the outer query needs to compare against a combination of columns from the subquery.
○ EXISTS
FROM employees
FROM job_history
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
);
✅ Explanation:
● The subquery returns pairs of (department_id, job_id) from job_history.
● The outer query returns employees who have the same department_id and job_id as in the job
history.
FROM employees e
WHERE EXISTS (
SELECT 1
FROM departments d
);
✅ Explanation:
● Even though the subquery isn't returning multiple columns, it uses multiple columns in its condition.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
FROM (
FROM departments d
GROUP BY d.department_name
);
✅ Explanation:
● The subquery in the FROM clause returns two columns: department name and count of employees.
❗ Important Notes:
● When using (col1, col2) IN (SELECT col1, col2 ...), the number and order of columns must match.
Correlated subqueries:
A correlated subquery in Oracle SQL is a subquery that depends on a column from the outer query. Unlike
a non-correlated subquery, it cannot run independently, because it refers to values from the outer query.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔸 Example: Find employees who earn more than the average salary in their
department
sql
FROM employees e
SELECT AVG(salary)
FROM employees
);
✅ Explanation:
The subquery:
sql
SELECT AVG(salary)
FROM employees
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● So, the subquery is re-evaluated for each employee using their department.
An inline view is a subquery in the FROM clause that behaves like a temporary table or view for the outer
query to use.
✅ Purpose: Often used to simplify complex queries, especially when you want to aggregate or filter data
before applying additional logic.
🔸 Basic Syntax:
sql
FROM (
FROM table_name
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
WHERE condition
) inline_view_alias
WHERE some_condition;
🔸 Example Scenario:
You have an EMPLOYEES table like this:
You want to find all employees who earn more than the average salary in their department.
SELECT e.employee_id,
e.first_name,
[Link],
d.avg_salary
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
FROM employees e
JOIN (
FROM employees
GROUP BY department_id
)d
ON e.department_id = d.department_id
🔹 Explanation:
Inline View (Subquery):
sql
FROM employees
GROUP BY department_id
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Outer Query:
● Filters employees where their salary is greater than the average salary of their department.
Only Alice is returned (John and Carol earn less than 8000, Bob earns equal to avg of 10000).
Scalar subquery:
In Oracle SQL, a scalar subquery is a subquery that returns exactly one value (a single row and one
column) and can be used anywhere a single value (scalar) is allowed — such as in the SELECT, WHERE, or
ORDER BY clauses.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
SELECT first_name,
salary,
FROM employees;
✅ Explanation:
● The subquery (SELECT AVG(salary) FROM employees) returns a single value (e.g., 7800).
FROM employees
SELECT AVG(salary)
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
FROM employees
);
✅ Explanation:
● Filters employees whose salary is greater than the average.
Introduction to constraints:
PRIMARY KEY Ensures each row has a unique and not null identifier.
🔸 Purpose
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
last_name VARCHAR2(50),
);
✅ In this example:
● employee_id, first_name, and hire_date must have values when inserting data.
❗ You can only do this if the column already has no NULL values.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✅ This will work because all NOT NULL columns are provided.
sql
❌ This will fail because first_name is NOT NULL but was not provided.
FROM user_tab_columns
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
first_name VARCHAR2(50),
);
sql
🔸 Note: You must ensure that existing values are not NULL before applying this change, or it
will fail.
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
FROM all_tab_columns
Default constraints:
In SQL, a DEFAULT constraint assigns a default value to a column when no value is provided during an
INSERT.
first_name VARCHAR2(50),
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
);
sql
This does not make the column NULL-only—it just removes the automatic default.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● DEFAULTs can be constants ('N/A', 0, 100), or built-in functions like SYSDATE, SYSTIMESTAMP,
USER, etc.
● DEFAULTs are only applied when the column is omitted in the INSERT. If you explicitly insert
NULL, that NULL is stored.
🧪 Example:
sql
Check constraints:
In Oracle SQL, a CHECK constraint enforces rules at the column or table level by specifying a condition that
each row must satisfy. It ensures that only valid data is stored in the database.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔧 Syntax Examples
1. CREATE TABLE with a CHECK Constraint
sql
);
sql
age NUMBER,
);
You can give your CHECK constraint a name (chk_age), which makes it easier to reference or drop later.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
pgsql
sql
FROM user_constraints
In Oracle SQL, a PRIMARY KEY constraint uniquely identifies each row in a table and ensures that the key
column(s) contain unique and non-null values.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
One Per Table Only one primary key per table is allowed
🔧 Syntax Examples
1. Create Table with PRIMARY KEY
sql
first_name VARCHAR2(50),
last_name VARCHAR2(50)
);
Here, employee_id is the primary key—it must be unique and not null.
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
department_id NUMBER,
name VARCHAR2(100),
);
sql
employee_id NUMBER,
project_id NUMBER,
assignment_date DATE,
);
Both employee_id and project_id together must be unique and not null.
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
⚠️ The column must already have unique and not null values before adding the constraint.
sql
FROM user_cons_columns
WHERE constraint_name IN (
SELECT constraint_name
FROM user_constraints
);
⚠️ Important Notes
● Only one PRIMARY KEY per table
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● It differs from UNIQUE in that UNIQUE allows multiple NULLs, but PRIMARY KEY does not allow
any NULLs
● You can reference a primary key from another table using a foreign key
In Oracle SQL, a UNIQUE key constraint ensures that all values in a column or group of columns are
different (i.e., unique). Unlike a PRIMARY KEY, it allows NULLs, but not duplicate non-null values.
Allows NULLs Unlike PRIMARY KEY, NULLs are allowed (but not duplicate non-null values)
Multiple UNIQUEs allowed You can have multiple UNIQUE constraints per table
🔧 Syntax Examples
1. Create Table with UNIQUE Constraint
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
);
Both username and email must be unique across the table. They can be null (unless NOT NULL is added).
sql
national_id VARCHAR2(20),
);
sql
customer_id NUMBER,
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
room_number NUMBER,
booking_date DATE,
);
This ensures no two bookings can have the same room on the same date.
sql
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
FROM user_cons_columns
WHERE constraint_name IN (
SELECT constraint_name
FROM user_constraints
);
In Oracle SQL, a FOREIGN KEY constraint enforces a relationship between two tables. It ensures that the
values in a column (or group of columns) in the child table match values in a column of the parent
table—typically a PRIMARY KEY or UNIQUE constraint.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Enforces referential integrity Prevents inserting values in the child table that don't
exist in the parent
Requires referenced column to be UNIQUE or The parent column must have unique values
PRIMARY KEY
Optional ON DELETE actions You can define behavior when a parent row is deleted
(CASCADE, SET NULL)
It:
● Prevents orphaned records (i.e., child records that don’t have a corresponding parent).
🏗️ Syntax
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
id NUMBER,
parent_id NUMBER,
CONSTRAINT fk_parent
REFERENCES parent_table(id)
);
🔧 Syntax Examples
1. Create Table with FOREIGN KEY
sql
name VARCHAR2(100)
);
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
name VARCHAR2(100),
department_id NUMBER,
REFERENCES departments(department_id)
);
sql
REFERENCES departments(department_id);
3. ON DELETE Options
When defining a foreign key, you can specify what happens when a referenced row is deleted:
● ON DELETE SET NULL: Set child foreign key to NULL when parent is deleted
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
REFERENCES departments(department_id)
🔄 Example of CASCADE
sql
name VARCHAR2(100),
department_id NUMBER,
REFERENCES departments(department_id)
ON DELETE CASCADE
);
● You cannot insert a value into the child table that doesn’t exist in the parent.
● You cannot delete a row in the parent if child rows exist unless you use ON DELETE CASCADE or
ON DELETE SET NULL.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
FROM user_constraints
sql
FROM user_constraints a
sql
FROM user_constraints
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
⚠️ Notes
● You cannot delete a parent row if child rows exist, unless:
● FOREIGN KEY columns must have the same data type as the referenced column
Summary of constraints:
Constraints are rules applied to table columns to enforce data integrity — they ensure the data in the database
is valid, consistent, and reliable.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
PRIMARY KEY Uniquely identifies each row in a table. Must be unique and not null. Only one primary
key per table.
FOREIGN KEY Ensures that a value in one table matches a value in another table. Maintains referential
integrity between tables.
Default
UNIQUE Ensures that all values in a column (or group of columns) are unique across rows.
Allows one null value.
NOT NULL Prevents a column from having NULL values. Ensures data is always entered in that
column.
CHECK Validates data against a custom condition (e.g., age > 18, salary >= 0).
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
dept_id NUMBER
);
sql
dept_id NUMBER,
dept_name VARCHAR2(100),
);
sql
REFERENCES departments(dept_id);
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
Unlike other constraints, NOT NULL & DEFAULT is added using MODIFY:
sql
sql
Summary Table
FOREIGN KEY ADD CONSTRAINT fk_name FOREIGN KEY (col) REFERENCES parent(col)
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
Disable a constraint
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
name VARCHAR2(100),
gender CHAR(1),
CONSTRAINT chk_gender
);
sql
sql
-- ✅ This works
INSERT INTO employees (emp_id, name, gender) VALUES (1, 'Alice', 'F');
✅ Summary
Constraint Type Purpose
In Oracle SQL, set operators are used to combine the results of two or more SELECT queries. They work
like sets in mathematics, combining rows while removing or keeping duplicates depending on the operator
used.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
MINUS Returns rows in the first query but not in the second.
All rows selected by the first query but not the second including
duplicates
MINUS ALL
All distinct rows selected by the first query but not the second
EXPECT
All rows selected by the first query but not the second including
duplicates
EXPECT ALL
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🧱 Syntax
sql
<SET OPERATOR>
📌 Rules:
● The number and data types of columns must match in both queries.
● The column names in the result come from the first query.
🔍 Examples
Assume we have two tables: employees_2024 and employees_2025
sql
UNION
sql
UNION ALL
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
INTERSECT
sql
MINUS
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Introduction to PL/SQL:
PL/SQL (Procedural Language for SQL) is Oracle Corporation's procedural extension to SQL, designed for
seamless integration with the Oracle Database. It combines the power of SQL with the procedural features of
programming languages like loops, conditions, and error handling.
🔹 What is PL/SQL?
PL/SQL stands for Procedural Language extensions to SQL. It allows developers to write code blocks that
combine SQL statements with procedural logic such as:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Purpose Used to query and manipulate Used to write full programs (logic, loops, conditions, etc.)
data in a database
Execution Executes one statement at a Executes a block of code (multiple statements) at once
time
Control Structures Not supported Supported (IF, FOR, WHILE, CASE, etc.)
Error Handling Limited (only in tools, not in Robust error handling using EXCEPTION blocks
SQL itself)
Variables Cannot declare variables Can declare and use variables and constants
Used For Querying, inserting, updating, Creating applications: procedures, functions, triggers, packages
and deleting data
Example SELECT * FROM employees; A block with DECLARE, BEGIN, EXCEPTION, END
✅ Summary
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● PL/SQL is for programming logic and creating complex applications within the database.
🔹 Features of PL/SQL
● ✅ Tight Integration with SQL
● ✅ High Performance for Batch Operations
● ✅ Strong Error Handling
● ✅ Modular Code (Procedures, Functions, Packages)
● ✅ Portability (Works across different platforms with Oracle DB)
● ✅ Security (Supports user permissions and encapsulation)
🔹 Use Cases
● Writing stored procedures and functions
● Creating triggers
PL/SQL Procedures
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
A procedure in PL/SQL is a named block of code that performs a specific task. It can accept parameters,
execute SQL statements, and return results indirectly (through OUT parameters).
IS
-- Declarations
BEGIN
-- Procedure logic
EXCEPTION
-- Error handling
END procedure_name;
sql
-- Variable declarations
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
END;
DECLARE
v_employee_name VARCHAR2(50);
BEGIN
FROM employees
EXCEPTION
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● Modular programming
🔹 Variables in PL/SQL:
In PL/SQL, variables are used to store data temporarily during the execution of a block. You can assign
values, manipulate them, and use them in SQL and control statements.
✅ Declaring Variables
Variables are declared in the DECLARE section of a PL/SQL block using the following syntax:
sql
🔹 Example:
sql
DECLARE
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
BEGIN
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
PL/SQL supports several string (character) data types to store and manipulate text. These are commonly used
for names, descriptions, codes, etc.
String datatypes:
● Fixed-length strings
● Variable-length strings
● Character large objects
Here's a detailed comparison and examples of the string-related data types in PL/SQL: VARCHAR2,
NVARCHAR2, CHAR, NCHAR, CLOB, and NCLOB.
🔹 1. VARCHAR2
● Stores variable-length character strings.
✅ Example:
sql
DECLARE
v_name VARCHAR2(50);
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
BEGIN
END;
🔹 2. NVARCHAR2
● Like VARCHAR2, but stores Unicode character data (multi-language support).
✅ Example:
sql
DECLARE
v_country_name NVARCHAR2(50);
BEGIN
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔹 3. CHAR
● Stores fixed-length strings.
✅ Example:
sql
DECLARE
v_code CHAR(5);
BEGIN
v_code := 'AB';
END;
🔹 4. NCHAR
● Like CHAR, but stores Unicode data in fixed-length format.
✅ Example:
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
DECLARE
v_lang_code NCHAR(5);
BEGIN
END;
✅ Example:
sql
DECLARE
v_long_text CLOB;
BEGIN
DBMS_OUTPUT.PUT_LINE(SUBSTR(v_long_text, 1, 100));
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✅ Example:
sql
DECLARE
v_unicode_text NCLOB;
BEGIN
DBMS_OUTPUT.PUT_LINE(SUBSTR(TO_CLOB(v_unicode_text), 1, 100));
END;
🔸 Summary Table
Data Type Fixed/Variable Supports Unicode Max Length (PL/SQL)
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
INITCAP() Capitalizes first letter of each word INITCAP('john doe') → 'John Doe'
TRIM() Removes leading/trailing characters (default: space) TRIM(' abc ') → 'abc'
Examples:
● CONCAT()
sql
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
END;
● UPPER()
sql
BEGIN
END;
● LOWER()
sql
BEGIN
END;
● INITCAP()
sql
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
END;
● SUBSTR()
sql
BEGIN
END;
● INSTR()
sql
BEGIN
END;
● LPAD()
sql
BEGIN
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● RPAD()
sql
BEGIN
END;
● REPLACE()
sql
BEGIN
END;
● TRANSLATE()
sql
BEGIN
END;
● TRIM()
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
BEGIN
END;
● LTRIM()
sql
BEGIN
END;
● RTRIM()
sql
BEGIN
END;
PL/SQL provides several numeric data types for storing and processing numbers, including integers,
decimals, and floating-point numbers. These are used in everything from simple arithmetic to complex
financial and scientific calculations.
NUMBER(p, s) General-purpose numeric type with precision and NUMBER(6,2) stores 9999.99
scale
PLS_INTEGER Fastest integer type, used only in PL/SQL (not SQL) 100, -200
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔹 Explanation of NUMBER(p, s)
● p: Precision – total number of digits (1 to 38)
🔹 Examples of Declarations
sql
DECLARE
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
END;
⚠️ PLS_INTEGER is limited to PL/SQL blocks — not usable directly in SQL statements or tables.
🔹 Summary
Type Used For PL/SQL Only?
PL/SQL provides a wide range of numeric functions for mathematical calculations, rounding, comparisons,
and more. These work with NUMBER, INTEGER, FLOAT, PLS_INTEGER, etc.
What it does:
Rounds a number to the nearest whole number or d decimal places.
Syntax:
Example:
plsql
BEGIN
END;
Explanation:
Used when reporting rounded values like currency or percentages.
What it does:
Cuts off digits after the specified decimal place, without rounding.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Example:
plsql
BEGIN
END;
Explanation:
Ideal for truncating sensitive financial calculations (e.g., banking).
● FLOOR(n) – Floor
What it does:
Returns the largest integer that is less than or equal to the number. It always rounds down.
Syntax: FLOOR(number)
Example:
plsql
BEGIN
END;
Explanation:
Used when you want to estimate conservatively (e.g., maximum capacity without exceeding a limit).
● CEIL(n) – Ceiling
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
What it does:
Returns the smallest integer that is greater than or equal to the number. It always rounds up, even if the
number is already close to an integer.
Syntax: CEIL(number)
Example:
plsql
BEGIN
END;
Explanation:
This is helpful in billing systems (e.g., always charge full units even for partial use).
What it does:
Converts a number into a string with optional formatting (like commas, decimal points, currency symbols, etc.).
Syntax:
plsql
TO_CHAR(number, [format_model])
● format_model (optional): A format string that specifies how the number should be displayed.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Example:
Basic Conversion
plsql
BEGIN
END;
Output: '12345'
What it does:
Returns the remainder of the division x ÷ y.
Example:
plsql
BEGIN
END;
Explanation:
Useful in tasks like checking if a number is even/odd, cycle-based operations, or page calculations.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Purpose:
Returns the remainder of division x ÷ y based on the sign of the divisor (y).
Syntax:
plsql
MOD(dividend, divisor)
Purpose:
Returns the remainder from the division of x by y, but it's calculated using the IEEE standard:
REMAINDER=x−(y∗ROUND(x/y))REMAINDER = x - (y * ROUND(x/y))
REMAINDER=x−(y∗ROUND(x/y))
Use case General arithmetic, cycle logic Scientific and statistical applications
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🧪 Examples
Example 1: Positive Numbers
plsql
BEGIN
END;
✅ Explanation:
● MOD(10, 3) = 10 - 3×FLOOR(10/3) = 10 - 3×3 = 1
plsql
BEGIN
END;
✅ Explanation:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🧠 Takeaway:
● MOD returns a positive result (follows divisor's sign).
plsql
BEGIN
END;
✅ Explanation:
● MOD(10, -3) = 10 - (-3)×FLOOR(10 / -3) = 10 - (-3×(-4)) = 10 - 12 = -2
🧠 Notice:
● MOD result sign matches divisor
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
plsql
BEGIN
END;
plsql
BEGIN
END;
Summary Table
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
(10, 3) 1 1
(-10, 3) 2 -1
(10, -3) -2 1
(-10, -3) -1 -1
✅ When to Use
Scenario Use MOD Use REMAINDER
plsql
DECLARE
BEGIN
IF MOD(num, 2) = 0 THEN
DBMS_OUTPUT.PUT_LINE('Even Number');
ELSE
DBMS_OUTPUT.PUT_LINE('Odd Number');
END IF;
END;
In PL/SQL (Oracle), date and time values can be represented using several date-related data types.
There are three data types you can use to work with dates and times.
1.Date : This data type stores a date and time, resolved to the second. It does not include the time zone.
Date is the oldest and most commonly used data type for working with dates in oracle applications.
2.Timestamp : Time stamps are similar to dates but with these two key distinctions: (1) You can store
and manipulate times resolved to the nearest billionth of a second (nine decimal places of precision.),
and (2) You can associate a time zone with a time stamp, and oracle database will take that time zone
into account when manipulating the time stamp.
3.Interval : Whereas date and timestamp record a specific point in time, interval records and computes a
time duration. You can specify an interval in terms of years and months, or days and seconds.
1. DATE
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
plsql
DECLARE
BEGIN
END;
2. TIMESTAMP
sql
TIMESTAMP [ (fractional_seconds_precision) ]
Example:
plsql
DECLARE
ts TIMESTAMP := SYSTIMESTAMP;
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
END;
sql
Example:
plsql
DECLARE
BEGIN
END;
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
Example:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
plsql
DECLARE
interval1 INTERVAL YEAR TO MONTH := INTERVAL '2-3' YEAR TO MONTH; -- 2 years, 3 months
BEGIN
END;
sql
Example:
plsql
DECLARE
BEGIN
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Summary Table
TIMESTAMP WITH LOCAL TIME Timestamp normalized to session TZ Time zone at runtime
ZONE
INTERVAL YEAR TO MONTH Span of years and months Used in date arithmetic
INTERVAL DAY TO SECOND Span of days to fractional seconds Used in date arithmetic
PL/SQL (and Oracle SQL) provides a rich set of date functions to handle, format, manipulate, and calculate
date and time values.
● TO_CHAR
● EXTRACT
● TO_DATE
● TRUNC
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● ADD_MONTHS
● NEXT_DAY
● LAST_DAY
1. TO_CHAR()
Purpose:
Syntax:
sql
TO_CHAR(date_or_timestamp, format_model)
✅ Use Cases:
● Displaying dates in readable/custom formats
Example:
plsql
DECLARE
v_today VARCHAR2(50);
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
END;
Format Meaning
MM Month (01–12)
DD Day of month
MI Minute
SS Second
2. EXTRACT()
Purpose: The EXTRACT() function retrieves a specific part (like year, month, or hour) from a DATE,
TIMESTAMP, or INTERVAL value.
Syntax
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● date_part: The component you want (e.g., YEAR, MONTH, DAY, HOUR, etc.)
Time Zones TIMEZONE_HOUR, TIMEZONE_MINUTE Only for TIMESTAMP WITH TIME ZONE
Example:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
END;
3. TO_DATE()
Purpose:
Syntax:
sql
Use Cases:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✅ Example:
sql
DECLARE
v_date DATE;
BEGIN
END;
⚠️ Pitfall:
If the string and format don’t match, Oracle raises ORA-01843: not a valid month or similar errors.
Wrong:
sql
Right:
sql
TO_DATE('2025/07/21', 'YYYY/MM/DD')
4. TRUNC()
The TRUNC() function in PL/SQL truncates a DATE or TIMESTAMP to a specified unit of time—like day,
month, year, or hour—removing smaller time components.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Syntax
sql
TRUNC(date_value [, format])
● format (optional): A string indicating how to truncate (e.g. 'MM', 'YYYY', etc.)
If no format is provided, it defaults to 'DD' (truncates the time part, keeps the date).
plsql
DECLARE
BEGIN
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Output:
sql
Truncating SYSTIMESTAMP
sql
FROM dual;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● ADD_MONTHS()
✅ Purpose:
Adds or subtracts a specified number of calendar months to/from a date.
✅ Syntax:
sql
ADD_MONTHS(date_value, number_of_months)
✅ Example:
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
-- Result: 21-OCT-2025
✅ Edge Case:
sql
● NEXT_DAY()
✅ Purpose:
Returns the next occurrence of the specified weekday after a given date.
✅ Syntax:
sql
NEXT_DAY(date_value, 'weekday')
✅ Example:
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✅ Notes:
● If the date is already the same weekday, NEXT_DAY returns the next one (not the same date).
● LAST_DAY()
✅ Purpose:
Returns the last day of the month for a given date.
✅ Syntax:
sql
LAST_DAY(date_value)
✅ Example:
sql
plsql
DECLARE
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
v_expiry DATE;
v_payday DATE;
v_month_end DATE;
BEGIN
END;
🔶 Summary Table
Function Purpose Example Output
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● The & symbol is used in SQL*Plus, SQL Developer, and similar Oracle tools to prompt the user for
input at runtime.
● It tells Oracle to replace the &variable with a value you type when running the script or query.
Example:
DECLARE
Num1 NUMBER(2);
Num2 NUMBER(2);
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Res NUMBER(3);
BEGIN
num1:=&NUMBER1;
num2:=&NUMBER2;
res:=num1+num2;
DBMS_OUTPUT.PUT_LINE(‘Result is :’||res;
END;
/
OUT PUT:
sql
rust
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
plsql
DECLARE
v_name VARCHAR2(50);
BEGIN
v_name := '&username';
END;
rust
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Hello, Alice!
Notes:
● Use single quotes ' ' around &variable in string contexts to make sure the input is treated as a string.
● You can use &&variable to reuse the same input multiple times without prompting again.
● This works only in tools like SQL*Plus, SQLcl, Oracle SQL Developer, not inside application code or
pure PL/SQL blocks run programmatically.
In PL/SQL, %TYPE and %ROWTYPE are attribute datatypes used to declare variables dynamically based
on the structure of existing database objects like columns or entire rows.
They inherit the datatype and size automatically, making your code:
● More reliable
● Easier to maintain
✅ What It Does:
● Declares a variable with the same data type as a table column or another variable.
✅ Syntax:
plsql
variable_name table_name.column_name%TYPE;
✅ Example:
plsql
DECLARE
v_salary [Link]%TYPE;
BEGIN
FROM employees
END;
🔍 What Happens:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● If the column is changed in the future (e.g., from NUMBER(8,2) to NUMBER(10,2)), no code changes
are needed.
✅ Syntax:
plsql
record_variable table_name%ROWTYPE;
✅ Example:
plsql
DECLARE
v_emp employees%ROWTYPE;
BEGIN
FROM employees
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
END;
🔍 What Happens:
● v_emp has fields like v_emp.employee_id, v_emp.salary, v_emp.job_id, etc.
Used for Single values (e.g., salary) Full row records (e.g., employee)
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✅ Benefits
● ✔ Reduces hardcoding of data types
plsql
DECLARE
v_emp employees%ROWTYPE;
v_deptid departments.department_id%TYPE;
BEGIN
v_deptid := v_emp.department_id;
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● Make decisions
● Repeat actions
Without control statements, your PL/SQL code would run line-by-line in the order it appears — no conditions,
no loops, no decision-making.
Type Description
(selection)
If statements in plsql:
In PL/SQL, the IF statement is used to make decisions in your program. It allows you to execute certain code only when a
condition is true.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔹 Purpose:
To control the flow of execution based on logical conditions.
🔹 IF Statements
Syntax:
pl
IF condition THEN
-- statements
END IF;
Variants:
Example:
plsql
DBMS_OUTPUT.PUT_LINE('High salary');
DBMS_OUTPUT.PUT_LINE('Medium salary');
ELSE
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
DBMS_OUTPUT.PUT_LINE('Low salary');
END IF;
1. IF...THEN
plsql
IF condition THEN
-- statements
END IF;
🔸 Example:
plsql
DBMS_OUTPUT.PUT_LINE('High salary');
END IF;
2. IF...THEN...ELSE
plsql
IF condition THEN
-- true block
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
ELSE
-- false block
END IF;
🔸 Example:
plsql
DBMS_OUTPUT.PUT_LINE('High salary');
ELSE
DBMS_OUTPUT.PUT_LINE('Normal salary');
END IF;
3. IF...THEN...ELSIF...ELSE
plsql
IF condition1 THEN
-- block1
-- block2
ELSE
-- block3
END IF;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔸 Example:
plsql
DBMS_OUTPUT.PUT_LINE('Grade: A');
DBMS_OUTPUT.PUT_LINE('Grade: B');
ELSE
DBMS_OUTPUT.PUT_LINE('Grade: C');
END IF;
[Link] IF Statement
✅ Syntax:
pl
IF outer_condition THEN
IF inner_condition THEN
ELSE
END IF;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
ELSE
END IF;
✅ Example:
pl
DECLARE
BEGIN
IF dept_id = 10 THEN
ELSE
END IF;
ELSE
DBMS_OUTPUT.PUT_LINE('Normal salary');
END IF;
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✅ Summary
Statement Form Description
In PL/SQL, the CASE statement is used to evaluate conditions or expressions and execute one block of code
based on the result — similar to switch-case in other programming languages like C or Java.
● Improves readability
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✅ Syntax:
plsql
CASE expression
-- code block
-- code block
ELSE
-- default block
END CASE;
✅ Example:
plsql
DECLARE
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
CASE job_code
DBMS_OUTPUT.PUT_LINE('Programmer');
DBMS_OUTPUT.PUT_LINE('HR Representative');
DBMS_OUTPUT.PUT_LINE('Sales Representative');
ELSE
DBMS_OUTPUT.PUT_LINE('Other Role');
END CASE;
END;
Used when each WHEN clause contains a full condition (not just a value).
✅ Syntax:
plsql
CASE
-- code block
-- code block
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
ELSE
-- default block
END CASE;
✅ Example:
plsql
DECLARE
BEGIN
CASE
DBMS_OUTPUT.PUT_LINE('Grade: A');
DBMS_OUTPUT.PUT_LINE('Grade: B');
DBMS_OUTPUT.PUT_LINE('Grade: C');
ELSE
DBMS_OUTPUT.PUT_LINE('Grade: F');
END CASE;
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Notes
● CASE statements must be complete — include ELSE to handle all cases (optional, but recommended)
The FOR loop in PL/SQL is a control structure used to repeat a block of code a specific number of times. It
automatically initializes, increments, and terminates the loop control variable.
Type Description
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Purpose:
Used when you know how many times to iterate (e.g., 1 to 10).
Syntax:
plsql
-- Code block
END LOOP;
plsql
BEGIN
END LOOP;
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
📝 Output:
ini
i=1
i=2
i=3
i=4
i=5
plsql
BEGIN
END LOOP;
END;
📝 Output:
Ini
i=5
i=4
i=3
i=2
i=1
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Feature Details
Purpose:
PL/SQL opens the cursor, fetches each row, and closes the cursor — all automatically.
plsql
DECLARE
CURSOR emp_cur IS
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
BEGIN
END LOOP;
END;
plsql
BEGIN
FOR rec IN (SELECT empno, ename FROM emp WHERE deptno = 10) LOOP
END LOOP;
END;
In both cases, rec is a record variable that holds each row returned by the query.
Feature Details
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
plsql
DECLARE
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
CURSOR emp_cur IS
BEGIN
END LOOP;
END;
🔚 Summary
Loop Type Description Best Used For
Numeric FOR Loops between two numbers Counters, sums, fixed iterations
Cursor FOR Loops through result of a SQL query Row-by-row processing from tables
Simple loop:
A simple loop in PL/SQL is a basic loop structure that repeatedly executes a block of code until it is explicitly
exited using the EXIT statement. It does not have a built-in condition to stop automatically, so you must provide
one inside the loop.
plsql
LOOP
-- Statements to execute
END LOOP;
✅ Example:
plsql
DECLARE
i NUMBER := 1;
BEGIN
LOOP
i := i + 1;
END LOOP;
END;
🔍 Explanation:
● i := 1; initializes the counter.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
○ Increments i by 1.
📝 Key Points:
● Always use an EXIT or EXIT WHEN inside a simple loop; otherwise, it becomes an infinite loop.
● Good for when you don’t know exactly how many times you need to loop ahead of time.
While loop:
A WHILE loop in PL/SQL repeatedly executes a block of code as long as a condition is TRUE. Unlike a
simple loop, the condition is checked before each iteration.
-- Statements to execute
END LOOP;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✅ Example:
plsql
DECLARE
i NUMBER := 1;
BEGIN
i := i + 1;
END LOOP;
END;
🔍 Explanation:
● i := 1; initializes the counter.
○ Increments i.
● When i becomes 6, the condition i <= 5 becomes FALSE, and the loop exits.
📝 Key Points:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● A WHILE loop might not run at all if the condition is false at the start.
● Always make sure the condition will eventually become false — or you’ll get an infinite loop.
Condition check Inside the loop using EXIT WHEN At the start of the loop
Risk of infinite loop ✅ Yes (if no EXIT WHEN is used) ✅ Yes (if condition never becomes false)
Use case When exit depends on logic inside When you want to loop while a condition is true
loop
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
plsql
DECLARE
CURSOR emp_cursor IS
v_empno [Link]%TYPE;
v_ename [Link]%TYPE;
BEGIN
OPEN emp_cursor;
LOOP
END LOOP;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
CLOSE emp_cursor;
END;
CURSOR emp_cursor IS... Declares a cursor named emp_cursor for a SELECT query
OPEN emp_cursor; Executes the query and makes the result set available
FETCH emp_cursor INTO... Retrieves one row at a time into declared variables
EXIT WHEN Exits the loop when no more rows are left to fetch
emp_cursor%NOTFOUND;
● Works well with complex logic and conditional processing per row
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Cursor Attributes
Attribute Description
%FOUND:
plsql
DECLARE
CURSOR emp_cursor IS
v_empno [Link]%TYPE;
v_ename [Link]%TYPE;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
BEGIN
OPEN emp_cursor;
IF emp_cursor%FOUND THEN
DBMS_OUTPUT.PUT_LINE('Record Found:');
ELSE
END IF;
CLOSE emp_cursor;
END;
🧾 Output (example):
If data exists:
yaml
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
Record Found:
If no data:
pgsql
🔍 Key Points:
● %FOUND returns TRUE if the last FETCH returned a row.
%NOTFOUND:
● %NOTFOUND returns TRUE if the last FETCH did not return any row.
● Used with explicit cursors to know when to exit a loop or stop fetching data.
DECLARE
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
CURSOR emp_cursor IS
v_empno [Link]%TYPE;
v_ename [Link]%TYPE;
BEGIN
OPEN emp_cursor;
LOOP
END LOOP;
CLOSE emp_cursor;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
END;
💡 Explanation:
● The loop keeps fetching rows.
● EXIT WHEN emp_cursor%NOTFOUND; stops the loop when there are no more rows.
📌 Output (Example):
If 3 employees are in dept 10:
yaml
%ROWCOUNT:
● %ROWCOUNT returns the number of rows fetched so far (for explicit cursors) or affected (for
implicit cursors).
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
DECLARE
CURSOR emp_cursor IS
v_empno [Link]%TYPE;
v_ename [Link]%TYPE;
BEGIN
OPEN emp_cursor;
LOOP
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
END LOOP;
CLOSE emp_cursor;
END;
🔍 Explanation:
● emp_cursor%ROWCOUNT tells you how many rows have been fetched up to that point.
BEGIN
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● SQL%ROWCOUNT gives the number of rows affected by the last DML operation (e.g., INSERT,
UPDATE, DELETE).
📝 Summary Table
Attribute Works With What It Does
%ISOPEN:
● Returns:
🟡 Useful to prevent errors by avoiding attempts to fetch from or close an unopened or already closed cursor.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
DECLARE
CURSOR emp_cursor IS
v_empno [Link]%TYPE;
v_ename [Link]%TYPE;
BEGIN
IF emp_cursor%ISOPEN THEN
ELSE
END IF;
OPEN emp_cursor;
-- Check again
IF emp_cursor%ISOPEN THEN
END IF;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
CLOSE emp_cursor;
-- Final check
END IF;
END;
📝 Output (Example):
kotlin
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🧠 Summary
Attribute Purpose Returns
● Especially useful when calling PL/SQL code from applications (like Java, Python, or .NET) that
expect a result set.
✅ Syntax
1. Define the ref cursor type
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
plsql
plsql
SYS_REFCURSOR:
● Used when you want to return or work with query results dynamically.
pl
DECLARE
emp_cur SYS_REFCURSOR;
v_empno [Link]%TYPE;
v_ename [Link]%TYPE;
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
LOOP
END LOOP;
CLOSE emp_cur;
END;
🔍 How It Works
● SYS_REFCURSOR is used instead of declaring your own REF CURSOR type.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
✅ Benefits of SYS_REFCURSOR
Feature Advantage
📌 Use Case
You’ll commonly use SYS_REFCURSOR when:
In PL/SQL, run-time errors occur while the code is executing, not during compilation. PL/SQL lets you
handle these errors gracefully using the EXCEPTION block, so your program doesn't crash unexpectedly.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● TOO_MANY_ROWS — Query returns more than one row for SELECT INTO.
3. Logical Errors
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● Note: These errors don’t raise exceptions automatically — you have to debug them.
📋 Summary Table
Error Type When Detected Cause Handling
Logical Error During/after Flawed program logic Code review and debugging
execution
Exception Handling
● Exceptions are errors or unexpected events that occur during the execution of a PL/SQL program
(run-time errors).
● Exception handling lets you catch these errors and respond to them gracefully instead of letting the
program crash.
● You use the EXCEPTION block to define how to handle different errors.
plsql
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
EXCEPTION
END;
DECLARE
denominator NUMBER := 0;
result NUMBER;
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
EXCEPTION
END;
Explanation:
● The WHEN ZERO_DIVIDE block catches this error and displays a friendly message.
2.Error Occurs: When an error happens, PL/SQL immediately jumps to the EXCEPTION block.
3.Matching Exception: It looks for a matching WHEN clause for that error.
5.Program Continues or Ends: After handling, the program either continues or ends gracefully.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
VALUE_ERROR :
pl
DECLARE
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
v_name VARCHAR2(5);
BEGIN
v_name := 'Jonathan';
EXCEPTION
END;
🔍 Explanation
● v_name can only hold 5 characters.
● This causes a VALUE_ERROR because PL/SQL cannot truncate the string automatically.
● The EXCEPTION block catches the error and prints a friendly message.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
plsql
DECLARE
BEGIN
EXCEPTION
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● TOO_MANY_ROWS: A SELECT INTO returns more than one row, which is not allowed.
⚠️ Problem:
You try to assign multiple rows from a query into a single variable using SELECT INTO.
plsql
DECLARE
v_ename [Link]%TYPE;
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
EXCEPTION
END;
🧾 Explanation:
● SELECT INTO expects only one row.
⚠️ Problem:
You try to fetch a row, but no data is returned.
plsql
DECLARE
v_ename [Link]%TYPE;
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
EXCEPTION
END;
Exception Cause
TOO_MANY_ROWS Query returns more than one row into one variable
✅ Best Practices
● Use EXCEPTION blocks to catch these errors.
● Use IF EXISTS checks before SELECT INTO when unsure about data.
A stored procedure in PL/SQL is a named block of code that performs a specific task and is stored in the
database. You can call it again and again, just like a function in any programming language.
✅ Basic Syntax
pl
...
IS
-- Declarations
BEGIN
-- Executable statements
EXCEPTION
END procedure_name;
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
END;
🔸 To Execute:
plsql
BEGIN
welcome_message;
END;
📌 Output:
pgsql
BEGIN
END;
🔸 To Execute:
plsql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
BEGIN
greet_user('Alice');
END;
📌 Output:
Hello, Alice!
p_empno IN [Link]%TYPE,
IS
BEGIN
EXCEPTION
p_sal := 0;
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
DECLARE
v_salary [Link]%TYPE;
BEGIN
get_salary(7369, v_salary);
END;
BEGIN
p_num := p_num * 2;
END;
🔸 To Use It:
pl
DECLARE
v_number NUMBER := 5;
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
double_number(v_number);
END;
📌 Output:
javascript
Doubled Number: 10
🧠 Summary
Mode Use
📘 Functions in plsql
A PL/SQL function without parameters:
● Takes no input
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
● Is useful for returning fixed values, system info, or results based on internal logic only
RETURN VARCHAR2
IS
BEGIN
END;
BEGIN
DBMS_OUTPUT.PUT_LINE(get_welcome_message);
END;
📌 Output:
pgsql
Welcome to PL/SQL!
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
RETURN DATE
IS
BEGIN
RETURN SYSDATE;
END;
BEGIN
END;
RETURN NUMBER
IS
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
RETURN 100;
END;
BEGIN
END;
🧠 Key Notes
● No parameters means no input is needed when calling.
📦 Packages in PL/SQL :
A package in PL/SQL is a collection of related procedures, functions, variables, constants, cursors, and
exceptions that are stored together under a single name.
Think of it like a toolbox: all the tools (procedures/functions) you need for a task are grouped and organized in
one place.
1. Package Specification
This is the interface — it tells users what the package offers (but not how it works).
pl
PROCEDURE show_message;
END emp_utils;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
2. Package Body
This contains the code for the procedures and functions declared in the spec.
plsql
PROCEDURE show_message IS
BEGIN
END;
BEGIN
RETURN 30000;
END;
END emp_utils;
BEGIN
emp_utils.show_message;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
END;
📌 Output:
sql
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔁 Triggers in PL/SQL:
A trigger in PL/SQL is a named block of code that automatically executes in response to a specific event on
a table or view — such as an INSERT, UPDATE, or DELETE.
✅ What Is a Trigger?
● A trigger is fired automatically by the database when certain actions happen.
○ Auditing changes
ON table_name
BEGIN
-- Trigger logic
END;
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
emp_id NUMBER,
action VARCHAR2(10),
log_time TIMESTAMP
);
plsql
BEGIN
END;
Explanation:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
BEGIN
END IF;
END;
Explanation:
● If the new salary is lower, it raises an error and stops the update.
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
pl
BEGIN
END;
Explanation:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
INSTEAD OF Trigger
An INSTEAD OF trigger is a special type of row-level trigger defined on a view, not on a table. When
someone runs an INSERT, UPDATE, or DELETE on that view, Oracle fires the trigger instead of performing
the standard DML.
● Views based on joins, aggregates, or other complex SQL constructs are generally non-updatable.
● These triggers enable INSERT, UPDATE, or DELETE operations on such views by implementing
the logic to modify underlying tables manually.
● They allow better data validation, integrity checks, and business logic encapsulation at the database
layer.
🧪 Simple Syntax
sql
ON view_name
BEGIN
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
END;
sql
dept_name VARCHAR2(50)
);
emp_name VARCHAR2(50),
);
sql
FROM employees e
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
sql
BEGIN
VALUES (
:NEW.emp_id,
:NEW.emp_name,
);
END;
What Happens:
[Link] @teluguwebguru
SQL Notes TeluguWebGuru
🔍 Key Properties
● Only for views: Cannot be defined on tables. They let you override default behavior for DML on
views.
● Always row-level: Each row modification triggers the code.
● :NEW and :OLD values are accessible, but you cannot modify them within the trigger.
Use Cases
Views with validation needs Validate or transform input data before modifying base tables
Applications working via views Allow business logic in database layer instead of in application code
📝 Summary
● Use INSTEAD OF triggers to handle DML on views that are otherwise non-updatable.
● Triggers fire instead of the attempted view DML, leveraging :NEW (and optionally :OLD) values.
[Link] @teluguwebguru