MySQL Tutorial


Beginners To Experts


The site is under development.

MySQL Tutorial

1.1 What is MySQL?
MySQL is an open-source relational database management system based on SQL (Structured Query Language).

1.2 Features of MySQL
Some features include cross-platform support, high performance, security, and scalability.

1.3 Installing MySQL on Windows
1. Download MySQL Installer
2. Run setup and follow wizard
3. Configure root password and start service

1.4 Installing MySQL on Linux
sudo apt update
sudo apt install mysql-server
sudo mysql_secure_installation

1.5 Starting MySQL Server
sudo systemctl start mysql
sudo systemctl enable mysql

1.6 Logging into MySQL
mysql -u root -p

1.7 Basic MySQL Commands
SHOW DATABASES;
CREATE DATABASE testdb;
USE testdb;

1.8 MySQL Workbench Overview
MySQL Workbench is a GUI tool for managing MySQL databases. It includes tools for query, design, and admin.

1.9 Connecting MySQL to Applications
Use language-specific libraries like:
- PHP: mysqli, PDO
- Python: mysql-connector-python

1.10 MySQL vs. Other RDBMS
MySQL is widely used due to ease of use and community support, though others like PostgreSQL offer advanced features.

2.1 Creating a Database
CREATE DATABASE company;

2.2 Using a Database
USE company;

2.3 Creating a Table
CREATE TABLE employees (id INT PRIMARY KEY, name VARCHAR(100), age INT);

2.4 Describing a Table
DESCRIBE employees;

2.5 Altering a Table
ALTER TABLE employees ADD COLUMN department VARCHAR(50);

2.6 Dropping a Table
DROP TABLE employees;

2.7 Dropping a Database
DROP DATABASE company;

2.8 Renaming a Table
RENAME TABLE employees TO staff;

2.9 Viewing Tables
SHOW TABLES;

2.10 Table Storage Engines
SHOW ENGINES;

3.1 Numeric Data Types
INT, DECIMAL, FLOAT, DOUBLE

3.2 String Data Types
CHAR, VARCHAR, TEXT

3.3 Date and Time Types
DATE, DATETIME, TIMESTAMP

3.4 NULL and NOT NULL
CREATE TABLE example (name VARCHAR(50) NOT NULL);

3.5 DEFAULT Values
CREATE TABLE example (active BOOLEAN DEFAULT TRUE);

3.6 PRIMARY KEY Constraint
CREATE TABLE example (id INT PRIMARY KEY);

3.7 UNIQUE Constraint
CREATE TABLE example (email VARCHAR(100) UNIQUE);

3.8 CHECK Constraint
CREATE TABLE example (age INT CHECK (age > 18));

3.9 FOREIGN KEY Constraint
CREATE TABLE orders (id INT, user_id INT, FOREIGN KEY(user_id) REFERENCES users(id));

3.10 AUTO_INCREMENT
CREATE TABLE example (id INT AUTO_INCREMENT PRIMARY KEY);

4.1 INSERT Statement
INSERT INTO employees (name, age) VALUES ('Alice', 30);

4.2 Multiple INSERTs
INSERT INTO employees (name, age) VALUES ('Bob', 25), ('Charlie', 28);

4.3 SELECT Statement
SELECT * FROM employees;

4.4 WHERE Clause
SELECT * FROM employees WHERE age > 25;

4.5 ORDER BY Clause
SELECT * FROM employees ORDER BY age DESC;

4.6 LIMIT Clause
SELECT * FROM employees LIMIT 5;

4.7 LIKE Operator
SELECT * FROM employees WHERE name LIKE 'A%';

4.8 BETWEEN Operator
SELECT * FROM employees WHERE age BETWEEN 25 AND 35;

4.9 IN Operator
SELECT * FROM employees WHERE department IN ('HR', 'IT');

4.10 IS NULL Check
SELECT * FROM employees WHERE department IS NULL;

5.1 UPDATE Statement
UPDATE employees SET age = 32 WHERE name = 'Alice';

5.2 Update Multiple Columns
UPDATE employees SET age = 33, department = 'HR' WHERE id = 1;

5.3 Using WHERE in UPDATE
UPDATE employees SET department = 'Sales' WHERE department IS NULL;

5.4 DELETE Statement
DELETE FROM employees WHERE name = 'Bob';

5.5 DELETE with Condition
DELETE FROM employees WHERE age < 25;

5.6 TRUNCATE Table
TRUNCATE TABLE employees;

5.7 Safe Updates Mode
SET SQL_SAFE_UPDATES = 0;

5.8 Affected Rows
SELECT ROW_COUNT();

5.9 DELETE vs TRUNCATE
-- DELETE can use WHERE clause, TRUNCATE removes all rows faster

5.10 ROLLBACK Deleted Data
START TRANSACTION;
DELETE FROM employees;
ROLLBACK;

6.1 String Functions
SELECT UPPER('hello'), LOWER('WORLD');

6.2 Numeric Functions
SELECT ABS(-5), ROUND(3.14159, 2);

6.3 Date Functions
SELECT CURDATE(), NOW();

6.4 Conversion Functions
SELECT CAST('2023-01-01' AS DATE);

6.5 Aggregate Functions
SELECT COUNT(*), AVG(age), MAX(age) FROM employees;

6.6 Math Functions
SELECT POW(2, 3), SQRT(16);

6.7 Control Flow Functions
SELECT IF(age > 30, 'Senior', 'Junior') FROM employees;

6.8 JSON Functions
SELECT JSON_OBJECT('name', 'Alice', 'age', 30);

6.9 NULL Handling
SELECT IFNULL(NULL, 'Default');

6.10 Grouping with HAVING
SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 2;

7.1 INNER JOIN
SELECT * FROM orders INNER JOIN customers ON orders.customer_id = customers.id;

7.2 LEFT JOIN
SELECT * FROM customers LEFT JOIN orders ON customers.id = orders.customer_id;

7.3 RIGHT JOIN
SELECT * FROM orders RIGHT JOIN customers ON orders.customer_id = customers.id;

7.4 FULL OUTER JOIN
SELECT * FROM customers
LEFT JOIN orders ON customers.id = orders.customer_id
UNION
SELECT * FROM customers
RIGHT JOIN orders ON customers.id = orders.customer_id;

7.5 SELF JOIN
SELECT A.name, B.name FROM employees A, employees B WHERE A.manager_id = B.id;

7.6 CROSS JOIN
SELECT * FROM employees CROSS JOIN departments;

7.7 NATURAL JOIN
SELECT * FROM employees NATURAL JOIN departments;

7.8 Using Aliases
SELECT E.name, D.name FROM employees E JOIN departments D ON E.dept_id = D.id;

7.9 Multiple Joins
SELECT * FROM orders
JOIN customers ON orders.customer_id = customers.id
JOIN products ON orders.product_id = products.id;

7.10 Join Conditions
SELECT * FROM employees E JOIN departments D ON E.dept_id = D.id WHERE D.name = 'IT';

8.1 Creating Indexes
CREATE INDEX idx_name ON employees(name);

8.2 Composite Indexes
CREATE INDEX idx_name_age ON employees(name, age);

8.3 Unique Index
CREATE UNIQUE INDEX idx_email ON employees(email);

8.4 Dropping Index
DROP INDEX idx_name ON employees;

8.5 Creating Views
CREATE VIEW view_employees AS SELECT name, age FROM employees;

8.6 Querying Views
SELECT * FROM view_employees;

8.7 Updating Views
CREATE OR REPLACE VIEW view_employees AS SELECT name, age, department FROM employees;

