0% found this document useful (0 votes)
4 views24 pages

M4_SQL

This document provides comprehensive notes on SQL, covering key concepts such as Data Definition Language (DDL) and Data Manipulation Language (DML), relational databases, set operations, aggregate functions, domain constraints, referential integrity, assertions, views, and nested subqueries. It explains the purpose and usage of various SQL commands and constraints, along with examples to illustrate their application. The notes are designed to aid in understanding SQL for university exams and practical database management.

Uploaded by

arunabhagain07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views24 pages

M4_SQL

This document provides comprehensive notes on SQL, covering key concepts such as Data Definition Language (DDL) and Data Manipulation Language (DML), relational databases, set operations, aggregate functions, domain constraints, referential integrity, assertions, views, and nested subqueries. It explains the purpose and usage of various SQL commands and constraints, along with examples to illustrate their application. The notes are designed to aid in understanding SQL for university exams and practical database management.

Uploaded by

arunabhagain07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Here is a very detailed and long-type note on the topic SQL from the Database Management

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 (Structured Query Language) – Full


Detailed Notes
SQL is a standard language used to store, retrieve, manipulate, and manage data in relational
databases. It was developed by IBM in the early 1970s and later became a standard by ANSI and
ISO.

🔷 1. Concept of DDL and DML

🔹
SQL is categorized into several types of statements. The two main categories are:

1.1 DDL – Data Definition Language


• DDL commands are used to define or change the structure of database schema objects like
tables, indexes, and constraints.

💡
• 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 (

EmpID INT PRIMARY KEY,

Name VARCHAR(100),

Salary DECIMAL(10,2)

);

ALTER TABLE Employee ADD Department VARCHAR(50);

DROP TABLE Employee;

🔹 1.2 DML – Data Manipulation Language


• DML commands are used to modify or retrieve data in existing tables.
💡
• DML commands do not alter the structure.
Common DML Commands:

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);

UPDATE Employee SET Salary = 60000 WHERE EmpID = 1;

🔷
DELETE FROM Employee WHERE EmpID = 1;

2. Relational Databases and Tables


• A relational database consists of one or more tables, where each table represents an entity.
• Each table has rows (tuples) and columns (attributes).

🧾
• Each column has a specific data type.

Example Table: Student


RollNo Name Dept Marks
101 Amit CSE 88

🔷
102 Sneha IT 92

3. Set Operations in SQL

🔹
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;

3.2 UNION ALL


Combines results and includes duplicates.
SELECT Name FROM CSE_Students

UNION ALL

SELECT Name FROM IT_Students;


🔹 3.3 INTERSECT
Shows only common rows.
SELECT Name FROM CSE_Students

INTERSECT

🔹
SELECT Name FROM IT_Students;

3.4 EXCEPT or MINUS


Returns rows from the first query that are not in the second.
SELECT Name FROM CSE_Students

EXCEPT

SELECT Name FROM IT_Students;

🔶 What Are Aggregate Functions?


Aggregate functions in SQL are special functions that perform a calculation on a set of values and
return a single value as the result.
They are commonly used with the SELECT statement and often combined with GROUP BY and
HAVING clauses.

🔶 List of Common Aggregate Functions


Function Description
COUNT() Counts the number of rows
SUM() Calculates the total sum of values
AVG() Calculates the average (mean) value
MIN() Finds the smallest (minimum) value

🔷
MAX() Finds the largest (maximum) value

1. COUNT() – Count Rows


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 total number of students

SELECT COUNT(DISTINCT Department) FROM Student;

-- Counts how many different departments exist


🔷 2. SUM() – Total of Values


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

3. AVG() – Average Value


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

4. MIN() – Minimum Value


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

5. MAX() – Maximum Value


Returns the highest (largest) value in the specified column.

Syntax:

🧾
SELECT MAX(column_name) FROM table_name;

Example:
SELECT MAX(Marks) FROM Student;

-- Returns the highest mark in the class


🔶 Use of Aggregate Functions with GROUP BY
The GROUP BY clause is used to group the results by one or more columns, and then aggregate

🧾
functions are applied to each group.

Example:
SELECT Department, AVG(Marks)

FROM Student

GROUP BY Department;

🔶
-- Returns average marks for each department

Use of Aggregate Functions with HAVING

