Unit 2 Notes
Unit 2 Notes
A) CREATE
B) ALTER
C) DROP
D) TRUNCATE
Removes all records from a table but keeps the table structure.
A) INSERT
B) UPDATE
UPDATE Student
SET Age = 21
WHERE Roll_No = 101;
C) DELETE
3. SELECT Queries
The SELECT statement is used to retrieve data from one or more tables.
Basic Syntax
SELECT column_name
FROM table_name;
Examples
D) Using ORDER BY
SELECT *
FROM Student
ORDER BY Name;
E) Using DISTINCT
G) Using OR Operator
SELECT *
FROM Student
WHERE Age = 18 OR Age = 20;
H) Using LIKE
SELECT *
FROM Student
WHERE Name LIKE 'R%';
I) Using BETWEEN
SELECT *
FROM Student
WHERE Age BETWEEN 18 AND 25;
J) Using IN
SELECT *
FROM Student
WHERE Age IN (18, 20, 22);
Query
SELECT Name
FROM Student
WHERE Age > 19;
Output
Name
Rahul
Amit
DDL is used to define and modify database structures. Commands include CREATE,
ALTER, DROP, and TRUNCATE.
DML is used to manipulate data stored in tables. Commands include INSERT, UPDATE,
and DELETE.
SELECT Queries
Example:
It can be used with clauses such as WHERE, ORDER BY, DISTINCT, LIKE,
BETWEEN, and IN to filter and display data as required.
String, Date and Numerical Functions
SQL provides various built-in functions to manipulate strings, dates, and numeric values.
1. String Functions
String functions are used to perform operations on character data.
Examples
UPPER()
SELECT UPPER('rahul');
Output: RAHUL
LOWER()
SELECT LOWER('RAHUL');
Output: rahul
CONCAT()
SELECT CONCAT('Hello',' World');
LENGTH()
SELECT LENGTH('Database');
Output: 8
2. Date Functions
Date functions are used to work with date and time values.
Function Description
Examples
Current Date
SELECT CURRENT_DATE;
Extract Year
SELECT YEAR('2026-06-07');
Output: 2026
Extract Month
SELECT MONTH('2026-06-07');
Output: 6
Extract Day
SELECT DAY('2026-06-07');
Output: 7
3. Numerical Functions
Numerical functions are used to perform mathematical calculations.
Examples
ABS()
SELECT ABS(-25);
Output: 25
ROUND()
SELECT ROUND(12.56);
Output: 13
CEIL()
SELECT CEIL(12.1);
Output: 13
FLOOR()
SELECT FLOOR(12.9);
Output: 12
MOD()
SELECT MOD(10,3);
Output: 1
SQRT()
SELECT SQRT(25);
Output: 5
POWER()
SELECT POWER(2,3);
Output: 8
• UPPER()
• LOWER()
• LENGTH()
• CONCAT()
• SUBSTRING()
• TRIM()
Date Functions
Date functions work with date and time values. Common functions are:
• CURRENT_DATE
• NOW()
• YEAR()
• MONTH()
• DAY()
Numerical Functions
• ABS()
• ROUND()
• CEIL()
• FLOOR()
• MOD()
• SQRT()
• POWER()
These functions help in efficient data processing and manipulation in SQL databases.
They are commonly used with the SELECT statement and GROUP BY clause.
A) COUNT()
Output: 3
B) SUM()
Calculates the total.
Output: 240
C) AVG()
Output: 80
D) MAX()
Output: 90
E) MIN()
Output: 70
GROUP BY Example
SELECT Department, AVG(Marks)
FROM Student
GROUP BY Department;
2. View
A View is a virtual table created from one or more existing tables. It does not store data
physically; it stores only the SQL query.
Advantages of Views
• Improves security.
• Simplifies complex queries.
• Provides data independence.
• Restricts access to specific data.
Creating a View
CREATE VIEW Student_View AS
SELECT Roll_No, Name
FROM Student;
Using a View
SELECT * FROM Student_View;
Deleting a View
DROP VIEW Student_View;
Example
Student Table
View
CREATE VIEW StudentMarks AS
SELECT Name, Marks
FROM Student;
Output
Name Marks
Rahul 80
Name Marks
Priya 90
3. Indexes
An Index is a database object that improves the speed of data retrieval operations.
It works similarly to an index in a book, allowing the DBMS to locate records quickly
without scanning the entire table.
Advantages of Indexes
• Faster searching of records.
• Improves query performance.
• Reduces data access time.
Disadvantages of Indexes
• Requires additional storage space.
• Slows down INSERT, UPDATE, and DELETE operations because indexes must also
be updated.
Creating an Index
CREATE INDEX idx_name
ON Student(Name);
Deleting an Index
DROP INDEX idx_name;
Types of Indexes
1. Primary Index
2. Secondary Index
3. Unique Index
Aggregate functions perform calculations on multiple rows and return a single value.
View
A view is a virtual table created from one or more tables. It stores only the query and helps
improve security and simplify data access.
Index
An index is a database object used to improve the speed of data retrieval. It helps the DBMS
locate records quickly and enhances query performance.
Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name;
103 Amit IT 70
104 Neha IT 85
Output
Department AVG(Marks)
CSE 85
Department AVG(Marks)
IT 77.5
Output
Department COUNT(*)
CSE 2
IT 2
2. HAVING Clause
The HAVING clause is used to filter groups created by the GROUP BY clause.
WHERE filters rows before grouping, while HAVING filters groups after grouping.
Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;
Output
Department AVG(Marks)
CSE 85
Example 2: Departments Having More Than One Student
SELECT Department, COUNT(*)
FROM Student
GROUP BY Department
HAVING COUNT(*) > 1;
Execution Order
FROM
↓
WHERE
↓
GROUP BY
↓
HAVING
↓
SELECT
↓
ORDER BY
The GROUP BY clause is used to group rows having the same values in specified columns.
It is generally used with aggregate functions like COUNT(), SUM(), AVG(), MAX(), and
MIN().
Example:
HAVING Clause
The HAVING clause is used to filter groups formed by the GROUP BY clause. It is similar
to WHERE but works on grouped data.
Example:
Thus, GROUP BY creates groups of records, while HAVING applies conditions to those
groups.
Joins are useful when data is stored in multiple tables and needs to be retrieved together.
Example Tables
Student Table
Student_ID Name Dept_ID
101 Rahul 1
102 Priya 2
103 Amit 1
Department Table
Dept_ID Dept_Name
1 Computer
2 IT
3 Mechanical
Types of Joins
1. INNER JOIN
Returns only the matching records from both tables.
Syntax
SELECT columns
FROM table1
INNER JOIN table2
ON [Link] = [Link];
Example
SELECT [Link], Department.Dept_Name
FROM Student
INNER JOIN Department
ON Student.Dept_ID = Department.Dept_ID;
Output
Name Dept_Name
Rahul Computer
Priya IT
Amit Computer
Syntax
SELECT columns
FROM table1
LEFT JOIN table2
ON [Link] = [Link];
Example
SELECT [Link], Department.Dept_Name
FROM Student
LEFT JOIN Department
ON Student.Dept_ID = Department.Dept_ID;
Example
SELECT [Link], Department.Dept_Name
FROM Student
RIGHT JOIN Department
ON Student.Dept_ID = Department.Dept_ID;
Output
Name Dept_Name
Rahul Computer
Amit Computer
Priya IT
NULL Mechanical
Example
SELECT [Link], Department.Dept_Name
FROM Student
FULL OUTER JOIN Department
ON Student.Dept_ID = Department.Dept_ID;
5. CROSS JOIN
Returns the Cartesian Product of both tables.
Syntax
SELECT *
FROM Student
CROSS JOIN Department;
If Student has 3 rows and Department has 3 rows:
Result = 3 × 3 = 9 rows
6. SELF JOIN
A table is joined with itself.
Example
Employee Table
Output
Employee Manager
Rahul Amit
Priya Amit
Join Diagram
INNER JOIN
Common records only
LEFT JOIN
All Left + Matching Right
RIGHT JOIN
All Right + Matching Left
FULL JOIN
All records from both tables
CROSS JOIN
Cartesian Product
SELF JOIN
Table joined with itself
Difference Between INNER JOIN and
OUTER JOIN
INNER JOIN OUTER JOIN
Returns only matching rows Returns matching and non-matching rows
Excludes NULL matches Includes NULL matches
Faster Slightly slower
A JOIN is used to combine rows from two or more tables based on a related column.
Types of Joins
Example
SELECT [Link], Department.Dept_Name
FROM Student
INNER JOIN Department
ON Student.Dept_ID = Department.Dept_ID;
Joins are used to retrieve related data from multiple tables efficiently.
In DBMS and relational algebra, a relation (table) is considered a set of tuples (rows).
Example
Let:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
Properties of a Set
2. Set Operations
Set operations are used to combine or compare the results of two queries.
A) UNION
Combines results of two queries and removes duplicates.
Syntax
SELECT column_name FROM Table1
UNION
SELECT column_name FROM Table2;
Example
Table A:
Name
Rahul
Priya
Table B:
Name
Priya
Amit
SELECT Name FROM A
UNION
SELECT Name FROM B;
Output
Name
Rahul
Priya
Amit
B) UNION ALL
Combines results and keeps duplicates.
Output
Name
Rahul
Priya
Priya
Amit
C) INTERSECT
Returns only common records from both queries.
Output
Name
Priya
D) EXCEPT (or MINUS in some DBMSs)
Returns records present in the first query but not in the second.
Output
Name
Rahul
3. Set Membership
Set Membership checks whether a value belongs to a set of values.
Syntax
SELECT *
FROM Student
WHERE column_name IN (value1, value2, value3);
Example
Student Table:
Roll_No Name
101 Rahul
102 Priya
103 Amit
SELECT *
FROM Student
WHERE Roll_No IN (101, 103);
Output
Roll_No Name
101 Rahul
103 Amit
NOT IN Operator
Used to select values that do not belong to a set.
SELECT *
FROM Student
WHERE Roll_No NOT IN (101, 103);
Output
Roll_No Name
102 Priya
A set is a collection of distinct elements. In DBMS, relations are treated as sets of tuples.
Set Operations
Set Membership
Set membership checks whether a value belongs to a set. It is implemented using the IN
operator.
Example:
SELECT *
FROM Student
WHERE Roll_No IN (101, 103);
These concepts help perform powerful data retrieval and comparison operations in SQL.
Definition
A subquery is a SELECT statement nested inside another SQL statement such as
SELECT, INSERT, UPDATE, or DELETE.
Syntax
SELECT column_name
FROM table_name
WHERE column_name OPERATOR
(SELECT column_name
FROM table_name
WHERE condition);
Example
Calculation
Output
Name Marks
Priya 90
2. Multiple-Row Subquery
Returns multiple rows.
Example
Find students whose marks are equal to any marks greater than 75.
SELECT Name
FROM Student
WHERE Marks IN
(SELECT Marks
FROM Student
WHERE Marks > 75);
Output
Name
Rahul
Priya
Example
SELECT Name
FROM Student
WHERE Roll_No IN
(SELECT Roll_No
FROM Student
WHERE Marks > 80);
Output
Name
Priya
Example
SELECT Name
FROM Student S
WHERE EXISTS
(SELECT *
FROM Student
WHERE Marks > 85);
Since a student with marks greater than 85 exists, the condition becomes true.
Example
SELECT Name
FROM Student
WHERE Marks > ANY
(SELECT Marks
FROM Student
WHERE Marks < 80);
Example
SELECT Name
FROM Student
WHERE Marks > ALL
(SELECT Marks
FROM Student
WHERE Marks < 80);
Output
Name
Rahul
Priya
Department Table
Dept_ID Dept_Name
10 HR
20 IT
Query
SELECT Name
FROM Employee
WHERE Dept_ID =
(SELECT Dept_ID
FROM Department
WHERE Dept_Name = 'IT');
Output
Name
Priya
Exam Answer (5 Marks)
Nested Queries (Subqueries)
A Nested Query or Subquery is a query placed inside another SQL query. The inner query
executes first, and its result is passed to the outer query.
1. Single-row subquery
2. Multiple-row subquery
3. Subquery with IN
4. Subquery with EXISTS
5. Subquery with ANY
6. Subquery with ALL
Example
SELECT Name
FROM Student
WHERE Marks >
(SELECT AVG(Marks)
FROM Student);
Nested queries are used to perform complex data retrieval operations and make SQL
statements more powerful and flexible.
DCL Commands
A) GRANT
Syntax:
GRANT privilege_name
ON table_name
TO user_name;
Example:
Meaning: User1 can view and insert records into the Student table.
B) REVOKE
Syntax:
REVOKE privilege_name
ON table_name
FROM user_name;
Example:
REVOKE INSERT
ON Student
FROM User1;
Meaning: User1 can no longer insert records into the Student table.
Advantages of DCL
• Provides database security.
• Controls user access.
• Protects sensitive data.
• Prevents unauthorized operations.
TCL Commands
A) COMMIT
COMMIT;
B) ROLLBACK
Example:
ROLLBACK;
C) SAVEPOINT
Creates a point within a transaction to which you can later roll back.
Example:
SAVEPOINT sp1;
D) ROLLBACK TO SAVEPOINT
Example:
ROLLBACK TO sp1;
SAVEPOINT sp1;
UPDATE Student
SET Age = 21
WHERE Roll_No = 101;
ROLLBACK TO sp1;
COMMIT;
Explanation
• Record is inserted.
• Savepoint sp1 is created.
• Age is updated.
• Rollback returns to sp1, canceling the update.
• COMMIT saves the remaining changes.
Transaction States
Active
↓
Partially Committed
↓
Committed
If an error occurs:
Active
↓
Failed
↓
Rolled Back
Example:
Commands:
Example:
SAVEPOINT sp1;
ROLLBACK TO sp1;
COMMIT;
Thus, DCL provides security by controlling user permissions, while TCL ensures data
consistency by managing transactions.