8.8 Dropping Views
DROP VIEW view_employees;

8.9 Indexed Views
-- Not supported in MySQL directly, use indexed base tables for performance.

8.10 Materialized Views
-- MySQL does not support materialized views natively.

9.1 What is a Transaction?
START TRANSACTION;

9.2 COMMIT
COMMIT;

9.3 ROLLBACK
ROLLBACK;

9.4 SAVEPOINT
SAVEPOINT sp1;

9.5 ROLLBACK TO SAVEPOINT
ROLLBACK TO SAVEPOINT sp1;

9.6 RELEASE SAVEPOINT
RELEASE SAVEPOINT sp1;

9.7 Transaction Isolation Levels
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

9.8 Implicit Transactions
UPDATE employees SET age = age + 1;

9.9 Explicit Locks
LOCK TABLES employees WRITE;

9.10 Unlocking Tables
UNLOCK TABLES;

10.1 Creating Users
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

10.2 Granting Privileges
GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost';

10.3 Revoking Privileges
REVOKE ALL PRIVILEGES ON *.* FROM 'newuser'@'localhost';

10.4 Dropping Users
DROP USER 'newuser'@'localhost';

10.5 Viewing Privileges
SHOW GRANTS FOR 'newuser'@'localhost';

10.6 Changing Passwords
ALTER USER 'newuser'@'localhost' IDENTIFIED BY 'newpassword';

10.7 Creating Roles
CREATE ROLE 'developer';

10.8 Granting Roles
GRANT 'developer' TO 'newuser'@'localhost';

10.9 Setting Default Roles
SET DEFAULT ROLE 'developer' TO 'newuser'@'localhost';

10.10 Dropping Roles
DROP ROLE 'developer';

11.1 Creating Procedures
DELIMITER //
CREATE PROCEDURE getEmployees()
BEGIN
  SELECT * FROM employees;
END //
DELIMITER ;

11.2 Executing Procedures
CALL getEmployees();

11.3 Parameters in Procedures
CREATE PROCEDURE getAge(IN emp_id INT)
BEGIN
  SELECT age FROM employees WHERE id = emp_id;
END;

11.4 OUT Parameters
CREATE PROCEDURE getCount(OUT total INT)
BEGIN
  SELECT COUNT(*) INTO total FROM employees;
END;

11.5 INOUT Parameters
CREATE PROCEDURE addFive(INOUT num INT)
BEGIN
  SET num = num + 5;
END;

11.6 Deleting Procedures
DROP PROCEDURE getEmployees;

11.7 SHOW PROCEDURE STATUS
SHOW PROCEDURE STATUS WHERE Db = 'testdb';

11.8 CONDITIONALS in Procedures
IF age > 30 THEN SET level = 'Senior'; ELSE SET level = 'Junior'; END IF;

11.9 LOOP in Procedures
LOOP statements can be added using REPEAT or WHILE blocks.

11.10 Cursor Use
DECLARE cursor CURSOR FOR SELECT name FROM employees;

12.1 Creating Functions
CREATE FUNCTION square(x INT) RETURNS INT RETURN x * x;

12.2 Executing Functions
SELECT square(5);

12.3 Function with Logic
CREATE FUNCTION age_group(age INT) RETURNS VARCHAR(10)
RETURN IF(age < 18, 'Minor', 'Adult');

12.4 Dropping Functions
DROP FUNCTION square;

12.5 SHOW FUNCTION STATUS
SHOW FUNCTION STATUS WHERE Db = 'testdb';

12.6 Function with SQL Queries
CREATE FUNCTION total_employees() RETURNS INT
BEGIN
  DECLARE total INT;
  SELECT COUNT(*) INTO total FROM employees;
  RETURN total;
END;

12.7 Nested Function Calls
SELECT square(total_employees());

12.8 Parameters and Defaults
-- MySQL functions do not support default parameter values directly

12.9 Using Functions in SELECT
SELECT name, age_group(age) FROM employees;

12.10 Best Practices
Keep functions pure: avoid changes to database state inside them.

13.1 Creating a Trigger
CREATE TRIGGER before_insert_emp
BEFORE INSERT ON employees
FOR EACH ROW SET NEW.created_at = NOW();

13.2 AFTER INSERT Trigger
CREATE TRIGGER after_insert_log
AFTER INSERT ON employees
FOR EACH ROW INSERT INTO log_table(action) VALUES('inserted');

13.3 BEFORE UPDATE Trigger
CREATE TRIGGER before_update_emp
BEFORE UPDATE ON employees
FOR EACH ROW SET NEW.updated_at = NOW();

13.4 AFTER UPDATE Trigger
CREATE TRIGGER after_update_log
AFTER UPDATE ON employees
FOR EACH ROW INSERT INTO log_table(action) VALUES('updated');

13.5 BEFORE DELETE Trigger
CREATE TRIGGER before_delete_emp
BEFORE DELETE ON employees
FOR EACH ROW SET @deleted_name = OLD.name;

13.6 AFTER DELETE Trigger
CREATE TRIGGER after_delete_log
AFTER DELETE ON employees
FOR EACH ROW INSERT INTO log_table(action) VALUES('deleted');

13.7 Viewing Triggers
SHOW TRIGGERS;

13.8 Dropping Triggers
DROP TRIGGER before_insert_emp;

13.9 Limiting Trigger Use
-- Use conditions within trigger body to prevent unintended execution

13.10 Trigger Errors
-- Use SIGNAL to raise custom errors in triggers

14.1 Enabling Event Scheduler
SET GLOBAL event_scheduler = ON;

14.2 Creating Events
CREATE EVENT ev_backup
ON SCHEDULE EVERY 1 DAY
DO INSERT INTO backup_log(run_time) VALUES(NOW());

14.3 One-Time Event
CREATE EVENT ev_once
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO DELETE FROM temp_data;

14.4 Altering Events
ALTER EVENT ev_backup DISABLE;

14.5 Dropping Events
DROP EVENT ev_backup;

14.6 Viewing Events
SHOW EVENTS;

14.7 Using EVENT DEFINER
CREATE DEFINER = 'admin'@'localhost' EVENT ev_def...

14.8 Event Permissions
GRANT EVENT ON testdb.* TO 'scheduler'@'localhost';

14.9 Logging Events
-- Use log table to track event execution manually.

14.10 Best Practices
Use clear names and monitor their performance.

15.1 Exporting with mysqldump
mysqldump -u root -p testdb > testdb_backup.sql

15.2 Importing with mysql
mysql -u root -p testdb < testdb_backup.sql

15.3 Selective Backup
mysqldump -u root -p testdb employees > emp_backup.sql

15.4 Backup with Triggers
mysqldump -u root -p --triggers testdb > full_backup.sql

15.5 Backup Stored Procedures
mysqldump -u root -p --routines testdb > procs.sql

15.6 Backup All Databases
mysqldump -u root -p --all-databases > alldb.sql

15.7 Restore with CREATE
mysql -u root -p -e "CREATE DATABASE testdb_restore"

15.8 Restoring Triggers
-- Included automatically in dump unless --skip-triggers

15.9 Restoring with GUI
Use MySQL Workbench > Data Import/Restore

15.10 Automating Backup
Use cron jobs in Linux or Task Scheduler in Windows to run dump script daily.

16.1 Query Optimization
EXPLAIN SELECT * FROM employees WHERE age > 30;

16.2 Index Usage
CREATE INDEX idx_age ON employees(age);

16.3 Analyzing Slow Queries
SHOW VARIABLES LIKE 'slow_query_log';

16.4 Caching Results
SET GLOBAL query_cache_size = 1048576;

