Unit-02(Relational Data Model and Database Languages)
Relational Model in DBMS
The Relational Model is a way of organizing data in a database using tables. Each table, also
called a relation, is made up of rows and columns:
• Rows (Tuples): Each row represents a single record or object (for example, one student).
• Columns (Attributes): Each column represents a property or detail about that record (for
example, the student’s name, age, or phone number).
In simple words, the relational model tells us how data should be stored, arranged, and
managed in a relational database. It takes the abstract design from an ER diagram and converts
it into a structure that can actually be used in databases like MySQL, Oracle, or SQL Server.
Example:
Imagine we have a table named STUDENT. It stores information about students. The table might
have columns like:
• ROLL_NO
• NAME
• ADDRESS
• PHONE
• AGE
Each row in this table would represent one student, with their details filled in under these
Columns.
Key Terms in the Relational Model
1. Attribute
Attributes are like the headings of the columns in a table.
They describe the properties of an entity.
Example: In a STUDENT table, attributes can be ROLL_NO, NAME,
ADDRESS, PHONE, and AGE.
2. Relation Schema
A relation schema is the blueprint or structure of a table.
It shows the table’s name and its attributes.
Example: STUDENT (ROLL_NO, NAME, ADDRESS, PHONE, AGE)
This means the STUDENT table has these five columns.
If the design includes multiple tables, the whole set is called a Relational Schema.
3. Tuple
A tuple is just a row in the table.
It stores the actual data of one entity.
Example:(1, RAM, DELHI, 9455123451, 18)
This is one tuple (one student’s details) in the STUDENT table.
4. Relation Instance
A relation instance is the set of all rows (tuples) present in a table at a
particular moment.
It can change over time when we add, delete, or update records.
Example: The current list of all students in the STUDENT table is its relation
Instance.
5. Degree
The degree of a relation is the number of attributes (columns) in a table.
Example: The STUDENT table has 5 attributes → so its degree is 5.
6. Cardinality
Cardinality means the number of rows (tuples) in a table.
Example: If STUDENT table has 4 students (rows), then its cardinality is 4.
7. NULL Values
A NULL value means the data is missing, unknown, or not available.
Example: If STUDENT with ROLL_NO = 4 has no phone number stored,
then PHONE = NULL
Think of it this way:
• Attributes = Column names
• Tuple = One row (record)
• Degree = Number of columns
• Cardinality = Number of rows
• Relation Schema = Design of the table
Constraints in Relational Model
When designing a database, we set some rules (constraints) to make sure the data stored is correct,
meaningful, and consistent.
👉These rules are always checked before any operation like insertion, deletion, or update.
👉If a rule is broken, the operation will fail.
The main types of constraints are:
1. Domain Constraints
These rules ensure that the value in each column (attribute) must come from its
defined domain (data type).
Example:
o AGE must be an integer (like 18, 20, and 21). You can’t insert text like
“Eighteen”.
o NAME must be text, not numbers.
Domains are defined by data types such as:
o Numeric types → INT, FLOAT (for numbers and decimals).
o Character types→ CHAR, VARCHAR, TEXT (for words or text).
o Boolean → TRUE/FALSE values.
o Special types → DATE, TIME, TIMESTAMP, MONEY, etc.
👉In short: Domain constraints check that the right type of data goes into the right column.
2. Key Integrity (Uniqueness Rule)
Every table must have one or more keys that uniquely identify each row.
Example:
o In the STUDENT table, ROLL_NO is the key.
o No two students can have the same roll number.
o A roll number can never be left empty (NULL).
In short: Keys make sure each row is unique and identifiable.
3. Referential Integrity Constraints
These rules maintain the link between two tables.
If a column in one table refers to another table, its value must exist in that second
Table.
Example:
STUDENT Table
ROLL_NO NAME ADDRESS PHONE AGE BRANCH_CODE
1 RAM DELHI 9455123451 18 CS
2 RAMESH GURGAON 9652431543 18 CS
3 SUJIT ROHTAK 9156253131 20 ECE
4 SURESH DELHI NULL 18 IT
BRANCH Table
BRANCH_CODE BRANCH_NAME
CS COMPUTER SCIENCE
IT INFORMATION TECHNOLOGY
ECE ELECTRONICS & COMMUNICATION ENGG
CV CIVIL ENGINEERING
Here, BRANCH_CODE in STUDENT must match a BRANCH_CODE in the BRANCH
table.
So, if someone tries to insert a student with BRANCH_CODE = "ME" (Mechanical), the
database will reject it, because "ME" is not in the BRANCH table.
In short: Referential integrity makes sure data in one table is consistent with related data in
another table.
4. Entity Integrity Constraint
This rule makes sure that every row (tuple) in a table can be uniquely identified.
In other words:
o Every table must have a Primary Key.
o The Primary Key cannot be NULL (because then we wouldn’t be able to
identify the record).
o The Primary Key must be unique (no two rows can have the same key
value).
Example: STUDENT Table
ROLL_NO (PK) NAME AGE
1 RAM 18
2 RAMESH 19
3 SUJIT 20
• Here, ROLL_NO is the primary key.
• If we try to insert a student without a roll number (NULL) → not allowed.
• If we try to insert another student with ROLL_NO = 2 (duplicate) → Not allowed.
In short: Entity Integrity ensures that each record in a table is unique and identifiable.
✅ Summary
• Domain Constraint → correct type of data.
• Key Integrity → Unique & non-null identifiers.
• Referential Integrity → Consistent links between tables.
Relational Algebra in DBMS
Relational Algebra is like the mathematics of databases.
It provides a formal set of operations (rules) that we can use to query and manipulate
data stored in relational databases.
Think of it as the foundation of SQL. Every SQL query you write is built on the concepts
of relational algebra.
It tells how to retrieve data step by step.
It makes queries easier to optimize for speed and performance. Key Concepts
Before learning operations, let’s clarify some terms:
1. Relations →A table in the database (with rows and columns).
2. Tuples →A row in the table (one record).
3. Attributes →The columns (properties of the data). Example: Name, Age,
Grade.
4. Domains →The type of values allowed in each attribute. Example: Age
can only be numbers, not text.
Basic Operators in Relational Algebra
These are the building blocks of queries:
1. Selection (σ) → Filters rows based on a condition.
Example: If we have a relation R with attributes A, B, and C, and we want to select tuples where
C > 3, we write: σ(c>3)(R) will select the tuples which have c more than 3.
A B C
Output:
A B C
1 2 4
2 2 3 1 2 4
3 2 3 4 3 4
4 3 4
2. Projection (π) →Picks specific columns.
Example: Suppose we want columns B and C from Relation R. π(B,C)(R)
will show following columns.
Output:
B C
2 4
2 3
3 4
3. Union (U) → Combines results from two tables (removes duplicates).
Example: Consider the following table of Students having different optional subjects in their
course.
FRENCH
Student_Name Roll_Number
Ram 01
Mohan 02
Vivek 13
π(Student_Name)(FRENCH) U π(Student_Name)(GERMAN) Output:
Student_Name
Ram
Mohan
Vivek
Geeta
Shyam
Rohan
4. Set Difference (−) → Finds rows present in one table but not in another.
Example: To find students enrolled only in FRENCH but not in GERMAN, we write:
π(Student_Name)(FRENCH) - π(Student_Name)(GERMAN)
Student_Name
Ram
Mohan
5. Rename (ρ) → Gives temporary names to tables or columns. Example:
We can rename an attribute B in relation R to D
A B C
1 2 4
2 2 3
3 2 3
4 3 4
ρ(D/B)R will rename the attribute 'B' of the relation by 'D".
Output Table:
A D C
1 2 4
2 2 3
3 2 3
4 3 4
6. Cartesian Product (×) → Combines every row of one table with every
row of another (used before joins).
Let’s say A and B, so the cross product between A X B will result in all the attributes of A
followed by each attribute of B. Each record of A will pair with every record of B. Relation A:
Name Age Sex
Ram 14 M
Output: If relation A has 3 rows and relation B has 2 rows, the Cartesian product A × B will
result in 6 rows.
Name Age Sex ID Course
Ram 14 M 1 DS
Ram 14 M 2 DBMS
Sona 15 F 1 DS
Sona 15 F 2 DBMS
DS
Kim 20 M 1
Kim 20 M 2 DBMS
Derived (Advanced) Operators
These are built using the basic ones:
1. Joins → Combine related rows from two tables.
o Inner Join →Only matching rows.
o Natural Join → Joins on same-named attributes automatically.
o Outer Joins (Left, Right, Full) → Keep unmatched rows with
NULLs.
2. Intersection (∩) → Finds rows common to both tables.
3. Division (÷) → Used for “for all” queries.
o Example: Find students who are enrolled in all courses.
1) JOIN Operator
A JOIN is an operation in DBMS that combines rows from two or more tables based on a related
column between them.
The main purpose of a join is to retrieve data spread across multiple tables — in other words, to
perform multi-table queries.
It is represented by the symbol .
Syntax
R3 ← R1 <join_condition> R2
Here: R1 and R2 are the two tables (relations) being joined. R3 is the result table after performing
the join.
Example:
Temp ← student ([Link] = [Link]) exam
Here, S and E are aliases for the tables student and exam.
Example
Let’s consider two tables:
Table 1 – Student
ROLL_NO NAME ADDRESS PHONE AGE
1 HARSH DELHI xxxxxxxxxx 18
2 PRATIK BIHAR xxxxxxxxxx 19
3 PRIYANKA SILIGURI xxxxxxxxxx 20
4 DEEP RAMNAGAR xxxxxxxxxx 18
5 SAPTARSHI KOLKATA xxxxxxxxxx 19
Table 2 – Student_Course
ROLL_NO COURSE_ID
1 1
2 2
3 2
ROLL_NO COURSE_ID
4 3
5 1
The two tables are connected by the common column ROLL_NO.
Performing a join:
Student Student_Course Result:
ROLL_NO NAME ADDRESS PHONE AGE COURSE_ID
1 HARSH DELHI xxxxxxxxxx 18 1
2 PRATIK BIHAR xxxxxxxxxx 19 2
3 PRIYANKA SILIGURI xxxxxxxxxx 20 2
4 DEEP RAMNAGAR xxxxxxxxxx 18 3
5 SAPTARSHI KOLKATA xxxxxxxxxx 19 1
Types of Joins in DBMS
There are several types of joins in SQL, each used for a specific purpose. The
most commonly used ones are:
1. Inner Join
2. Outer Join
1. Inner Join
An Inner Join combines rows from two or more tables and returns only the rows that have
matching values in both tables.
Inner joins can be of three types:
• Conditional (Theta) Join
• Equi Join
• Natural Join
(a) Conditional (Theta) Join
In a conditional join, tables are joined based on a specific condition that can use comparison
operators like <, >, <=, >=, !=, and =.
Example:
Table A
R S
10 5
7 20
Table B
T U
10 12
17 6
Join: A
(S < T) B
Output:
R S T U
10 5 10 12
Explanation:
Only the row where S < T is true is included in the result.
(b) Equi Join
In an Equi Join, tables are joined based on the equality condition (=).
Example:
Table A
Column A Column B
a a
a b
Table C
Column A Column B
a a
a c
Join:
A ([Link] = [Link]) C
Output:
Column A Column B
a a
Explanation:
Only rows where the value of Column B is the same in both tables are returned.
(c) Natural Join
In a Natural Join, tables are automatically joined based on columns with the same name and
data type.
You don’t need to specify a condition.
Example:
Table A
Number Square
2 4
3 9
Table B
Number Cube
2 8
3 27
Join:
A B
Output:
Number Square Cube
2 4 8
3 9 27
Explanation:
The column Number is common in both tables, so it appears only once in the result.
2. Outer Join
An Outer Join returns not only the matching rows but also the non-matching rows from
one or both tables.
Missing values are filled with NULL.
Types of Outer Joins:
• Left Outer Join
• Right Outer Join
• Full Outer Join
(a) Left Outer Join ( )
Returns all records from the left table, and matching records from the right table. If no
match is found, NULL is used for the right-side columns.
Example: .Table A
Number Square
2 4
3 9
4 16
Table B
Number Cube
2 8
3 27
Number Cube
5 125
Join:
A⟕B
Output:
Number Square Cube
2 4 8
3 9 27
4 16 NULL
Explanation:
The value 4 exists only in Table A, so its Cube is NULL.
(b) Right Outer Join (⟖)
Returns all records from the right table, and matching records from the left table. If no
match is found, NULL is used for the left-side columns.
Join:
A⟖B
Output:
Number Square Cube
2 4 8
3 9 27
5 NULL 125
Explanation:
The value 5 exists only in Table B, so its Square is NULL.
(c) Full Outer Join (⟗)
A Full Outer Join combines the results of both left and right outer joins.
It includes all rows from both tables — and where no match exists, NULLs are filled in.
Join:
A B
Output:
Number Square Cube
2 4 8
3 9 27
4 16 NULL
5 NULL 125
Explanation:
• For 4, no Cube exists → NULL.
• For 5, no Square exists → NULL.
2️) Set Intersection (∩)
i. Returns only rows common to both tables.
ii. Like set theory intersection. iii. Works only if
both relations have the same attributes.
Example: Consider the following table of Students having different optional subjects in their
course.
Geeta 17
Shyam 21
Rohan 25
From the above table of FRENCH and GERMAN, the Set Intersection is used as follows:
Output:
Student_Name
Vivek
Geeta
π(Student_Name)(FRENCH ∩ π(Student_Name)(GERMAN)
Explanation: The only constraint in the Set Difference between two relations is that both relations
must have the same set of Attributes.
3️) Division (÷)
• Used for “for all” queries.
• Returns tuples in one relation that are related to all tuples in another
relation.
Example:
Find students who are enrolled in all courses.
Student_Course ( Dividend Table):
Student_ID Course_ID
101 C1
101 C2
102 C1
103 C1
103 C2
Course ( Divisor Table):
Course_ID
C1
Course_ID
C2
Example: Query is to find students who are enrolled in all courses listed in the Course
table. In this case, students must be enrolled in both C1 and C2.
Student_Course(Student_ID, Course_ID)÷ Course(Course_ID)
Output:
S tudent_ID
101
103
Relational Calculus
Relational Algebra = procedural → tells how to get data.
Relational Calculus = non-procedural → tells what data you want, not how to
fetch it.
Queries are written in the form of logical formulas (conditions) instead of step-
by step operations.
It is the theoretical foundation for SQL.
Two types:
o Tuple Relational Calculus (TRC)
o Domain Relational Calculus (DRC)
Tuple Relational Calculus (TRC)
Tuple Relational Calculus (TRC) is a non-procedural query language used to retrieve data from a
relational database.
This means — in TRC, we describe what data we want, not how to get it.
It is based on first-order predicate logic and uses tuple variables to represent rows (tuples) of
tables.
Basic Syntax
{ t | P(t) }
Where:
• t → Tuple variable (acts as a placeholder for each row)
• P(t) → Predicate (condition that the tuple must satisfy)
• {} → Denotes the result set (all tuples satisfying the condition)
Logical Operators Used in TRC
Operator Meaning
∧ AND
∨ OR
¬ NOT
Quantifiers Used in TRC
Symbol Meaning Example
∃ “There exists” ∃ t ∈ r (Q(t)) → There exists a tuple t in relation r satisfying Q(t)
∀ “For all” ∀ t ∈ r (Q(t)) → For all tuples t in relation r, Q(t) is true
Example Table: Employees
Employee ID Name Salary Department ID
101 Riya 60000 D1
102 Aman 48000 D2
103 Neha 75000 D1
Query Example:
Find the names of all employees earning more than $50,000.
TRC Query:
{ t | Employees(t) ∧ [Link] > 50000 }
Explanation:
• Employees(t) → means “t” is a tuple from the Employees table.
• [Link] > 50000 → only those tuples where the salary is more than 50,000 are selected.
The result is the set of tuples where employees earn more than $50,000.
Key Idea
TRC is non-procedural — it tells what data to retrieve, not how to retrieve it. This makes
it more mathematical and declarative, often used in theory and academic concepts, not in
practical SQL systems.
Tuple Relational Calculus Query Form
A general TRC query looks like this:
{ t | P(t) }
• t → represents the result tuples.
• P(t) → is a condition (predicate) that must be true for t to be included.
P(t) can use logical connectors like:
• AND ( ∧ )
• OR ( ∨ )
• NOT ( ¬ )
And quantifiers:
• ∃ → There exists
• ∀ → For all
Domain Relational Calculus (DRC)
Domain Relational Calculus is a non-procedural query language in DBMS where you describe
what data you want, not how to get it.
It is based on domain variables that take individual attribute values (not entire tuples like in TRC).
Syntax:
{⟨a1,a2,a3,...,an⟩ ∣ P(a1,a2,a3,...,an)}\{ \langle a_1, a_2, a_3, ..., a_n \rangle \ | \ P(a_1, a_2, a_3,
..., a_n) \}{⟨a1,a2,a3,...,an⟩ ∣ P(a1,a2,a3,...,an)}
• a1,a2,...,ana_1, a_2, ..., a_na1,a2,...,an: Domain variables (represent individual column
values)
• P(...)P(...)P(...): Predicate or condition that must be true
Example Tables
Customer
Customer name Street City
Saurabh A7 Patiala
Mehak B6 Jalandhar
Sumiti D9 Ludhiana
Customer name Street City
Ria A5 Patiala
Branch
Branch name Branch City
ABC Patiala
DEF Ludhiana
GHI Jalandhar
Account
Account number Branch name Balance
1111 ABC 50000
1112 DEF 10000
1113 GHI 9000
1114 ABC 7000
Loan
Loan number Branch name Amount
L33 ABC 10000
L35 DEF 15000
L49 GHI 9000
L98 DEF 65000
Borrower
Customer name Loan number
Saurabh L33
Mehak L49
Ria L98
Depositor
Customer name Account number
Saurabh 1111
Customer name Account number
Mehak 1113
Suniti 1114
Example 1:
Find the loan number, branch, and amount of loans ≥ 10000 DRC
Expression:
{⟨lno,bname,amt⟩ ∣ Loan(lno,bname,amt) ∧ amt≥10000}
Result:
Loan number Branch name Amount
L33 ABC 10000
L35 DEF 15000
L98 DEF 65000
Example 2:
Find the loan numbers for loans ≥ 10000 DRC
Expression:
{⟨lno⟩ ∣ ∃bname,amt(Loan(lno,bname,amt)∧amt≥10000)}
Result:
Loan number
L33
L35
L98
Example 3:
Find customer names who have both a loan and an account.
DRC Expression:
{⟨cname⟩ ∣ ∃lno(Borrower(cname,lno)) ∧ ∃accno(Depositor(cname,accno))}
Result:
Customer name
Saurabh
Mehak
Example 4:
Find the names of all customers having a loan at the “ABC” branch.
DRC Expression:
{⟨cname⟩ ∣ ∃lno,amt(Borrower(cname,lno) ∧ Loan(lno,“ABC”,amt))}
Result:
Customer name
Saurabh
Tuple Relational Calculus (TRC) is a non-procedural query language used to retrieve data from a
relational database.
This means — in TRC, we describe what data we want, not how to get it.
It is based on first-order predicate logic and uses tuple variables to represent rows (tuples) of
tables.
Basic Syntax
{ t | P(t) }
Where:
• t → Tuple variable (acts as a placeholder for each row)
• P(t) → Predicate (condition that the tuple must satisfy)
• {} → Denotes the result set (all tuples satisfying the condition)
Logical Operators Used in TRC
Operator Meaning
∧ AND
∨ OR
¬ NOT
Quantifiers Used in TRC
Symbol Meaning Example
∃ “There exists” ∃ t ∈ r (Q(t)) → There exists a tuple t in relation r satisfying Q(t)
∀ “For all” ∀ t ∈ r (Q(t)) → For all tuples t in relation r, Q(t) is true
Example Table: Employees
Employee ID Name Salary Department ID
101 Riya 60000 D1
102 Aman 48000 D2
103 Neha 75000 D1
Query Example:
Find the names of all employees earning more than $50,000.
TRC Query:
{ t | Employees(t) ∧ [Link] > 50000 }
Explanation:
• Employees(t) → means “t” is a tuple from the Employees table.
• [Link] > 50000 → only those tuples where the salary is more than 50,000 are selected.
The result is the set of tuples where employees earn more than $50,000.
Key Idea
TRC is non-procedural — it tells what data to retrieve, not how to retrieve it. This makes
it more mathematical and declarative, often used in theory and academic concepts, not in
practical SQL systems.
Tuple Relational Calculus Query Form
A general TRC query looks like this:
{ t | P(t) }
• t → represents the result tuples.
• P(t) → is a condition (predicate) that must be true for t to be included.
P(t) can use logical connectors like:
• AND ( ∧ )
• OR ( ∨ )
• NOT ( ¬ )
And quantifiers:
• ∃ → There exists
• ∀ → For all
What is SQL?
SQL (Structured Query Language) is a standard language used to interact with relational
databases.
It allows users to store, retrieve, update, and manage data efficiently.
Features of SQL
User-friendly syntax (similar to English).
Powerful and widely used across industries.
Supports large datasets and complex queries.
How SQL Works
SQL queries go through several steps inside a DBMS (MySQL, Oracle, SQL Server, PostgreSQL,
etc.):
1. Input – User submits a command (SELECT, INSERT, UPDATE, DELETE).
2. Parsing – SQL engine checks syntax and validates schema.
3. Optimization – Query optimizer generates the most efficient execution plan using indexes
and statistics.
4. Execution – DBMS executes the query and accesses/modifies data.
5. Output – Returns result set (SELECT) or success message (INSERT/UPDATE/DELETE).
Key Components of an SQL System
Database – Collection of related data stored in tables.
Tables – Contain rows (records) and columns (fields).
Indexes – Improve query performance by speeding up searches.
Views – Virtual tables created from SELECT queries.
Stored Procedures – Predefined SQL programs stored in the database.
Transactions – Ensure ACID properties and group multiple operations.
Security & Permissions – GRANT and REVOKE for access control.
Joins – Combine data from multiple related tables.
Rules for Writing SQL Queries
1. End each SQL statement with a semicolon (;).
2. SQL keywords are case-insensitive (SELECT = select).
3. Whitespace and line breaks are allowed.
4. Avoid using reserved keywords as table/column names.
5. Use comments:
o Single-line → -- comment
o Multi-line → /* comment */
6. Use constraints (NOT NULL, UNIQUE, PRIMARY KEY, etc.).
7. Enclose string values in single quotes (‘example’).
8. Naming rules:
o Start with a letter
o Max 30 characters
o Only letters, numbers, underscores allowed
Types of SQL Commands
1. DDL – Data Definition Language
Used to define or modify the structure of database objects.
Command Description
CREATE Creates tables, views, indexes
ALTER Modifies existing objects
DROP Deletes entire object
Command Description
TRUNCATE Removes all rows but keeps structure
2. DML – Data Manipulation Language
Used to modify data inside tables.
Command Description
INSERT Adds new records
UPDATE Modifies existing data
DELETE Removes records
3. DQL – Data Query Language
Command Description
SELECT Retrieves data from tables
4. DCL – Data Control Language
Command Description
GRANT Gives user privileges
REVOKE Removes privileges
5. TCL – Transaction Control Language
Command Description
COMMIT Saves changes permanently
ROLLBACK Undoes changes
SAVEPOINT Creates a temporary rollback point
Benefits of SQL
Efficient for large and complex data.
Standardized by ANSI and ISO.
Scalable for small to enterprise systems.
Flexible with procedural extensions (PL/SQL, T-SQL).
Secure with user privileges and permissions.
Limitations of SQL
1. Complex for advanced tasks (optimization, indexing).
2. Not ideal for massive unstructured or distributed data.
3. Vendor-specific differences (MySQL vs Oracle vs SQL Server).
4. Limited native support for real-time analytics in traditional systems.
Real-World Applications of SQL
E-Commerce: Orders, customers, inventory
Healthcare: Patient records, prescriptions
Banking: Accounts, transactions, reports
Web Development: CMS, dynamic websites
Data Science: Data extraction & preprocessing for ML
SQL Operators
Operators are used inside a WHERE clause to filter and compare data.
Types of SQL Operators
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Compound Operators
6. Special Operators
1) Arithmetic Operators
Used for mathematical calculations.
Operator Description Example
+ Addition SELECT 10 + 5;
Operator Description Example
- Subtraction SELECT 10 - 5;
* Multiplication SELECT 10 * 5;
/ Division SELECT 10 / 2;
% Modulo (remainder) SELECT 10 % 3;
2) Comparison Operators
Used to compare values.
Operator Meaning Example
= Equal to WHERE name = 'John'
> Greater than WHERE price > 200
< Less than WHERE price < 100
>= Greater or equal WHERE age >= 18
<= Less or equal WHERE salary <= 50000
<> / != Not equal WHERE city <> 'London'
3) Logical Operators
Operator Description Example
AND TRUE if all conditions are true WHERE country = 'USA' AND city = 'NY'
OR TRUE if any condition is true WHERE city = 'London' OR city = 'Paris'
NOT Negates a condition WHERE NOT country = 'USA'
4) Special Operators
Operator Description Example
IN Matches any value in a list WHERE city IN ('Delhi','Mumbai')
BETWEEN Checks range WHERE price BETWEEN 10 AND 50
Operator Description Example
LIKE Pattern matching WHERE name LIKE 'A%'
IS NULL Checks NULL WHERE address IS NULL
EXISTS Checks subquery result WHERE EXISTS (SELECT * FROM Orders)
WHERE marks > ALL (SELECT marks
ALL Compares with all values
FROM test)
WHERE salary > ANY (SELECT salary
ANY / SOME Compares with any value
FROM emp)
Combines results & removes
UNION
duplicates
INTERSECT Common rows
EXCEPT / Rows from first query not in
MINUS second
Operator Precedence
Order in which SQL evaluates operators:
1. Parentheses (highest priority)
2. Arithmetic:
o *, /, %
o +, -
3. Comparison operators: =, >, <, <=, >=, <>
4. Logical:
o NOT
o AND
o OR (lowest)
Example:
WHERE age > 18 AND salary > 50000 OR experience < 5
Evaluation order:
1. age > 18
2. salary > 50000
3. experience < 5
4. (age > 18 AND salary > 50000)
5. Final OR condition
Tables
A table stores data in rows and columns.
Constraints:
PRIMARY KEY – Unique identifier
FOREIGN KEY – Maintains relationships
NOT NULL – Cannot be empty
UNIQUE – No duplicate values
Example:
CREATE TABLE Employee (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
emp_salary DECIMAL(10,2),
emp_city VARCHAR(50)
);
Views
A View is a virtual table based on a SELECT query.
It does not store data physically.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE condition;
Examples:
1. Simple View
CREATE VIEW EmployeeView AS
SELECT Name, Department FROM Employees;
2. Conditional View
CREATE VIEW HighSalary AS
SELECT Name, Salary FROM Employees
WHERE Salary > 50000;
3. Join View
CREATE VIEW EmpDeptView AS
SELECT [Link], [Link]
FROM Employee E
JOIN Department D ON [Link] = [Link];
Modify View
CREATE OR REPLACE VIEW HighSalary AS ...
Delete View
DROP VIEW HighSalary;
Queries vs Subqueries
Feature Query Subquery
Execution Independent Executes first & used by outer query
Purpose Complete operation Provides value/result to outer query
Syntax Standalone Inside parentheses
Nesting Cannot be nested Can be nested
Example SELECT * FROM Employees SELECT * WHERE id IN (SELECT id ...)
Types of Subqueries
1. Single-row – returns 1 row
2. Multi-row – returns multiple rows
3. Correlated – depends on outer query
4. Non-correlated – independent from outer query
Aggregate Functions
Used to perform calculations on multiple rows.
Function Description
SUM() Total
AVG() Average
COUNT() Number of rows
MIN() Minimum value
MAX() Maximum value
Example:
SELECT emp_city, COUNT(*) FROM Employee
GROUP BY emp_city;
Joins
Used to combine data from multiple tables.
Type Description
INNER JOIN Matching rows only
LEFT JOIN All rows from left + matched from right
RIGHT JOIN All rows from right + matched from left
FULL OUTER JOIN Rows with match in either table
Set Operations
UNION – Combines results & removes duplicates
INTERSECT – Only common rows
EXCEPT / MINUS – Rows in first set not in second
Cursors (PL/SQL)
Cursor is a pointer to the result of a query.
Types:
1. Implicit – Created automatically
2. Explicit – Created by user
Example:
DECLARE
CURSOR emp_cursor IS
SELECT emp_name, emp_salary FROM Employee;
emp_record emp_cursor%ROWTYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO emp_record;
EXIT WHEN emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(emp_record.emp_name || ' - ' || emp_record.emp_salary);
END LOOP;
CLOSE emp_cursor;
END;
Stored Procedures
Pre-compiled SQL/PLSQL code stored in the database.
Example:
CREATE OR REPLACE PROCEDURE GiveBonus AS
BEGIN
UPDATE Employee
SET emp_salary = emp_salary * 1.10
WHERE emp_salary < 50000;
END;
EXEC GiveBonus;
PL/SQL Overview
PL/SQL is Oracle’s procedural extension for SQL.
Features:
Variables & Constants
IF / CASE
Loops
Exception Handling
Cursors
Procedures & Functions
Example:
DECLARE
v_salary Employee.emp_salary%TYPE;
BEGIN
SELECT emp_salary INTO v_salary FROM Employee WHERE emp_id = 101;
IF v_salary < 50000 THEN
DBMS_OUTPUT.PUT_LINE('Salary is below 50000');
ELSE
DBMS_OUTPUT.PUT_LINE('Salary is 50000 or above');
END IF;
END;