SlideShare a Scribd company logo
Complex Queries
(Aggregate Function,
Nested Queries,
Triggers)
AGGREGATES FUNCTION IN SQL
• An aggregate function in SQL performs a calculation on
multiple values and returns a single value.
• Aggregate functions often use with the GROUP BY and
HAVING clauses of the SELECT statement.
• Various types of SQL aggregate functions are: Count, Sum,
Avg, Min, Max
• NULL values discarded when aggregate functions are applied
to a particular column.
This function returns the number of rows in a database table.
Syntax: COUNT(columnname)
Examples:
SELECT COUNT(product_id)
FROM Products;
SELECT COUNT(product_id)
FROM Products
WHERE unit_price > 4;
COUNT() FUNCTION
This function returns the total sum of a numeric column.
Syntax: SUM(columnname)
Examples:
SELECT SUM(unit_price)
FROM Products;
SELECT COUNT(customer_id), city
FROM Customers
GROUP BY city
HAVING SUM(points) > 3000;
SUM() FUNCTION
This function calculates the average of a set of values.
Syntax: AVG(columnname)
Examples:
SELECT AVG(quantity_in_stock)
FROM Products;
SELECT department_id, AVG(salary)
FROM Employees
GROUP BY department_id;
AVG() FUNCTION
This function returns the lowest value (minimum) in a set of non-NULL
values.
Syntax: MIN(columnname)
Example:
SELECT MIN(quantity_in_stock)
FROM Products;
MIN() FUNCTION
This function returns the highest value (maximum) in a set of non-NULL
values.
Syntax: MAX(columnname)
Example:
SELECT MAX(quantity_in_stock)
FROM Products;
MAX() FUNCTION
CORRELATED NESTED QUERIES
• Evaluated once for each row in the outer query.
• Correlated nested queries are used for row-by-row
processing.
• Each nested sub-query is executed once for every row of
the outer query.
• A correlated nested query is one way of reading every row
in a table and comparing values in each row against related
data.
Example:
SELECT first_name, last_name
FROM employee a
WHERE TargetSale >
(SELECT Sales
FROM sale
WHERE emp_id = a.emp_id);
Correlated Nested Queries
TRIGGERS IN SQL
Triggers in SQL serve as a mechanism for automatically
executing a set of SQL statements in response to certain
events occurring in the database. These events can include
data manipulation operations (e.g., INSERT, UPDATE,
DELETE) on specific tables.
TRIGGERS IN SQL
Scenario: In a university database, there's a table named
Grades that stores students' grades for various courses. We
want to implement a trigger that automatically updates a
student's overall GPA (Grade Point Average) whenever a new
grade is inserted or updated in the Grades table.
Objective: We'll create a trigger that calculates the overall
GPA of a student whenever a new grade is inserted or
updated in the Grades table.
TRIGGERS IN SQL
Tables:
Grades: Contains student grades for different courses.
Students: Contains student information including their overall GPA.
Steps:
Create a Trigger: We'll create a trigger that fires after each insert or
update operation on the Grades table.
Calculate GPA: Inside the trigger, we'll calculate the overall GPA of the
student based on their grades in different courses.
Update Student's GPA: Finally, we'll update the student's overall GPA in
the Students table.
CREATE TRIGGER UpdateGPA
AFTER INSERT ON Grades
FOR EACH ROW
BEGIN
DECLARE total_credits INT;
DECLARE total_grade_points DECIMAL(5, 2);
DECLARE new_gpa DECIMAL(5, 2);
-- Calculate total credits and grade points for the student
SELECT SUM(course_credits), SUM(grade * course_credits)
INTO total_credits, total_grade_points
FROM Grades
WHERE student_id = NEW.student_id;
-- Calculate GPA
IF total_credits > 0 THEN
SET new_gpa = total_grade_points / total_credits;
ELSE
SET new_gpa = 0; -- To handle the case when there are no grades yet
END IF;
-- Update student's GPA
UPDATE Students
SET gpa = new_gpa
WHERE student_id = NEW.student_id;
END;
CREATE A TRIGGER
CALCULATE GPA
UPDATE GPA



Alubijid | Balubal | Cagayan de Oro | Claveria | Jasaan | Oroquieta | Panaon | Villanueva
Home of the Trailblazers
Ad

More Related Content

Similar to Lesson-5-Complex-Queries-Aggregate-Function-Nested-Queries-Triggers.pptx (20)

unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_
unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_
unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_
townhallforme1
 
unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_
unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_
unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_
townhallforme1
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
Function
FunctionFunction
Function
Durgaprasad Yadav
 
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrjPLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
KathanPatel49
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Julian Hyde
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
Vikash Sharma
 
Les17
Les17Les17
Les17
Vijay Kumar
 
Les04
Les04Les04
Les04
Sudharsan S
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
Dhananjay Goel
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
mukesh24pandey
 
ADVANCED MODELLING.pptx
ADVANCED MODELLING.pptxADVANCED MODELLING.pptx
ADVANCED MODELLING.pptx
RUPAK BHATTACHARJEE
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence Portfolio
Chris Seebacher
 
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasdasdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
MuhamedAhmed35
 
Sql FUNCTIONS
Sql FUNCTIONSSql FUNCTIONS
Sql FUNCTIONS
Abrar ali
 
Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17
Thuan Nguyen
 