16.5 Optimizing Joins
EXPLAIN SELECT * FROM employees JOIN departments ON employees.dept_id = departments.id;

16.6 Reducing Redundancy
-- Normalize tables to avoid repeating data

16.7 Profiling Queries
SET PROFILING = 1; SELECT * FROM employees; SHOW PROFILES;

16.8 Table Maintenance
ANALYZE TABLE employees;

16.9 Optimizing Temporary Tables
-- Use MEMORY engine for faster temp tables

16.10 Using LIMIT
SELECT * FROM employees LIMIT 10;

17.1 User Authentication
CREATE USER 'secure_user'@'localhost' IDENTIFIED BY 'S@feP@ss';

17.2 Password Expiry
ALTER USER 'secure_user'@'localhost' PASSWORD EXPIRE INTERVAL 30 DAY;

17.3 Account Locking
ALTER USER 'secure_user'@'localhost' ACCOUNT LOCK;

17.4 SSL Connections
-- Enable SSL and set REQUIRE SSL for users

17.5 Limiting Access
GRANT SELECT ON sensitive_db.* TO 'reader'@'192.168.1.%';

17.6 Secure File Priv
SHOW VARIABLES LIKE 'secure_file_priv';

17.7 Auditing Logins
-- Use general_log or third-party plugin

17.8 Encryption at Rest
-- Enable InnoDB encryption support

17.9 Data Masking
SELECT CONCAT(LEFT(ssn,3), '-**-****') FROM users;

17.10 Backups with Encryption
mysqldump -u root -p testdb | openssl enc -aes-256-cbc -out backup.sql.enc

18.1 What is Replication?
-- Replication copies data from one MySQL server to another.

18.2 Setting up Master Server
CHANGE MASTER TO MASTER_HOST='master_host_ip', MASTER_USER='replicator', MASTER_PASSWORD='password', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=107;

18.3 Setting up Slave Server
START SLAVE;

18.4 Checking Slave Status
SHOW SLAVE STATUS\G;

18.5 Stopping Slave
STOP SLAVE;

18.6 Skipping Errors
SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 1; START SLAVE;

18.7 Replication Types
-- Statement-based, Row-based, Mixed replication.

18.8 Delayed Replication
CHANGE MASTER TO MASTER_DELAY=3600;

18.9 Multi-Source Replication
-- Allows a slave to replicate from multiple masters.

18.10 Monitoring Replication
SHOW PROCESSLIST;

19.1 What is Partitioning?
-- Partitioning splits a large table into smaller pieces for performance.

19.2 Types of Partitioning
-- RANGE, LIST, HASH, KEY partitioning.

19.3 RANGE Partition Example
CREATE TABLE orders (
  id INT,
  order_date DATE
)
PARTITION BY RANGE (YEAR(order_date)) (
  PARTITION p2019 VALUES LESS THAN (2020),
  PARTITION p2020 VALUES LESS THAN (2021),
  PARTITION pmax VALUES LESS THAN MAXVALUE
);

19.4 LIST Partition Example
CREATE TABLE employees (
  id INT,
  region VARCHAR(20)
)
PARTITION BY LIST COLUMNS(region) (
  PARTITION p_north VALUES IN ('North'),
  PARTITION p_south VALUES IN ('South')
);

19.5 HASH Partition Example
CREATE TABLE users (
  id INT,
  username VARCHAR(50)
)
PARTITION BY HASH(id)
PARTITIONS 4;

19.6 ALTER PARTITION
ALTER TABLE orders REORGANIZE PARTITION pmax INTO (PARTITION p2021 VALUES LESS THAN (2022), PARTITION pmax VALUES LESS THAN MAXVALUE);

19.7 Dropping Partitions
ALTER TABLE orders DROP PARTITION p2019;

19.8 Querying Partitioned Tables
SELECT * FROM orders WHERE order_date BETWEEN '2020-01-01' AND '2020-12-31';

19.9 Benefits of Partitioning
-- Improved query performance and easier maintenance.

19.10 Limitations
-- Not all storage engines support partitioning.

20.1 What is Full-Text Search?
-- Full-text search allows searching text-based data efficiently.

20.2 Creating Full-Text Index
CREATE FULLTEXT INDEX idx_content ON articles(content);

20.3 Using MATCH...AGAINST
SELECT * FROM articles WHERE MATCH(content) AGAINST('database');

20.4 Boolean Mode Search
SELECT * FROM articles WHERE MATCH(content) AGAINST('+database -mysql' IN BOOLEAN MODE);

20.5 Natural Language Mode
SELECT * FROM articles WHERE MATCH(content) AGAINST('database');

20.6 Relevance Ranking
SELECT *, MATCH(content) AGAINST('database') AS relevance FROM articles ORDER BY relevance DESC;

20.7 Stopwords
-- Words ignored in full-text search (e.g., 'the', 'and').

20.8 Limitations
-- Minimum word length and stopwords can affect search results.

20.9 Updating Full-Text Index
OPTIMIZE TABLE articles;

20.10 Alternative: External Search Engines
-- Use Elasticsearch or Sphinx for advanced search features.

21.1 What is a View?
-- A virtual table representing the result of a query.

21.2 Creating a View
CREATE VIEW employee_names AS SELECT id, name FROM employees;

21.3 Querying a View
SELECT * FROM employee_names;

21.4 Updating a View
CREATE OR REPLACE VIEW employee_names AS SELECT id, name, age FROM employees;

21.5 Dropping a View
DROP VIEW employee_names;

21.6 Updatable Views
-- Views based on single table and without aggregates can be updatable.

21.7 Using Views for Security
GRANT SELECT ON employee_names TO 'readonly_user'@'localhost';

21.8 View Limitations
-- Views cannot contain ORDER BY without LIMIT in MySQL.

21.9 Materialized Views (Workaround)
-- MySQL does not support materialized views natively; simulate with tables and triggers.

21.10 Performance Considerations
-- Views do not store data; performance depends on underlying queries.

22.1 Creating a Stored Procedure
DELIMITER $$ 
CREATE PROCEDURE GetEmployeeCount()
BEGIN
  SELECT COUNT(*) FROM employees;
END$$
DELIMITER ;

22.2 Calling a Stored Procedure
CALL GetEmployeeCount();

22.3 Procedure with Parameters
DELIMITER $$
CREATE PROCEDURE GetEmployeesByDept(IN dept_id INT)
BEGIN
  SELECT * FROM employees WHERE dept_id = dept_id;
END$$
DELIMITER ;

22.4 Using OUT Parameters
DELIMITER $$
CREATE PROCEDURE GetDeptEmployeeCount(IN dept_id INT, OUT emp_count INT)
BEGIN
  SELECT COUNT(*) INTO emp_count FROM employees WHERE dept_id = dept_id;
END$$
DELIMITER ;

22.5 Dropping a Procedure
DROP PROCEDURE IF EXISTS GetEmployeeCount;

22.6 Error Handling
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
  -- Handle error
END;

22.7 Procedure Variables
DECLARE total INT DEFAULT 0;

22.8 Using Procedures in Applications
CALL GetEmployeesByDept(1);

22.9 Performance Considerations
-- Stored procedures reduce client-server communication overhead.

22.10 Security Aspects
GRANT EXECUTE ON PROCEDURE GetEmployeeCount TO 'user'@'localhost';

23.1 What is a Transaction?
-- A sequence of SQL statements executed as a single unit.

23.2 Starting a Transaction
START TRANSACTION;

23.3 Committing a Transaction
COMMIT;

23.4 Rolling Back a Transaction
ROLLBACK;

