M4_SQL
M4_SQL
Systems (DBMS) subject, written in simple English. This will help you prepare for university
📘
exams and improve your understanding of all the listed concepts.
🔹
SQL is categorized into several types of statements. The two main categories are:
💡
• These commands directly affect the structure of the database.
Common DDL Commands:
Command Description
CREATE Creates a new table, view, or other object
ALTER Modifies the structure of an existing table
DROP Deletes an object (table, view, etc.) permanently
🧾
TRUNCATE Deletes all data from a table but not its structure
Example:
CREATE TABLE Employee (
Name VARCHAR(100),
Salary DECIMAL(10,2)
);
Command Description
INSERT Adds new records
UPDATE Modifies existing records
DELETE Removes records
🧾
SELECT Retrieves records
Example:
INSERT INTO Employee (EmpID, Name, Salary) VALUES (1, 'Amit', 50000);
🔷
DELETE FROM Employee WHERE EmpID = 1;
🧾
• Each column has a specific data type.
🔷
102 Sneha IT 92
🔹
Set operations combine the results of two or more SELECT queries.
3.1 UNION
Combines results and removes duplicates.
SELECT Name FROM CSE_Students
UNION
🔹
SELECT Name FROM IT_Students;
UNION ALL
INTERSECT
🔹
SELECT Name FROM IT_Students;
EXCEPT
🔷
MAX() Finds the largest (maximum) value
✅
This function returns the total number of records (rows) in a table or satisfying a condition.
Syntax:
🧾
SELECT COUNT(column_name) FROM table_name;
Example:
SELECT COUNT(*) FROM Student;
✅
Returns the sum of all values in a column (only for numeric data types).
Syntax:
🧾
SELECT SUM(column_name) FROM table_name;
Example:
SELECT SUM(Marks) FROM Student;
🔷
-- Returns the total marks obtained by all students
✅
Calculates the average (mean) of the values in a numeric column.
Syntax:
🧾
SELECT AVG(column_name) FROM table_name;
Example:
SELECT AVG(Marks) FROM Student;
🔷
-- Returns the average marks
✅
Returns the lowest (smallest) value in the specified column.
Syntax:
🧾
SELECT MIN(column_name) FROM table_name;
Example:
SELECT MIN(Marks) FROM Student;
🔷
-- Returns the lowest mark in the class
✅
Returns the highest (largest) value in the specified column.
Syntax:
🧾
SELECT MAX(column_name) FROM table_name;
Example:
SELECT MAX(Marks) FROM Student;
🧾
functions are applied to each group.
Example:
SELECT Department, AVG(Marks)
FROM Student
GROUP BY Department;
🔶
-- Returns average marks for each department
🧾
HAVING is used to apply conditions on groups (unlike WHERE, which is used for rows).
Example:
SELECT Department, COUNT(*) AS StudentCount
FROM Student
GROUP BY Department
📌
-- Shows departments with more than 10 students
🧾
• Multiple aggregate functions can be used in one query.
Example:
SELECT MIN(Salary), MAX(Salary), AVG(Salary)
🔷
FROM Employee;
🧾
• Use IS NULL and IS NOT NULL to filter such data.
Example:
SELECT * FROM Student WHERE Marks IS NULL;
Here is a very detailed note on Domain Constraints in SQL for your
📘
DBMS subject, written in simple and exam-ready format:
👉
values.
It is one of the integrity constraints used to enforce data accuracy and consistency in
relational databases.
❌
• It must be within a logical range, such as between 0 and 120.
If someone tries to insert a value like 'twenty' or 500, domain constraint will
reject it.
✅
This ensures only valid type of data can be inserted.
Example:
CREATE TABLE Student (
RollNo INT,
Name VARCHAR(50),
Age INT,
AdmissionDate DATE
);
✅
The CHECK constraint allows you to specify a condition that values must satisfy.
Example:
CREATE TABLE Employee (
EmpID INT,
Name VARCHAR(30),
);
Here:
• Age must be between 18 and 60
• Salary must be greater than 0
If a value violates the condition, SQL will throw an error and reject the insertion or
update.
✅
This is part of domain constraints because NULL might not be a valid value for certain fields.
Example:
CREATE TABLE Department (
);
🔷 4. ENUM and SET (MySQL Specific)
✅
In MySQL, you can define a column to accept only certain fixed values using ENUM or SET.
Example:
CREATE TABLE Product (
ProductID INT,
);
✅
Reason Explanation
✅
Data Integrity Prevents invalid or meaningless data from being stored
✅
Data Consistency Ensures values follow defined rules
✅
Reduces Errors Automatic rejection of wrong data
Enforces Business Ensures compliance with real-world constraints (e.g., age limits, salary
Rules limits, etc.)
🔷 Key Terms
Term Explanation
Primary Key A column (or set of columns) that uniquely identifies each row in a table
🔶
Foreign Key A column in one table that refers to the primary key of another table
✅
✅
Prevents orphaned records
Enforces valid data relationships
Supports data accuracy and reliability
📘 Assertions
CHECK (condition);
CHECK (
NOT EXISTS (
SELECT *
FROM Employee E
SELECT M.Salary
FROM Employee M
✅
);
This assertion ensures that all employees earn less than or equal to their managers.
CHECK (
);
This assertion automatically prevents insertion of employees once the count reaches 1000.
🔹
Reason Explanation
🔹
Data Accuracy Maintains correct data across multiple tables
🔹
Business Rules Enforces rules like "students must not enroll in more than 6 courses"
🔷
Advanced Checks Useful when simple CHECK or FOREIGN KEY is not enough
❌ ✅
Scope Row-level Table-level / Cross-table
Can use subquery? No Yes
SQL standard Part of standard SQL Less supported in practice
📌 Key Points for Exam
• Assertions help enforce complex integrity constraints.
• Defined using CREATE ASSERTION ... CHECK(...)
📘 Views
🔷 What is a View?
A View is a virtual table in SQL that is based on the result of a SELECT query.
✅
It does not store the data itself but displays data stored in other real (base) tables.
A view behaves like a table, and you can query it just like a regular table.
🔹
Purpose Explanation
🔹
Simplify complex queries Use a view instead of writing the same SQL repeatedly
Show limited data from a table (e.g., only name and salary, not
🔹
Data Security
entire employee info)
🔹
Logical data independence Hide the complexity of the database schema
Combine data from multiple
Create one logical view from multiple joins
🔷
tables
FROM table_name
WHERE condition;
🔷 Example 1: Create a Simple View
Suppose we have a table named Employee:
CREATE TABLE Employee (
EmpID INT,
EmpName VARCHAR(50),
Department VARCHAR(50),
Salary INT
✅
);
FROM Employee;
🔷
SELECT * FROM EmployeeSalary;
FROM Employee
🔷
WHERE Department = 'Sales';
✅
or JOINs, then INSERT, UPDATE, and DELETE operations are allowed.
Example:
UPDATE EmployeeSalary
🔷 Modifying a View
You can use the CREATE OR REPLACE clause:
CREATE OR REPLACE VIEW EmployeeSalary AS
🔷
FROM Employee;
Dropping a View
To remove a view from the database:
DROP VIEW view_name;
Example:
🔷
DROP VIEW SalesEmployees;
Types of Views
Type Description
Simple View Based on a single table, does not contain functions or groupings
📌
Complex View Based on multiple tables using joins, groupings, etc.
✅
Advantage Explanation
✅
Simplifies complex SQL queries Use views instead of writing long queries repeatedly
✅
Provides data security Hide sensitive columns from users
✅
Enhances performance Views can sometimes be materialized (cached in memory)
❗
Supports logical data independence Schema changes do not affect users using views
Limitations of Views
❌
Limitation Explanation
❌
Some views are not updatable Especially if they use JOINs or aggregate functions
❌
Performance issues Complex views can slow down query performance
Does not store data It only shows data, cannot hold data permanently
📘 Nested Subqueries
🔷 What is a Subquery?
A Subquery (also called an inner query or nested query) is a query that is written inside another
query (called the outer query).
The inner query executes first, and its result is used by the outer query.
FROM table1
WHERE column2 IN (
SELECT column2
FROM table2
WHERE condition
🔷
);
Types of Subqueries
Type Description
Single-row Subquery Returns only one row
Multiple-row Subquery Returns more than one row
Multiple-column Subquery Returns more than one column
Correlated Subquery References columns from the outer query
🧠
Nested Subquery A subquery inside another subquery
• ANY, ALL
• EXISTS, NOT EXISTS
FROM Employee
WHERE Department = (
SELECT Department
FROM Employee
WHERE Salary = (
SELECT MAX(Salary)
FROM Employee
);
Here:
• Inner-most query finds the maximum salary.
• Middle query finds the department of the employee with that salary.
• Outer query finds employees in that department.
FROM Students
SELECT Marks
FROM Students
🔷
);
✅
A Correlated Subquery is a subquery that uses a value from the outer query.
Find employees who earn more than the average salary of their department:
SELECT EmpName, Department, Salary
FROM Employee E
SELECT AVG(Salary)
FROM Employee
);
• The subquery uses E.Department, which comes from the outer query.
• For each employee, the average salary of their department is calculated and compared.
FROM Department D
WHERE EXISTS (
SELECT *
FROM Employee E
🔷
);
✅
Benefit Description
✅
Break complex logic Into simpler, readable pieces
✅
Reuse queries Use inner queries again in outer queries
✅
Advanced filtering Based on results of other queries
❗
Solve real-world problems Like ranking, top-N analysis, etc.
❌
Limitation Explanation
❌
Slower performance Especially with large datasets
❌
Hard to debug Complex nested levels may confuse
🔶
Not supported everywhere Some older databases don’t support deep nesting
❌ ✅
Feature Nested Subquery Correlated Subquery
Uses outer query values? No Yes
Executes how many times? Once Multiple times (per row)
Feature Nested Subquery Correlated Subquery
Performance Usually better Slower for large data
Example MAX(), IN, ANY EXISTS, comparisons
📘 Stored Procedures
🔷 Key Characteristics
• Stored in the database.
• Can accept input (IN parameters), return output (OUT parameters), or do both.
• Executed using a CALL or EXEC command.
• Can contain SQL statements, control-flow statements (like IF, WHILE), cursors, and
exception handling.
✅
Feature Benefit
✅
Reusability Write once, use many times
✅
Performance Executes faster due to pre-compilation
✅
Security Users can run procedures without direct access to tables
✅
Modularity Break code into logical blocks
🔷
Maintainability Easier to debug and manage
IN input_param DATATYPE,
BEGIN
-- SQL statements
END //
DELIMITER ;
BEGIN
END //
✅
DELIMITER ;
🔷
CALL ShowAllEmployees();
BEGIN
END //
✅
DELIMITER ;
BEGIN
END //
✅
DELIMITER ;
🔷
SELECT @total;
BEGIN
UPDATE Employee
END //
🔷
DELIMITER ;
🔶
DROP PROCEDURE IF EXISTS ShowAllEmployees;
✅
Advantage Explanation
Precompiled Faster execution
✅
Advantage Explanation
✅
Reduced network traffic Send procedure call instead of large SQL
✅
Enhanced security Hide logic from end-users
✅
Reusability Use in multiple programs or modules
🔶
Maintainability Central location to update logic
Disadvantages
❌
Disadvantage Explanation
❌
Complex debugging Hard to debug stored procedures compared to application code
Syntax may differ between DBMS (e.g., MySQL, Oracle, SQL
❌
Portability issues
Server)
Increased load on DB
Logic shifts to the database engine
server
🔷 1. Cursors in SQL
✅ What is a Cursor?
A Cursor is a database object used to retrieve one row at a time from the result set of a query.
Normally, SQL operates on a set of rows, but sometimes you need to process each row
individually — in such cases, cursors are used.
✅ Types of Cursors
Cursor Type Description
Implicit Cursor Automatically created by SQL for single-row queries
Explicit Cursor Defined by the programmer for multi-row result sets
✅ Full Example
DELIMITER //
BEGIN
-- Declare cursor
-- Open cursor
OPEN emp_cursor;
read_loop: LOOP
IF done THEN
LEAVE read_loop;
END IF;
SELECT emp_name;
END LOOP;
-- Close cursor
CLOSE emp_cursor;
END //
DELIMITER ;
✅ Advantages of Cursors
• Helps with row-by-row processing
• Useful when logic cannot be written in a single SQL query
• Easy to control and manage result sets
❌ Disadvantages
• Slower than set-based operations
• Increases server load
• Not scalable for large data
🔷 2. Triggers in SQL
✅ What is a Trigger?
A Trigger is a predefined action that automatically executes (fires) in response to certain events
on a table.
✅ Types of Triggers
Type Fires When
BEFORE INSERT Before inserting a new row
AFTER INSERT After inserting a new row
BEFORE UPDATE Before updating an existing row
AFTER UPDATE After updating an existing row
BEFORE DELETE Before deleting a row
AFTER DELETE After deleting a row
✅ Trigger Syntax (MySQL-style)
CREATE TRIGGER trigger_name
ON table_name
BEGIN
-- SQL statements
END;
BEGIN
END;
BEGIN
END IF;
END;
✅ Advantages of Triggers
• Automatic and consistent enforcement of rules
• Useful for logging and validation
• No need to modify application code
❌ Disadvantages
• Can be difficult to debug
• May affect performance if too many triggers are fired
• Hidden logic (not always visible to developers)