Welcome to our SQL Auditing tutorial! In this lesson, we'll learn about tracking changes in a database and ensuring data integrity. This skill is essential for any developer or data analyst. Let's dive in! 🎯
SQL auditing is the process of recording and analyzing database activities. This helps identify unauthorized access, data manipulation, and other security threats. Auditing can also be used to track changes made by authorized users for version control and compliance purposes. 💡
Before we dive into examples, let's set up a simple database to work with.
CREATE DATABASE mydb;
USE mydb;
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(255),
position VARCHAR(255),
salary DECIMAL(10,2)
);
-- Insert some data
INSERT INTO employees (id, name, position, salary) VALUES (1, 'John', 'Software Engineer', 70000);
INSERT INTO employees (id, name, position, salary) VALUES (2, 'Jane', 'Data Analyst', 60000);Logging SQL statements can help track changes made to the database over time. Here's an example of logging all INSERT, UPDATE, and DELETE statements in our employees table.
-- Enable logging
SET GLOBAL general_log = 'ON';
-- Insert new employee
INSERT INTO employees (id, name, position, salary) VALUES (3, 'Doe', 'Designer', 80000);
-- Check the log
SELECT * FROM mysql.general_log WHERE Command_Type = 'Query';Triggers are a more advanced auditing method. Here's an example of creating a trigger that logs changes made to the employees table.
-- Create a trigger for the employees table
DELIMITER $$
CREATE TRIGGER log_employee_changes AFTER INSERT ON employees
FOR EACH ROW
BEGIN
INSERT INTO employee_audit (id, name, position, salary, operation, timestamp)
VALUES (NEW.id, NEW.name, NEW.position, NEW.salary, 'Insert', NOW());
END $$
DELIMITER ;
-- Insert a new employee
INSERT INTO employees (id, name, position, salary) VALUES (4, 'Smith', 'Project Manager', 90000);
-- Check the audit table
SELECT * FROM employee_audit;What is the purpose of SQL auditing?
What is the difference between logging SQL statements and using triggers for auditing?