23.5 Savepoints
SAVEPOINT sp1;

23.6 Rolling Back to Savepoint
ROLLBACK TO SAVEPOINT sp1;

23.7 Setting Isolation Levels
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

23.8 Autocommit Mode
SET autocommit=0;

23.9 Using Transactions in Procedures
BEGIN
  START TRANSACTION;
  -- statements
  COMMIT;
END;

23.10 Best Practices
Avoid long transactions to reduce locking and contention.

24.1 Logical Backups
mysqldump -u root -p database_name > backup.sql

24.2 Physical Backups
-- Copy data directory files while server is stopped

24.3 Incremental Backups
-- Use binary logs for point-in-time recovery

24.4 Backup Automation
crontab -e
0 2 * * * /usr/bin/mysqldump -u root -p password database_name > backup.sql

24.5 Verifying Backups
mysql -u root -p database_name < backup.sql

24.6 Backup Compression
mysqldump -u root -p database_name | gzip > backup.sql.gz

24.7 Secure Backup Storage
-- Store backups in encrypted or secure locations

24.8 Backup Retention Policies
-- Keep backups for defined periods and remove old ones

24.9 Point-in-Time Recovery
mysqlbinlog binlog.000001 | mysql -u root -p database_name

24.10 Disaster Recovery Planning
-- Regularly test backups and restore procedures

25.1 What is Performance Schema?
-- A feature for monitoring MySQL server performance.

25.2 Enabling Performance Schema
SHOW VARIABLES LIKE 'performance_schema';

25.3 Querying Performance Schema Tables
SELECT * FROM performance_schema.events_statements_summary_by_digest;

25.4 Monitoring Wait Events
SELECT * FROM performance_schema.events_waits_summary_global_by_event_name;

25.5 Using Performance Schema for Index Analysis
SELECT * FROM performance_schema.table_io_waits_summary_by_index_usage;

25.6 Configuring Performance Schema
UPDATE performance_schema.setup_instruments SET ENABLED = 'YES' WHERE NAME LIKE '%wait%';

25.7 Performance Schema Limitations
-- Can introduce overhead; use selectively in production.

25.8 Integrating with Monitoring Tools
-- Many tools like Percona Monitoring integrate with Performance Schema.

25.9 Viewing Mutex and Lock Contention
SELECT * FROM performance_schema.events_waits_summary_by_instance WHERE EVENT_NAME LIKE '%mutex%';

25.10 Best Practices
Enable only needed instruments and consumers to minimize overhead.

26.1 mysqldump Basics
mysqldump -u root -p database_name > backup.sql

26.2 Using mysqlpump
mysqlpump -u root -p database_name > backup_pump.sql

26.3 Percona XtraBackup
xtrabackup --backup --target-dir=/data/backup/

26.4 Automating Backups
crontab -e
0 3 * * * /usr/bin/mysqldump -u root -p password database_name > backup.sql

26.5 Backup Compression
mysqldump -u root -p database_name | gzip > backup.sql.gz

26.6 Encrypting Backups
mysqldump -u root -p database_name | openssl enc -aes-256-cbc -out backup.sql.enc

26.7 Restoring Backups
mysql -u root -p database_name < backup.sql

26.8 Incremental Backup Support
-- Percona XtraBackup supports incremental backups.

26.9 Backup Verification
mysqlcheck -u root -p --check database_name

26.10 Choosing the Right Tool
-- Consider data size, downtime, and backup type requirements.

27.1 Creating Secure Users
CREATE USER 'secure_user'@'localhost' IDENTIFIED BY 'StrongPass123!';

27.2 Granting Minimal Privileges
GRANT SELECT, INSERT ON mydb.* TO 'secure_user'@'localhost';

27.3 Revoking Privileges
REVOKE DELETE ON mydb.* FROM 'secure_user'@'localhost';

27.4 Password Policies
-- Enforce password complexity and expiration.

27.5 Using SSL/TLS
-- Configure MySQL for encrypted client connections.

27.6 Auditing User Activity
-- Enable audit plugins or use general query log.

27.7 Securing Backup Files
-- Store backups securely and encrypt if necessary.

27.8 Protecting Against SQL Injection
-- Use prepared statements and parameterized queries.

27.9 Limiting User Connections
ALTER USER 'secure_user'@'localhost' WITH MAX_USER_CONNECTIONS 5;

27.10 Regular Security Audits
-- Periodically review user privileges and logs.

28.1 What is an Index?
-- An index speeds up data retrieval operations.

28.2 Creating Indexes
CREATE INDEX idx_name ON employees(name);

28.3 Dropping Indexes
DROP INDEX idx_name ON employees;

28.4 Composite Indexes
CREATE INDEX idx_name_age ON employees(name, age);

28.5 Unique Indexes
CREATE UNIQUE INDEX idx_email ON employees(email);

28.6 Using EXPLAIN for Query Plans
EXPLAIN SELECT * FROM employees WHERE name = 'John';

28.7 Index Statistics
SHOW INDEX FROM employees;

28.8 Covering Indexes
-- Indexes that contain all columns needed by a query.

28.9 Index Maintenance
ANALYZE TABLE employees;

28.10 When Not to Use Indexes
-- Avoid indexing columns with low cardinality or frequent updates.

29.1 Understanding EXPLAIN Output
EXPLAIN SELECT * FROM employees WHERE age > 30;

29.2 Using Indexes Effectively
CREATE INDEX idx_age ON employees(age);

29.3 Avoiding SELECT *
SELECT name, age FROM employees WHERE age > 30;

29.4 Query Caching
-- MySQL query cache is deprecated in latest versions.

29.5 Optimizing JOINs
SELECT e.name, d.department_name
FROM employees e
JOIN departments d ON e.dept_id = d.id;

29.6 Using LIMIT to Reduce Result Size
SELECT * FROM employees ORDER BY age DESC LIMIT 10;

29.7 Avoiding Functions in WHERE
-- Use indexed columns without wrapping them in functions.

29.8 Analyzing Slow Queries
SHOW SLOW LOGS;

29.9 Using Prepared Statements
PREPARE stmt FROM 'SELECT * FROM employees WHERE age > ?';
SET @age = 30;
EXECUTE stmt USING @age;

29.10 Regular Query Review
-- Regularly review and optimize slow and frequent queries.

30.1 What is Replication?
-- Copying data from one MySQL server to another.

30.2 Master-Slave Replication Setup
-- Configure master with log-bin and server-id in my.cnf

30.3 Starting Slave
CHANGE MASTER TO MASTER_HOST='master_host', MASTER_USER='repl', MASTER_PASSWORD='password', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=  4;
START SLAVE;

30.4 Monitoring Replication Status
SHOW SLAVE STATUS\G;

30.5 Replication Filters
-- Use replicate-do-db or replicate-ignore-db to filter databases

30.6 Semi-Synchronous Replication
-- Ensures master waits for at least one slave to acknowledge.

30.7 Replication Troubleshooting
STOP SLAVE; SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 1; START SLAVE;

30.8 Multi-Source Replication
-- Slave can replicate from multiple masters.

30.9 Replication Lag
SHOW SLAVE STATUS\G; -- Check Seconds_Behind_Master

30.10 Replication Security
-- Use SSL and restrict replication user privileges.

31.1 What is Partitioning?
-- Splitting a large table into smaller, more manageable pieces.

31.2 Types of Partitioning
-- RANGE, LIST, HASH, KEY partitioning methods.