Oracle SQL Advanced
Oracle SQL AdvancedOracle SQL Advanced
Oracle SQL Advanced
Dhananjay Goel
 
Stored procedure Notes By Durgesh Singh
Stored procedure Notes By Durgesh SinghStored procedure Notes By Durgesh Singh
Stored procedure Notes By Durgesh Singh
imdurgesh
 
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docxMSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
gilpinleeanna
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
WO Community
 
unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_
unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_
unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_
townhallforme1
 
unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_
unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_
unit 3nit unit 1_unit1_unit1_.unit 1_unit1_unit1_
townhallforme1
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrjPLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
KathanPatel49
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Julian Hyde
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
Vikash Sharma
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
mukesh24pandey
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence Portfolio
Chris Seebacher
 
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasdasdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
MuhamedAhmed35
 
Sql FUNCTIONS
Sql FUNCTIONSSql FUNCTIONS
Sql FUNCTIONS
Abrar ali
 
Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17
Thuan Nguyen
 
Stored procedure Notes By Durgesh Singh
Stored procedure Notes By Durgesh SinghStored procedure Notes By Durgesh Singh
Stored procedure Notes By Durgesh Singh
imdurgesh
 
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docxMSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
gilpinleeanna
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
WO Community
 

Recently uploaded (20)

YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Ad

Lesson-5-Complex-Queries-Aggregate-Function-Nested-Queries-Triggers.pptx

  • 2. AGGREGATES FUNCTION IN SQL • An aggregate function in SQL performs a calculation on multiple values and returns a single value. • Aggregate functions often use with the GROUP BY and HAVING clauses of the SELECT statement. • Various types of SQL aggregate functions are: Count, Sum, Avg, Min, Max • NULL values discarded when aggregate functions are applied to a particular column.
  • 3. This function returns the number of rows in a database table. Syntax: COUNT(columnname) Examples: SELECT COUNT(product_id) FROM Products; SELECT COUNT(product_id) FROM Products WHERE unit_price > 4; COUNT() FUNCTION
  • 4. This function returns the total sum of a numeric column. Syntax: SUM(columnname) Examples: SELECT SUM(unit_price) FROM Products; SELECT COUNT(customer_id), city FROM Customers GROUP BY city HAVING SUM(points) > 3000; SUM() FUNCTION
  • 5. This function calculates the average of a set of values. Syntax: AVG(columnname) Examples: SELECT AVG(quantity_in_stock) FROM Products; SELECT department_id, AVG(salary) FROM Employees GROUP BY department_id; AVG() FUNCTION
  • 6. This function returns the lowest value (minimum) in a set of non-NULL values. Syntax: MIN(columnname) Example: SELECT MIN(quantity_in_stock) FROM Products; MIN() FUNCTION
  • 7. This function returns the highest value (maximum) in a set of non-NULL values. Syntax: MAX(columnname) Example: SELECT MAX(quantity_in_stock) FROM Products; MAX() FUNCTION
  • 8. CORRELATED NESTED QUERIES • Evaluated once for each row in the outer query. • Correlated nested queries are used for row-by-row processing. • Each nested sub-query is executed once for every row of the outer query. • A correlated nested query is one way of reading every row in a table and comparing values in each row against related data.
  • 9. Example: SELECT first_name, last_name FROM employee a WHERE TargetSale > (SELECT Sales FROM sale WHERE emp_id = a.emp_id); Correlated Nested Queries
  • 10. TRIGGERS IN SQL Triggers in SQL serve as a mechanism for automatically executing a set of SQL statements in response to certain events occurring in the database. These events can include data manipulation operations (e.g., INSERT, UPDATE, DELETE) on specific tables.
  • 11. TRIGGERS IN SQL Scenario: In a university database, there's a table named Grades that stores students' grades for various courses. We want to implement a trigger that automatically updates a student's overall GPA (Grade Point Average) whenever a new grade is inserted or updated in the Grades table. Objective: We'll create a trigger that calculates the overall GPA of a student whenever a new grade is inserted or updated in the Grades table.
  • 12. TRIGGERS IN SQL Tables: Grades: Contains student grades for different courses. Students: Contains student information including their overall GPA. Steps: Create a Trigger: We'll create a trigger that fires after each insert or update operation on the Grades table. Calculate GPA: Inside the trigger, we'll calculate the overall GPA of the student based on their grades in different courses. Update Student's GPA: Finally, we'll update the student's overall GPA in the Students table.
  • 13. CREATE TRIGGER UpdateGPA AFTER INSERT ON Grades FOR EACH ROW BEGIN DECLARE total_credits INT; DECLARE total_grade_points DECIMAL(5, 2); DECLARE new_gpa DECIMAL(5, 2); -- Calculate total credits and grade points for the student SELECT SUM(course_credits), SUM(grade * course_credits) INTO total_credits, total_grade_points FROM Grades WHERE student_id = NEW.student_id; -- Calculate GPA IF total_credits > 0 THEN SET new_gpa = total_grade_points / total_credits; ELSE SET new_gpa = 0; -- To handle the case when there are no grades yet END IF; -- Update student's GPA UPDATE Students SET gpa = new_gpa WHERE student_id = NEW.student_id; END; CREATE A TRIGGER CALCULATE GPA UPDATE GPA   
  • 14. Alubijid | Balubal | Cagayan de Oro | Claveria | Jasaan | Oroquieta | Panaon | Villanueva Home of the Trailblazers