Skip to content

[SQL-519] What is a trigger in SQL #354

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions data-manipulation/triggers/triggers-mysql.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
CREATE TABLE IF NOT EXISTS Student_audit_log (
id INT AUTO_INCREMENT PRIMARY KEY,
student_id INT,
action VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

DROP TRIGGER IF EXISTS after_student_insert;
DROP TRIGGER IF EXISTS after_student_update;
DROP TRIGGER IF EXISTS after_student_delete;

DELIMITER //
CREATE TRIGGER after_student_insert
AFTER INSERT ON Student
FOR EACH ROW
BEGIN
INSERT INTO student_audit_log(student_id, action)
VALUES (NEW.id, 'INSERT');
END//

CREATE TRIGGER after_student_update
AFTER UPDATE ON Student
FOR EACH ROW
BEGIN
INSERT INTO student_audit_log(student_id, action)
VALUES (NEW.id, 'UPDATE');
END//

CREATE TRIGGER after_student_delete
AFTER DELETE ON Student
FOR EACH ROW
BEGIN
INSERT INTO student_audit_log(student_id, action)
VALUES (OLD.id, 'DELETE');
END//
DELIMITER ;
58 changes: 58 additions & 0 deletions data-manipulation/triggers/triggers-pg.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
CREATE TABLE IF NOT EXISTS Student_audit_log (
id SERIAL PRIMARY KEY,
student_id INT,
action VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE OR REPLACE FUNCTION log_student_changes()
RETURNS TRIGGER AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
INSERT INTO Student_audit_log(student_id, action)
VALUES (NEW.id, 'INSERT');
RETURN NEW;
ELSIF TG_OP = 'UPDATE' THEN
INSERT INTO Student_audit_log(student_id, action)
VALUES (NEW.id, 'UPDATE');
RETURN NEW;
ELSIF TG_OP = 'DELETE' THEN
INSERT INTO Student_audit_log(student_id, action)
VALUES (OLD.id, 'DELETE');
RETURN OLD;
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER student_audit_trigger
AFTER INSERT OR UPDATE OR DELETE ON Student
FOR EACH ROW EXECUTE FUNCTION log_student_changes();

CREATE OR REPLACE FUNCTION log_bulk_deletion_student()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO Student_audit_log (action)
VALUES ('BULK_DELETION');
RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER log_bulk_deletion_student_trigger
AFTER DELETE ON Student
FOR EACH STATEMENT EXECUTE FUNCTION log_bulk_deletion_student();

CREATE OR REPLACE VIEW Department_view AS
SELECT * FROM Department;

CREATE OR REPLACE FUNCTION prevent_department_delete()
RETURNS TRIGGER AS $$
BEGIN
RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER prevent_department_deletion_trigger
INSTEAD OF DELETE ON Department_view
FOR EACH ROW
EXECUTE FUNCTION prevent_department_delete();
53 changes: 53 additions & 0 deletions data-manipulation/triggers/triggers-sqlserver.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Student_audit_log]') AND type in (N'U'))
BEGIN
CREATE TABLE Student_audit_log (
id INT IDENTITY(1,1) PRIMARY KEY,
student_id INT,
action VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT GETDATE()
);
END

-- Drop existing triggers if they exist
IF EXISTS (SELECT * FROM sys.triggers WHERE name = 'trg_student_audit')
DROP TRIGGER trg_student_audit;
GO

CREATE TRIGGER trg_student_audit
ON Student
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON;


IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
BEGIN
INSERT INTO student_audit_log (student_id, action)
SELECT id, 'INSERT'
FROM inserted;
END

IF EXISTS (SELECT * FROM inserted) AND EXISTS (SELECT * FROM deleted)
BEGIN
INSERT INTO student_audit_log (student_id, action)
SELECT id, 'UPDATE'
FROM inserted;
END

IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
BEGIN
INSERT INTO student_audit_log (student_id, action)
SELECT id, 'DELETE'
FROM deleted;
END
END
GO;

CREATE TRIGGER prevent_department_deletion_trigger
ON Department
INSTEAD OF DELETE
AS
BEGIN
RETURN;
END;
5 changes: 5 additions & 0 deletions mysql-queries/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### Relevant Articles:
- [How to Find the Engine for a Specific Table in MySQL?](https://www.baeldung.com/sql/mysql-find-table-storage-engine)
- [Changing a Table’s Storage Engine in MySQL](https://www.baeldung.com/sql/mysql-change-table-storage-engine)
- [Pattern Matching in MySQL](https://www.baeldung.com/sql/mysql-pattern-matching)
- [Comments in MySQL](https://www.baeldung.com/sql/mysql-comments-single-line-multiline-hint)
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
ALTER TABLE Student ENGINE=MyISAM;

SELECT
engine
FROM
information_schema.tables
WHERE
table_schema = 'University'
AND table_name = 'Student';

ALTER TABLE Student ENGINE=InnoDB;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
SELECT
engine
FROM
information_schema.tables
WHERE
table_schema = 'University'
AND table_name = 'Student';

SHOW TABLE STATUS LIKE 'Student';
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SHOW ENGINES;
13 changes: 13 additions & 0 deletions mysql-queries/comments-mysql/comments.mysql
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-- This query returns all Students in the University
SELECT * FROM Student;
SELECT * FROM Student -- WHERE NAME = 'John';

SELECT * FROM Student WHERE NAME /* wild card matching for name */ LIKE '%John%';

SELECT * FROM Student WHERE NAME
/* wild card matching for name.
Change it based on the requirement
*/
LIKE '%John%';

SELECT /*! STRAIGHT_JOIN */ * FROM Student /*+ USE INDEX (PRIMARY) */ WHERE id = 1001;
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
SELECT * FROM performance_schema.metadata_locks
WHERE OBJECT_TYPE = 'USER LEVEL LOCK';
2 changes: 2 additions & 0 deletions mysql-queries/detect-locked-table-mysql/locking-table.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
LOCK TABLES Student WRITE;

3 changes: 3 additions & 0 deletions mysql-queries/detect-locked-table-mysql/unlock-table.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
UNLOCK TABLES;

SELECT RELEASE_LOCK('Student');
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
SHOW OPEN TABLES WHERE `Table` LIKE 'Student' AND `Database` LIKE 'University' AND In_use > 0;

SHOW OPEN TABLES WHERE In_use > 0;
23 changes: 23 additions & 0 deletions mysql-queries/find-storage-engine/script.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
-- specify the database
USE University;

-- find the engine of University.Student
-- using the information_schema.tables
SELECT engine
FROM information_schema.tables
WHERE table_schema = 'University'
AND table_name = 'Student';

-- find the engine of all the tables in University
-- using the information_schema.tables
SELECT table_name, engine
FROM information_schema.tables
WHERE table_schema = 'University'
AND table_type = 'BASE TABLE'
AND table_name = 'Student';

-- find the engine of University.Student
-- using the information_schema.tables
SHOW TABLE STATUS
FROM University
WHERE name = 'Student';
90 changes: 90 additions & 0 deletions mysql-queries/mysql-images/images.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
-- SQL Script for the article Images in MySQL

-- Change schema to University
USE University;

-- Check max image size you can upload
SHOW VARIABLES LIKE 'max_allowed_packet';
SHOW VARIABLES LIKE 'secure_file_priv';

-- Grant access
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;

-- DIRECT STORAGE

-- Create Tables
CREATE TABLE DepartmentComplete
(
id INT PRIMARY KEY NOT Null,
name VARCHAR (50),
code VARCHAR (4),
logo BLOB,
UNIQUE (id)
);

CREATE TABLE StudentComplete
(
id INT PRIMARY KEY NOT null,
name VARCHAR (60),
national_id BIGINT NOT Null,
birth_date DATE,
enrollment_date DATE,
graduation_date DATE,
gpa FLOAT,
profile_pic BLOB,
UNIQUE (id)
);

-- Adding data for DepartmentComplete
INSERT INTO DepartmentComplete (id, name, code, logo) VALUES
(1, 'Computer Science', 'CS', LOAD_FILE('/usr/local/mysql/data/cs_logo.png')),
(2, 'Electronics and Communications', 'EC', LOAD_FILE('/usr/local/mysql/data/ece_logo.png')),
(3, 'Social Sciences', 'SS', LOAD_FILE('/usr/local/mysql/data/ss_logo.png')),
(4, 'Computational Biology', 'CB', LOAD_FILE('/usr/local/mysql/data/cb_logo.png')),
(5, 'Mathematics', 'MA', LOAD_FILE('/usr/local/mysql/data/ma_logo.png'));

-- Adding data for StudentComplete
INSERT INTO StudentComplete (id, name, national_id, birth_date, enrollment_date, graduation_date, gpa, profile_pic) VALUES
(1001, 'John Liu', 123345566, '2001-04-05', '2020-01-15', '2024-06-15', 4, LOAD_FILE('/usr/local/mysql/data/john_pp.jpeg')),
(1003, 'Rita Ora', 132345166, '2001-01-14', '2020-01-15', '2024-06-15', 4.2, LOAD_FILE('/usr/local/mysql/data/rita_pp.jpeg')),
(1007, 'Philip Lose', 321345566, '2001-06-15', '2020-01-15', '2024-06-15', 3.8, LOAD_FILE('/usr/local/mysql/data/philip_pp.jpeg')),
(1010, 'Samantha Prabhu', 3217165566, '2001-03-21', '2020-01-15', '2024-06-15', 4.9, LOAD_FILE('/usr/local/mysql/data/cs_logo.png')),
(1011, 'Vikas Jain', 321345662, '2001-7-18', '2020-01-15', NULL, 3.3, LOAD_FILE('/usr/local/mysql/data/vikas_pp.jpeg'));

SELECT * from DepartmentComplete;

SELECT * from StudentComplete;

-- INDIRECT STORAGE
-- Alter Table DepartmentComplete to drop logo
ALTER TABLE DepartmentComplete
DROP COLUMN logo;

-- Alter Table DepartmentComplete to add logo_path
ALTER TABLE DepartmentComplete
ADD logo_path VARCHAR (256);

-- Alter Table StudentComplete to drop profile_pic
ALTER TABLE StudentComplete
DROP COLUMN profile_pic;

-- Alter Table StudentComplete to add profile_pic_path
ALTER TABLE StudentComplete
ADD profile_pic_path VARCHAR (256);


-- Update data
UPDATE DepartmentComplete SET logo_path='/usr/local/mysql/data/cs_logo.png' WHERE code ='CS';
UPDATE DepartmentComplete SET logo_path='/usr/local/mysql/data/ece_logo.png' WHERE code ='EC';
UPDATE DepartmentComplete SET logo_path='/usr/local/mysql/data/ss_logo.png' WHERE code ='SS';
UPDATE DepartmentComplete SET logo_path='/usr/local/mysql/data/cb_logo.png' WHERE code ='CB';
UPDATE DepartmentComplete SET logo_path='/usr/local/mysql/data/ma_logo.png' WHERE code ='MA';

UPDATE StudentComplete SET profile_pic_path='/usr/local/mysql/data/john_pp.jpeg' WHERE name ='John Liu';
UPDATE StudentComplete SET profile_pic_path='/usr/local/mysql/data/rita_pp.jpeg' WHERE name ='Rita Ora';
UPDATE StudentComplete SET profile_pic_path='/usr/local/mysql/data/philip_pp.jpeg' WHERE name ='Philip Lose';
UPDATE StudentComplete SET profile_pic_path='/usr/local/mysql/data/samantha_pp.jpeg' WHERE name ='Samantha Prabhu';
UPDATE StudentComplete SET profile_pic_path='/usr/local/mysql/data/vikas_pp.jpeg' WHERE name ='Vikas Jain';

-- END
Binary file added mysql-queries/mysql-images/images/cb_logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added mysql-queries/mysql-images/images/cs_logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added mysql-queries/mysql-images/images/ece_logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added mysql-queries/mysql-images/images/john_pp.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added mysql-queries/mysql-images/images/ma_logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added mysql-queries/mysql-images/images/philip_pp.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added mysql-queries/mysql-images/images/rita_pp.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added mysql-queries/mysql-images/images/ss_logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added mysql-queries/mysql-images/images/vikas_pp.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
36 changes: 36 additions & 0 deletions mysql-queries/mysql-pattern-matching/pattern-matching.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
-- Change schema to University
USE University;

-- LIKE
SELECT * FROM Student
WHERE name LIKE LOWER ('R%');

SELECT * FROM Student
WHERE name LIKE BINARY 'r%';

SELECT * FROM Student
WHERE name LIKE '_________';

-- REGEXP_LIKE
SELECT * FROM Student
WHERE REGEXP_LIKE(name, '^R');

SELECT * FROM Student
WHERE REGEXP_LIKE(name, '^r', 'c');

SELECT Department.name, Course.name
FROM Department LEFT JOIN Course ON Department.id = Course.department_id
WHERE REGEXP_LIKE(Course.name, 'to')
AND Department.code="CS";

-- LOCATE
SELECT * FROM Student
WHERE LOCATE('R', name, 1)=1;

SELECT * FROM Department
WHERE LOCATE('a', name) < 0
AND LOCATE('a', name) < 0
AND LOCATE('e', name) < 0
AND LOCATE('i', name) < 0
AND LOCATE('o', name) < 0
AND LOCATE('u', name) < 0;
Loading