31.3 Creating a Range Partitioned Table
CREATE TABLE orders (
  order_id INT,
  order_date DATE
)
PARTITION BY RANGE (YEAR(order_date)) (
  PARTITION p0 VALUES LESS THAN (2018),
  PARTITION p1 VALUES LESS THAN (2020),
  PARTITION p2 VALUES LESS THAN MAXVALUE
);

31.4 Creating a List Partitioned Table
CREATE TABLE employees (
  emp_id INT,
  dept_id INT
)
PARTITION BY LIST (dept_id) (
  PARTITION p0 VALUES IN (1,2),
  PARTITION p1 VALUES IN (3,4)
);

31.5 Creating a Hash Partitioned Table
CREATE TABLE logs (
  log_id INT,
  user_id INT
)
PARTITION BY HASH(user_id)
PARTITIONS 4;

31.6 Altering Partitions
ALTER TABLE orders REORGANIZE PARTITION p2 INTO (
  PARTITION p2 VALUES LESS THAN (2022),
  PARTITION p3 VALUES LESS THAN MAXVALUE
);

31.7 Dropping Partitions
ALTER TABLE orders DROP PARTITION p0;

31.8 Benefits of Partitioning
-- Improves query performance and maintenance.

31.9 Limitations of Partitioning
-- Not all storage engines support partitioning; certain queries might not benefit.

31.10 Checking Partitions
SHOW CREATE TABLE orders;

32.1 What is Full-Text Search?
-- Searching text data efficiently using indexes.

32.2 Creating a Full-Text Index
CREATE TABLE articles (
  id INT PRIMARY KEY,
  title VARCHAR(200),
  body TEXT,
  FULLTEXT(title, body)
);

32.3 Using MATCH() AGAINST()
SELECT * FROM articles WHERE MATCH(title, body) AGAINST('database');

32.4 Boolean Mode Search
SELECT * FROM articles WHERE MATCH(title, body) AGAINST('+database -mysql' IN BOOLEAN MODE);

32.5 Natural Language Mode
SELECT * FROM articles WHERE MATCH(title, body) AGAINST('database' IN NATURAL LANGUAGE MODE);

32.6 Full-Text Search Limitations
-- Minimum word length and stopwords affect results.

32.7 Rebuilding Full-Text Indexes
OPTIMIZE TABLE articles;

32.8 Using Full-Text in InnoDB
-- Supported from MySQL 5.6 and later.

32.9 Ranking Results
SELECT id, MATCH(title, body) AGAINST('database') AS score FROM articles ORDER BY score DESC;

32.10 Best Practices
Use appropriate modes and maintain indexes regularly.

33.1 Creating a Table with JSON Column
CREATE TABLE products (
  id INT PRIMARY KEY,
  data JSON
);

33.2 Inserting JSON Data
INSERT INTO products (id, data) VALUES
(1, '{ "name": "Laptop", "price": 799 }');

33.3 Querying JSON Data
SELECT data->>'$.name' AS product_name FROM products;

33.4 JSON_EXTRACT Function
SELECT JSON_EXTRACT(data, '$.price') AS price FROM products;

33.5 Updating JSON Data
UPDATE products SET data = JSON_SET(data, '$.price', 899) WHERE id = 1;

33.6 Using JSON_ARRAY_APPEND
UPDATE products SET data = JSON_ARRAY_APPEND(data, '$.tags', 'new') WHERE id = 1;

33.7 JSON_CONTAINS Function
SELECT * FROM products WHERE JSON_CONTAINS(data, '"Laptop"', '$.name');

33.8 Indexing JSON Columns
CREATE INDEX idx_name ON products ((CAST(data->>'$.name' AS CHAR(100))));

33.9 Validating JSON Data
SELECT JSON_VALID(data) FROM products;

33.10 Best Practices with JSON
Use JSON for flexible schemas but prefer normalized tables for structured data.

34.1 Creating a View
CREATE VIEW employee_view AS
SELECT id, name, department FROM employees;

34.2 Querying a View
SELECT * FROM employee_view;

34.3 Updating a View
CREATE OR REPLACE VIEW employee_view AS
SELECT id, name, department, salary FROM employees;

34.4 Dropping a View
DROP VIEW employee_view;

34.5 Updatable Views
-- Views that can be used with INSERT, UPDATE, DELETE.

34.6 Views with Joins
CREATE VIEW emp_dept AS
SELECT e.name, d.name AS dept_name
FROM employees e
JOIN departments d ON e.dept_id = d.id;

34.7 Using Views for Security
-- Restrict access to specific columns via views.

34.8 Performance Considerations
-- Views do not store data; performance depends on underlying queries.

34.9 Materialized Views (Simulated)
-- Use tables and scheduled events to simulate materialized views.

34.10 Best Practices
Use views to simplify complex queries and enhance security.

35.1 What is a Transaction?
-- A sequence of SQL statements executed as a single unit.

35.2 Starting a Transaction
START TRANSACTION;

35.3 Committing a Transaction
COMMIT;

35.4 Rolling Back a Transaction
ROLLBACK;

35.5 Transaction Isolation Levels
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

35.6 Autocommit Mode
SET autocommit = 0;

35.7 Savepoints
SAVEPOINT sp1;
ROLLBACK TO sp1;

35.8 Using Transactions with InnoDB
-- InnoDB supports ACID-compliant transactions.

35.9 Handling Deadlocks
-- Detect and retry transactions on deadlock errors.

35.10 Best Practices
Keep transactions short and avoid user interaction within them.

36.1 Creating Users
CREATE USER 'user1'@'localhost' IDENTIFIED BY 'password123';

36.2 Granting Privileges
GRANT SELECT, INSERT ON mydb.* TO 'user1'@'localhost';

36.3 Revoking Privileges
REVOKE INSERT ON mydb.* FROM 'user1'@'localhost';

36.4 Changing Passwords
ALTER USER 'user1'@'localhost' IDENTIFIED BY 'newpassword';

36.5 Dropping Users
DROP USER 'user1'@'localhost';

36.6 Viewing User Privileges
SHOW GRANTS FOR 'user1'@'localhost';

36.7 Creating Users with Limited Hosts
CREATE USER 'user2'@'192.168.1.%' IDENTIFIED BY 'password';

36.8 Password Expiration Policy
ALTER USER 'user1'@'localhost' PASSWORD EXPIRE INTERVAL 90 DAY;

36.9 Using Roles
CREATE ROLE 'reporting';
GRANT SELECT ON mydb.* TO 'reporting';
GRANT 'reporting' TO 'user1'@'localhost';

36.10 Best Practices
Use least privilege principle and strong passwords.

37.1 Analyzing Slow Queries
SET GLOBAL slow_query_log = 'ON';
SHOW VARIABLES LIKE 'slow_query_log_file';

37.2 Using EXPLAIN for Query Optimization
EXPLAIN SELECT * FROM employees WHERE age > 30;

37.3 Optimizing Index Usage
CREATE INDEX idx_age ON employees(age);

37.4 Adjusting Buffer Pool Size
SET GLOBAL innodb_buffer_pool_size = 1073741824; -- 1GB

37.5 Query Cache Configuration
-- Deprecated in MySQL 8.0

37.6 Using Performance Schema
SELECT * FROM performance_schema.events_statements_summary_by_digest ORDER BY SUM_TIMER_WAIT DESC;

37.7 Optimizing Join Queries
SELECT e.name, d.dept_name FROM employees e JOIN departments d ON e.dept_id = d.id;

37.8 Monitoring Server Status
SHOW GLOBAL STATUS LIKE 'Threads_connected';

37.9 Using Partitioning for Performance
-- Split large tables to improve query efficiency.

37.10 Best Practices
Regularly analyze query performance and update indexes.

38.1 Logical Backup with mysqldump
mysqldump -u root -p mydb > mydb_backup.sql

38.2 Physical Backup with Percona XtraBackup
-- Use Percona XtraBackup for hot physical backups.

38.3 Using mysqlpump
mysqlpump -u root -p mydb > mydb_pump.sql

38.4 Backup Compression
mysqldump mydb | gzip > mydb_backup.sql.gz

38.5 Incremental Backups
-- Use binary logs for incremental backup.

38.6 Automating Backups
-- Schedule backups with cron jobs or Windows Task Scheduler.

38.7 Backup Verification
mysql -u root -p mydb < mydb_backup.sql

38.8 Restoring from Backup
mysql -u root -p mydb < mydb_backup.sql

38.9 Backup Best Practices
Keep backups secure, test restores regularly.

38.10 Using Cloud Backup Solutions
-- Consider cloud providers for offsite backups.

39.1 Using Strong Passwords
ALTER USER 'root'@'localhost' IDENTIFIED BY 'StrongP@ssw0rd!';

39.2 Limiting User Privileges
GRANT SELECT ON mydb.* TO 'user'@'localhost';

39.3 Enabling SSL Connections
-- Configure SSL in MySQL server and clients.

39.4 Auditing User Activity
-- Use MySQL Enterprise Audit plugin or third-party tools.

39.5 Updating MySQL Regularly
-- Keep MySQL server up to date with security patches.

39.6 Using Firewall Rules
-- Restrict access to MySQL port via firewall.

39.7 Disabling Remote Root Login
UPDATE mysql.user SET host='localhost' WHERE user='root' AND host!='localhost'; FLUSH PRIVILEGES;

39.8 Encrypting Data at Rest
-- Use InnoDB tablespace encryption.

39.9 Protecting Against SQL Injection
-- Use prepared statements and input validation.

39.10 Regular Security Audits
-- Periodically review logs and user privileges.

40.1 Using Performance Schema
SELECT * FROM performance_schema.events_statements_summary_by_digest ORDER BY SUM_TIMER_WAIT DESC;

40.2 Monitoring Threads
SHOW PROCESSLIST;

40.3 Checking Server Status Variables
SHOW GLOBAL STATUS;

40.4 Using INFORMATION_SCHEMA
SELECT * FROM information_schema.tables WHERE table_schema = 'mydb';

40.5 Enabling Slow Query Log
SET GLOBAL slow_query_log = 'ON';

40.6 Reading Slow Query Log
-- Check slow query log file at the path set by slow_query_log_file variable.

40.7 Using MySQL Enterprise Monitor
-- Tool for monitoring MySQL performance in real time.

40.8 Query Profiling
SET profiling = 1;
SELECT * FROM employees WHERE age > 30;
SHOW PROFILES;

40.9 Using sys Schema
SELECT * FROM sys.schema_unused_indexes;

40.10 Best Practices
Regularly monitor and analyze performance metrics for optimization.

41.1 Logical Backup with mysqldump
mysqldump -u root -p mydb > mydb_backup.sql

41.2 Physical Backup with Percona XtraBackup
-- Use Percona XtraBackup for hot physical backups.

41.3 Incremental Backups
-- Use binary logs for incremental backups.

41.4 Point-in-Time Recovery
-- Apply binary logs to restore to a specific point in time.

41.5 Restoring from Backup
mysql -u root -p mydb < mydb_backup.sql

41.6 Automating Backups
-- Use cron jobs or scheduled tasks to automate backup routines.

41.7 Backup Verification
-- Test restores regularly to ensure backup integrity.

41.8 Cloud Backup Solutions
-- Use cloud storage for offsite backups.

41.9 Backup Compression
mysqldump mydb | gzip > mydb_backup.sql.gz

41.10 Best Practices
Maintain multiple backup copies and document recovery procedures.

42.1 What is Replication?
-- Copying data from one MySQL server (master) to another (slave).

42.2 Setting up Master Server
CHANGE MASTER TO MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=107;

42.3 Setting up Slave Server
START SLAVE;

42.4 Checking Replication Status
SHOW SLAVE STATUS\G;

42.5 Stopping and Starting Replication
STOP SLAVE;
START SLAVE;

42.6 Replication Formats
-- Statement-based, row-based, and mixed formats.

42.7 Handling Replication Errors
-- Skip errors or fix and restart slave.

42.8 Semi-Synchronous Replication
-- Provides better durability guarantees.

42.9 Multi-Source Replication
-- Slave replicates from multiple masters.

42.10 Best Practices
Monitor replication lag and test failover procedures.

43.1 What is Partitioning?
-- Dividing a large table into smaller, manageable pieces called partitions.

43.2 Range Partitioning
CREATE TABLE sales (
  id INT,
  sale_date DATE
)
PARTITION BY RANGE (YEAR(sale_date)) (
  PARTITION p2019 VALUES LESS THAN (2020),
  PARTITION p2020 VALUES LESS THAN (2021)
);

43.3 List Partitioning
CREATE TABLE employees (
  id INT,
  dept_id INT
)
PARTITION BY LIST (dept_id) (
  PARTITION p1 VALUES IN (1,2),
  PARTITION p2 VALUES IN (3,4)
);

43.4 Hash Partitioning
CREATE TABLE logs (
  id INT,
  user_id INT
)
PARTITION BY HASH(user_id) PARTITIONS 4;

43.5 Key Partitioning
CREATE TABLE sessions (
  id INT,
  session_key VARCHAR(32)
)
PARTITION BY KEY(session_key) PARTITIONS 4;

43.6 Dropping Partitions
ALTER TABLE sales DROP PARTITION p2019;

43.7 Adding Partitions
ALTER TABLE sales ADD PARTITION (
  PARTITION p2021 VALUES LESS THAN (2022)
);

43.8 Querying Partitioned Tables
SELECT * FROM sales WHERE sale_date >= '2020-01-01';

43.9 Performance Considerations
-- Partition pruning improves query speed.

43.10 Best Practices
Choose partition type based on data and query patterns.

44.1 Creating a Stored Procedure
DELIMITER //
CREATE PROCEDURE GetEmployeeCount()
BEGIN
  SELECT COUNT(*) FROM employees;
END //
DELIMITER ;

44.2 Calling a Stored Procedure
CALL GetEmployeeCount();

44.3 Procedures with Parameters
CREATE PROCEDURE GetEmployeesByDept(IN dept_id INT)
BEGIN
  SELECT * FROM employees WHERE department_id = dept_id;
END;

44.4 Updating Data in Procedures
CREATE PROCEDURE UpdateSalary(IN emp_id INT, IN new_salary DECIMAL(10,2))
BEGIN
  UPDATE employees SET salary = new_salary WHERE id = emp_id;
END;

44.5 Dropping a Procedure
DROP PROCEDURE IF EXISTS GetEmployeeCount;

44.6 Error Handling in Procedures
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
  ROLLBACK;
END;

44.7 Using Variables in Procedures
DECLARE total INT;
SELECT COUNT(*) INTO total FROM employees;

44.8 Looping Constructs
WHILE total < 10 DO
  SET total = total + 1;
END WHILE;

44.9 Nested Procedures
CALL AnotherProcedure();

44.10 Best Practices
Keep procedures modular and use transactions for data integrity.

45.1 What is an Index?
-- Data structure that improves query speed.

45.2 Creating Indexes
CREATE INDEX idx_name ON employees(name);

45.3 Unique Indexes
CREATE UNIQUE INDEX idx_email ON employees(email);

45.4 Composite Indexes
CREATE INDEX idx_name_dept ON employees(name, department_id);

45.5 Dropping Indexes
DROP INDEX idx_name ON employees;

45.6 Indexes and Primary Keys
-- Primary key automatically creates a unique index.

45.7 Indexes on Foreign Keys
-- Create indexes to improve JOIN performance.

45.8 When Not to Use Indexes
-- Avoid on small tables or columns with low cardinality.

45.9 Monitoring Index Usage
SHOW INDEX FROM employees;

45.10 Best Practices
Create indexes based on query patterns and analyze regularly.

46.1 What is a View?
-- A virtual table based on the result of a query.

46.2 Creating Views
CREATE VIEW emp_view AS SELECT name, department_id FROM employees;

46.3 Querying Views
SELECT * FROM emp_view;

46.4 Updating Views
CREATE OR REPLACE VIEW emp_view AS SELECT name, department_id, salary FROM employees;

46.5 Dropping Views
DROP VIEW emp_view;

46.6 Updatable Views
-- Views that allow INSERT, UPDATE, DELETE operations if they meet certain criteria.

46.7 Using Views for Security
GRANT SELECT ON emp_view TO 'user1'@'localhost';

46.8 Views with Joins
CREATE VIEW emp_dept_view AS
SELECT e.name, d.dept_name FROM employees e JOIN departments d ON e.department_id = d.id;

46.9 Performance Considerations
-- Views do not store data, performance depends on underlying queries.

46.10 Best Practices
Use views to simplify complex queries and control data access.

47.1 What is a Transaction?
-- A sequence of SQL statements executed as a single unit of work.

47.2 Starting a Transaction
START TRANSACTION;

47.3 Committing a Transaction
COMMIT;

47.4 Rolling Back a Transaction
ROLLBACK;

47.5 Savepoints
SAVEPOINT savepoint1;

47.6 Rolling Back to a Savepoint
ROLLBACK TO SAVEPOINT savepoint1;

47.7 Setting Transaction Isolation Levels
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

47.8 Autocommit Mode
SET autocommit = 0;

47.9 Transactions with Stored Procedures
BEGIN
  START TRANSACTION;
  -- SQL statements
  COMMIT;
END;

47.10 Best Practices
Keep transactions short to reduce locking and contention.

48.1 Creating Users
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

48.2 Granting Privileges
GRANT SELECT, INSERT ON mydb.* TO 'newuser'@'localhost';

48.3 Revoking Privileges
REVOKE INSERT ON mydb.* FROM 'newuser'@'localhost';

48.4 Dropping Users
DROP USER 'newuser'@'localhost';

48.5 Viewing User Privileges
SHOW GRANTS FOR 'newuser'@'localhost';

48.6 Password Expiration
ALTER USER 'newuser'@'localhost' PASSWORD EXPIRE INTERVAL 90 DAY;

48.7 Account Locking
ALTER USER 'newuser'@'localhost' ACCOUNT LOCK;

48.8 Password Policies
-- Configure validate_password plugin for complexity rules.

48.9 Using Roles
CREATE ROLE 'read_only';
GRANT SELECT ON mydb.* TO 'read_only';
GRANT 'read_only' TO 'newuser'@'localhost';

48.10 Best Practices
Use least privilege principle and regularly review user accounts.

49.1 Logical Backup with mysqldump
mysqldump -u root -p mydb > mydb_backup.sql

49.2 Physical Backup
-- Copy raw data files with server offline for physical backup.

49.3 Incremental Backups
-- Use binary logs to perform incremental backups.

49.4 Point-in-Time Recovery
-- Restore backup and replay binary logs up to a point in time.

49.5 Restoring Backups
mysql -u root -p mydb < mydb_backup.sql

49.6 Automating Backups
-- Schedule backups using cron or Windows Task Scheduler.

49.7 Verifying Backups
-- Test backup files by restoring to a test server.

49.8 Backup Compression
mysqldump mydb | gzip > mydb_backup.sql.gz

49.9 Offsite Backups
-- Store backups offsite or in cloud storage for disaster recovery.

49.10 Best Practices
Maintain backup schedules, keep multiple copies, and document recovery procedures.

50.1 Understanding Query Execution Plans
EXPLAIN SELECT * FROM employees WHERE age > 30;

50.2 Using Indexes Effectively
CREATE INDEX idx_age ON employees(age);

50.3 Optimizing Joins
-- Use appropriate indexes and join types.

50.4 Analyzing Slow Queries
SET GLOBAL slow_query_log = ON;

50.5 Adjusting MySQL Configuration
-- Tune parameters like innodb_buffer_pool_size, query_cache_size.

50.6 Caching Strategies
-- Use query cache and external caches like Redis or Memcached.

50.7 Partitioning for Performance
-- Divide large tables into partitions for faster access.

50.8 Using Stored Procedures
-- Reduce network overhead by using server-side code.

50.9 Monitoring Performance Metrics
SHOW GLOBAL STATUS;

50.10 Best Practices
Continuously monitor, profile queries, and adjust indexes.

51.1 Using Strong Passwords
ALTER USER 'root'@'localhost' IDENTIFIED BY 'StrongP@ssw0rd!';

51.2 Limiting User Privileges
GRANT SELECT ON mydb.* TO 'readonly'@'localhost';

51.3 Using SSL Connections
-- Configure MySQL for SSL encrypted connections.

51.4 Auditing Database Access
-- Enable audit plugins to log user activity.

51.5 Protecting Against SQL Injection
-- Use prepared statements in application code.

51.6 Updating MySQL Regularly
-- Keep MySQL server updated to patch security vulnerabilities.

51.7 Disabling Remote Root Access
UPDATE mysql.user SET Host='localhost' WHERE User='root' AND Host='%'; FLUSH PRIVILEGES;

51.8 Using Firewalls
-- Restrict MySQL port access with firewall rules.

51.9 Encrypting Data at Rest
-- Use InnoDB tablespace encryption.

51.10 Best Practices Summary
Regularly review security settings and monitor access logs.

52.1 What is JSON Data Type?
-- Stores JSON documents efficiently.

52.2 Creating Tables with JSON Columns
CREATE TABLE products (
  id INT,
  attributes JSON
);

52.3 Inserting JSON Data
INSERT INTO products (id, attributes) VALUES
(1, '{"color": "red", "size": "M"}');

52.4 Querying JSON Data
SELECT attributes->>'$.color' AS color FROM products;

52.5 Updating JSON Data
UPDATE products SET attributes = JSON_SET(attributes, '$.size', 'L') WHERE id = 1;

52.6 Indexing JSON Columns
CREATE INDEX idx_color ON products ((CAST(attributes->>'$.color' AS CHAR(20))));

52.7 Validating JSON Data
SELECT JSON_VALID(attributes) FROM products;

52.8 JSON Functions
SELECT JSON_EXTRACT(attributes, '$.size') FROM products;

52.9 Storing Complex JSON Objects
-- Nested JSON with arrays and objects.

52.10 Best Practices
Use JSON for flexible schemas but consider performance impacts.

53.1 What is Full-Text Search?
-- Search text-based data efficiently.

53.2 Creating Full-Text Index
CREATE FULLTEXT INDEX idx_content ON articles(content);

53.3 Basic Full-Text Query
SELECT * FROM articles WHERE MATCH(content) AGAINST('database');

53.4 Boolean Mode Search
SELECT * FROM articles WHERE MATCH(content) AGAINST('+database -mysql' IN BOOLEAN MODE);

53.5 Natural Language Mode
SELECT * FROM articles WHERE MATCH(content) AGAINST('database');

53.6 Limitations
-- Minimum word length, stopwords, and indexing delays.