🧾
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

HAVING COUNT(*) > 10;

📌
-- Shows departments with more than 10 students

Important Points to Remember


• Aggregate functions ignore NULL values (except COUNT(*) which counts all).
• Can’t use aggregate functions in WHERE; use them in HAVING.

🧾
• Multiple aggregate functions can be used in one query.

Example:
SELECT MIN(Salary), MAX(Salary), AVG(Salary)

🔷
FROM Employee;

5. Null Values in SQL


• A NULL value represents unknown or missing data.

🧾
• 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:

Domain Constraints in SQL (DBMS


Subject)

🔶 What Are Domain Constraints?


In SQL and DBMS, a domain constraint defines the permissible values that an attribute (column)
can hold.
It ensures that each value in a column belongs to a particular data type and valid range or set of

👉
values.
It is one of the integrity constraints used to enforce data accuracy and consistency in
relational databases.

🔷 Example of Domain Constraint (Real-Life Analogy)


If we have a column named Age, domain constraint ensures:

• The value must be an integer.


• 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.

🔶 How Domain Constraints Are Applied in SQL


Domain constraints are enforced using:
1. Data Types
2. CHECK constraints
3. NOT NULL constraint
4. ENUM / Set of allowed values (in some DBMS)

🔷 1. Data Types (Basic Domain Constraint)


Each column must have a data type such as INT, VARCHAR, DATE, etc.


This ensures only valid type of data can be inserted.

Example:
CREATE TABLE Student (
RollNo INT,

Name VARCHAR(50),

Age INT,

AdmissionDate DATE

);

• RollNo can only contain integers

• Name must be a string (up to 50 characters)

• AdmissionDate must be a valid date

🔷 2. CHECK Constraint (Custom Domain Rule)


The CHECK constraint allows you to specify a condition that values must satisfy.

Example:
CREATE TABLE Employee (

EmpID INT,

Name VARCHAR(30),

Age INT CHECK (Age >= 18 AND Age <= 60),

Salary DECIMAL(10, 2) CHECK (Salary > 0)

);

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.

🔷 3. NOT NULL Constraint


It ensures that a column cannot have NULL values.


This is part of domain constraints because NULL might not be a valid value for certain fields.

Example:
CREATE TABLE Department (

DeptID INT NOT NULL,

DeptName VARCHAR(50) NOT NULL

);
🔷 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,

Category ENUM('Electronics', 'Clothing', 'Grocery')

);

• Only values from the list can be inserted into Category

📌 Importance of Domain Constraints


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.)

🔷 What is Referential Integrity?


Referential Integrity is a rule in a relational database that ensures the validity and consistency of
relationships between tables.
It ensures that a foreign key value in one table must either:
• Match a primary key value in another table, or
• Be NULL (if allowed).

🔷 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

Example Scenario (Real-Life Analogy)


Suppose we have two tables:
• Department Table → Holds department details
• Employee Table → Holds employee details and includes the department they belong to
We must ensure that:
• Every employee's department ID exists in the Department Table

🔶 Importance of Referential Integrity



✅ Ensures logical consistency between tables



Prevents orphaned records
Enforces valid data relationships
Supports data accuracy and reliability

📘 Assertions

🔷 What is an Assertion in SQL?


An Assertion is a condition or rule defined in SQL that must always be true for the database to
remain valid.
It is used to enforce complex integrity constraints that cannot be enforced using:
• CHECK constraints,
• NOT NULL, or
• FOREIGN KEY alone.

✅ Definition (Simple Words):


An assertion in SQL is a named constraint that applies to entire database tables or
across multiple tables to maintain data accuracy and consistency.

🔷 Syntax of Assertion in SQL


CREATE ASSERTION assertion_name

CHECK (condition);

• assertion_name → Name of the assertion

• CHECK (condition) → Condition that must always be true

🔷 Example 1: Salary Must Not Exceed Manager's Salary


Let’s say we have a Department and Employee table, and we want to make sure that:
“No employee’s salary should exceed the salary of their manager”
CREATE ASSERTION salary_check