53.7 Using WITH QUERY EXPANSION
SELECT * FROM articles WHERE MATCH(content) AGAINST('database' WITH QUERY EXPANSION);

53.8 Rebuilding Full-Text Index
ALTER TABLE articles DROP INDEX idx_content, ADD FULLTEXT INDEX idx_content(content);

53.9 Integrating with Applications
-- Use full-text search for efficient text search features.

53.10 Best Practices
Use appropriate indexes and be aware of limitations.

54.1 What is Replication?
-- Copying data from one MySQL server (master) to another (slave).

54.2 Setting up Master Server
-- Configure my.cnf with server-id and binary logging.

54.3 Setting up Slave Server
CHANGE MASTER TO MASTER_HOST='master_ip', MASTER_USER='replica', MASTER_PASSWORD='password', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=  4;

54.4 Starting Replication
START SLAVE;

54.5 Monitoring Replication Status
SHOW SLAVE STATUS\G;

54.6 Stopping Replication
STOP SLAVE;

54.7 Handling Replication Errors
-- Use SQL_THREAD or IO_THREAD status to troubleshoot.

54.8 Replication Types
-- Statement-based, row-based, mixed replication.

54.9 Using GTIDs
-- Global Transaction Identifiers simplify failover.

54.10 Best Practices
Ensure network reliability and monitor lag regularly.

55.1 What is Partitioning?
-- Dividing large tables into smaller, manageable pieces.

55.2 Types of Partitioning
-- RANGE, LIST, HASH, KEY partitioning methods.

55.3 Creating a Range Partitioned Table
CREATE TABLE sales (
  id INT,
  sale_date DATE,
  amount DECIMAL(10,2)
)
PARTITION BY RANGE (YEAR(sale_date)) (
  PARTITION p0 VALUES LESS THAN (2020),
  PARTITION p1 VALUES LESS THAN (2021),
  PARTITION p2 VALUES LESS THAN MAXVALUE
);

55.4 Querying Partitioned Tables
SELECT * FROM sales WHERE sale_date BETWEEN '2019-01-01' AND '2020-12-31';

55.5 Adding Partitions
ALTER TABLE sales ADD PARTITION (
  PARTITION p3 VALUES LESS THAN (2023)
);

55.6 Dropping Partitions
ALTER TABLE sales DROP PARTITION p0;

55.7 Benefits of Partitioning
-- Improves query performance and maintenance.

55.8 Limitations
-- Not supported on all storage engines and for all queries.

55.9 Monitoring Partitions
SHOW CREATE TABLE sales;

55.10 Best Practices
Choose partition keys wisely based on query patterns.

56.1 Creating a Stored Procedure
DELIMITER //
CREATE PROCEDURE GetEmployeeCount()
BEGIN
  SELECT COUNT(*) FROM employees;
END;
//
DELIMITER ;

56.2 Calling a Stored Procedure
CALL GetEmployeeCount();

56.3 Stored Procedure with Parameters
DELIMITER //
CREATE PROCEDURE GetEmployeesByDept(IN dept_id INT)
BEGIN
  SELECT * FROM employees WHERE department_id = dept_id;
END;
//
DELIMITER ;

56.4 Using OUT Parameters
DELIMITER //
CREATE PROCEDURE GetTotalSalary(OUT total DECIMAL(10,2))
BEGIN
  SELECT SUM(salary) INTO total FROM employees;
END;
//
DELIMITER ;

56.5 Dropping a Stored Procedure
DROP PROCEDURE GetEmployeeCount;

56.6 Handling Errors in Procedures
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
  -- Error handling code
END;

56.7 Using Variables in Procedures
DECLARE emp_count INT;
SELECT COUNT(*) INTO emp_count FROM employees;

56.8 Looping in Procedures
DECLARE i INT DEFAULT 0;
WHILE i < 10 DO
  -- loop body
  SET i = i + 1;
END WHILE;

56.9 Procedure Security
-- Use SQL SECURITY DEFINER or INVOKER as needed.

56.10 Best Practices
Keep procedures simple, document well, and handle exceptions.

57.1 Creating Complex Views
CREATE VIEW emp_sales AS
SELECT e.name, s.amount, s.sale_date
FROM employees e
JOIN sales s ON e.id = s.employee_id;

57.2 Updatable Views Restrictions
-- Views with joins may not be updatable.

57.3 Using WITH CHECK OPTION
CREATE VIEW active_employees AS
SELECT * FROM employees WHERE status = 'active'
WITH CHECK OPTION;

57.4 Indexing Views
-- MySQL does not support indexed views (materialized views).

57.5 Dropping Views Safely
DROP VIEW IF EXISTS emp_sales;

57.6 Using Views for Security
GRANT SELECT ON active_employees TO 'readonly'@'localhost';

57.7 Performance Considerations
-- Views execute underlying queries each time they are called.

57.8 Combining Views and Stored Procedures
-- Use procedures to encapsulate complex logic with views.

57.9 Nested Views
CREATE VIEW nested_view AS SELECT * FROM emp_sales;

57.10 Best Practices
Keep views simple and test performance impacts.

58.1 What is an Index?
-- Data structure to speed up data retrieval.

58.2 Creating Indexes
CREATE INDEX idx_name ON employees(name);

58.3 Unique Indexes
CREATE UNIQUE INDEX idx_email ON employees(email);

58.4 Composite Indexes
CREATE INDEX idx_name_age ON employees(name, age);

58.5 Dropping Indexes
DROP INDEX idx_name ON employees;

58.6 Indexes on Foreign Keys
-- Often automatically created for foreign keys.

58.7 Using EXPLAIN to Analyze Index Usage
EXPLAIN SELECT * FROM employees WHERE name = 'John';

58.8 When Not to Use Indexes
-- Avoid on small tables or columns with low cardinality.

58.9 Maintaining Indexes
OPTIMIZE TABLE employees;

58.10 Best Practices
Create indexes based on query patterns and monitor performance.

59.1 Starting a Transaction
START TRANSACTION;

59.2 Committing a Transaction
COMMIT;

59.3 Rolling Back a Transaction
ROLLBACK;

59.4 Savepoints
SAVEPOINT savepoint1;

59.5 Releasing Savepoints
RELEASE SAVEPOINT savepoint1;

59.6 Locking Tables
LOCK TABLES employees WRITE;

59.7 Unlocking Tables
UNLOCK TABLES;

59.8 Row-Level Locking
-- InnoDB supports row-level locking automatically.

59.9 Deadlocks
-- Detect and resolve deadlocks with proper transaction design.

59.10 Best Practices
Keep transactions short and handle errors carefully.

60.1 Full Database Backup with mysqldump
mysqldump -u root -p mydatabase > backup.sql

60.2 Incremental Backup Using Binary Logs
mysqlbinlog mysql-bin.000001 > incremental_backup.sql

60.3 Automating Backups with Cron
0 2 * * * /usr/bin/mysqldump -u root -p mydatabase > /backups/backup.sql

60.4 Compressing Backups
mysqldump -u root -p mydatabase | gzip > backup.sql.gz

60.5 Restoring a Backup
mysql -u root -p mydatabase < backup.sql

60.6 Using Percona XtraBackup
-- Physical hot backup tool for MySQL.

60.7 Backup Retention Policies
-- Keep backups for a defined period and clean old files.

60.8 Verifying Backup Integrity
-- Test restoring backups on a separate server.

60.9 Storing Backups Offsite
-- Use cloud storage or remote servers for disaster recovery.

60.10 Best Practices
Regularly schedule, verify, and document your backup processes.