CHECK (

NOT EXISTS (

SELECT *

FROM Employee E

WHERE E.Salary > (

SELECT M.Salary

FROM Employee M

WHERE M.EmpID = E.ManagerID


);

This assertion ensures that all employees earn less than or equal to their managers.

🔷 Example 2: Total Employees Must Not Exceed 1000


Suppose the total number of employees in the company must not exceed 1000:
CREATE ASSERTION max_employee_limit

CHECK (

(SELECT COUNT(*) FROM Employee) <= 1000

);

This assertion automatically prevents insertion of employees once the count reaches 1000.

🔷 Why Use Assertions?

🔹
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

Difference Between CHECK and ASSERTION


Feature CHECK Constraint ASSERTION
Applies to Single table/column Whole database

❌ ✅
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(...)

• Work across multiple tables or entire database


• Can contain subqueries inside the CHECK condition
• Not widely supported in commercial RDBMS; use triggers as an alternative.

📘 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.

🔷 Why Use Views?

🔹
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

Syntax to Create a View


CREATE VIEW view_name AS

SELECT column1, column2, ...

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


);

View to Show Only Employee Names and Salaries:


CREATE VIEW EmployeeSalary AS

SELECT EmpName, Salary

FROM Employee;

Now you can use the view as:

🔷
SELECT * FROM EmployeeSalary;

Example 2: View with WHERE Clause


✅ View to Show Employees from "Sales" Department:
CREATE VIEW SalesEmployees AS

SELECT EmpName, Salary

FROM Employee

🔷
WHERE Department = 'Sales';

Updating Data Using a View


If the view is based on one table and does not use GROUP BY, aggregate functions, DISTINCT,


or JOINs, then INSERT, UPDATE, and DELETE operations are allowed.

Example:
UPDATE EmployeeSalary

SET Salary = Salary + 500

WHERE EmpName = 'Ravi';

This will update the original Employee table.

❌ Views That Cannot Be Updated


You cannot modify data using a view if:
• The view has GROUP BY, DISTINCT, JOIN, AGGREGATE FUNCTIONS (like SUM, AVG)

• The view uses a subquery or UNION

• The view has columns derived from expressions

🔷 Modifying a View
You can use the CREATE OR REPLACE clause:
CREATE OR REPLACE VIEW EmployeeSalary AS

SELECT EmpName, Salary, Department

🔷
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.

Advantages of Using Views


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.

🔷 What is a Nested Subquery?


A Nested Subquery means placing a subquery inside another subquery, possibly multiple levels
deep.
• Used when the output of one query depends on the result of another.
• Helps solve complex problems involving comparisons, filters, or data dependencies.

🔷 Syntax of Nested Subquery


SELECT column1

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

Important Operators Used with Subqueries


• IN, NOT IN

• =, !=, >, <, >=, <=

• ANY, ALL
• EXISTS, NOT EXISTS

🔷 Example 1: Simple Nested Subquery


✅ Find names of employees who work in the department where salary is
maximum:
SELECT EmpName

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.

🔷 Example 2: Multiple-Row Nested Subquery


✅ Find students who scored more than ALL students in section 'B':
SELECT StudentName

FROM Students

WHERE Marks > ALL (

SELECT Marks

FROM Students

WHERE Section = 'B'

🔷
);

Example 3: Correlated Nested Subquery


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

WHERE Salary > (

SELECT AVG(Salary)

FROM Employee

WHERE Department = E.Department

);

• The subquery uses E.Department, which comes from the outer query.

• For each employee, the average salary of their department is calculated and compared.

🔷 Example 4: Nested Subquery with EXISTS


✅ Find departments that have at least one employee:
SELECT DeptName

FROM Department D

WHERE EXISTS (

SELECT *

FROM Employee E

WHERE D.DeptID = E.DeptID

🔷
);

Benefits of Using Nested Subqueries


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.

Limitations of Nested Subqueries


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

Nested vs. Correlated Subquery (Difference)

❌ ✅
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

🔷 What is a Stored Procedure?


A Stored Procedure is a precompiled collection of one or more SQL statements that are stored
in the database and can be executed as a program or routine.
It is used to encapsulate logic, improve performance, and promote code reuse.

🔷 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.

🔷 Why Use Stored Procedures?


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

Syntax (MySQL-style Example)


DELIMITER //

CREATE PROCEDURE ProcedureName (

IN input_param DATATYPE,

OUT output_param DATATYPE

BEGIN
-- SQL statements

END //

DELIMITER ;

• IN: Input parameter

• OUT: Output parameter

• INOUT: Both input and output

🔷 Example 1: Simple Stored Procedure (No Parameters)


✅ Create a procedure to display all employees:
DELIMITER //

CREATE PROCEDURE ShowAllEmployees()

BEGIN

SELECT * FROM Employee;

END //


DELIMITER ;

Call the procedure:

🔷
CALL ShowAllEmployees();

Example 2: Stored Procedure with Input Parameter


✅ Create a procedure to get employee details by ID:
DELIMITER //

CREATE PROCEDURE GetEmployeeByID(IN emp_id INT)

BEGIN

SELECT * FROM Employee WHERE ID = emp_id;

END //


DELIMITER ;

Call the procedure:


CALL GetEmployeeByID(101);
🔷 Example 3: Stored Procedure with Output Parameter
DELIMITER //

CREATE PROCEDURE GetTotalEmployees(OUT total INT)

BEGIN

SELECT COUNT(*) INTO total FROM Employee;

END //


DELIMITER ;

Call the procedure and get result:


CALL GetTotalEmployees(@total);

🔷
SELECT @total;

Example 4: Procedure with Control Statements


✅ Give a bonus to employees with salary < 30000:
DELIMITER //

CREATE PROCEDURE GiveBonus()

BEGIN

UPDATE Employee

SET Salary = Salary + 2000

WHERE Salary < 30000;

END //

🔷
DELIMITER ;

Modifying & Dropping a Procedure


• Alter a procedure (not all databases support this directly).
• Drop a procedure:

🔶
DROP PROCEDURE IF EXISTS ShowAllEmployees;

Advantages of Stored Procedures


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

📘 Cursors and Triggers

🔷 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.

✅ When to Use Cursors?


• When you want to loop through rows one-by-one.
• When row-by-row processing is needed (not possible with standard SQL operations).
• When procedural operations (like complex logic or calculations) are needed on each row.

✅ 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

✅ Syntax of Cursor in MySQL


DECLARE cursor_name CURSOR FOR SELECT_statement;
✅ Steps in Using a Cursor
1. Declare the cursor
2. Open the cursor
3. Fetch each row from the cursor
4. Close the cursor

✅ Full Example
DELIMITER //

CREATE PROCEDURE DisplayAllEmployees()

BEGIN

DECLARE emp_name VARCHAR(100);

DECLARE done INT DEFAULT 0;

-- Declare cursor

DECLARE emp_cursor CURSOR FOR SELECT name FROM Employee;

-- Declare continue handler

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

-- Open cursor

OPEN emp_cursor;

-- Loop through rows

read_loop: LOOP

FETCH emp_cursor INTO emp_name;

IF done THEN

LEAVE read_loop;

END IF;

-- Print employee name

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.

✅ When Triggers are Used?


• Automatically validate data
• Automatically log changes (audit trail)
• Enforce business rules
• Maintain integrity between tables

✅ 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

{BEFORE | AFTER} {INSERT | UPDATE | DELETE}

ON table_name

FOR EACH ROW

BEGIN

-- SQL statements

END;

✅ Example 1: Log insertion into Employee_Audit Table


CREATE TRIGGER log_insert

AFTER INSERT ON Employee

FOR EACH ROW

BEGIN

INSERT INTO Employee_Audit(EmpID, Action)

VALUES (NEW.ID, 'INSERTED');

END;

✅ Example 2: Prevent negative salary


CREATE TRIGGER prevent_negative_salary

BEFORE UPDATE ON Employee

FOR EACH ROW

BEGIN

IF NEW.Salary < 0 THEN

SIGNAL SQLSTATE '45000'

SET MESSAGE_TEXT = 'Salary cannot be negative';

END IF;

END;

✅ OLD and NEW Keywords


• OLD.column_name: Refers to the value before the change (used in DELETE and
UPDATE)
• NEW.column_name: Refers to the value after the change (used in INSERT and UPDATE)

✅ 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)

🔶 Differences Between Cursor and Trigger


Feature Cursor Trigger
Purpose Row-by-row processing Automatic action on table event
Execution Manually executed inside a procedure Automatically fired
Usage Procedural data operations Enforce rules, log events
Performance Slower, more control Faster but hidden

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy