MySQL Topics Documentation

MYSQL

Learn SQL and relational database concepts using MySQL to
structure and manage tabular data.

Introduction to MySQL

1. What is MySQL?

MySQL is an open-source Relational Database Management System (RDBMS) based on Structured Query Language (SQL). It is used for storing and managing data using tables, rows, and columns.

2. Installing MySQL

You can install MySQL on Windows, Mac, or Linux using the official installer or a package manager. Common tools: XAMPP, WAMP, or MySQL Workbench.

3. Connecting to MySQL

Use the MySQL client to connect:

mysql -u root -p
4. Creating a Database

Use the CREATE DATABASE command to create a new database.

CREATE DATABASE college;
5. Using a Database

Switch to a database using USE:

USE college;
6. Creating a Table

Use CREATE TABLE to define table structure.

CREATE TABLE students (
  id INT PRIMARY KEY,
  name VARCHAR(50),
  age INT,
  email VARCHAR(100)
);
7. Inserting Data

Insert a record using INSERT INTO:

INSERT INTO students VALUES (1, 'Alice', 20, 'alice@example.com');
8. Selecting Data

Retrieve records with SELECT:

SELECT * FROM students;
9. WHERE Clause

Filter results with the WHERE clause:

SELECT * FROM students WHERE age > 18;
10. Updating Records

Use UPDATE to modify data:

UPDATE students SET age = 21 WHERE id = 1;

MySQL Basics Continued

11. Deleting Records

Use DELETE to remove data from a table.

DELETE FROM students WHERE id = 1;
12. ORDER BY Clause

Sort results in ascending or descending order using ORDER BY.

SELECT * FROM students ORDER BY age ASC;
SELECT * FROM students ORDER BY name DESC;
13. LIMIT Clause

Use LIMIT to restrict the number of rows returned.

SELECT * FROM students LIMIT 5;
14. LIKE Operator (Pattern Matching)

Search for a pattern using LIKE.

SELECT * FROM students WHERE name LIKE 'A%';
SELECT * FROM students WHERE email LIKE '%@gmail.com';
15. Aggregate Functions

Used to perform calculations on a set of values.

SELECT COUNT(*) FROM students;
SELECT AVG(age) FROM students;
SELECT MAX(age), MIN(age) FROM students;
16. GROUP BY Clause

Group rows that have the same values into summary rows.

SELECT age, COUNT(*) FROM students GROUP BY age;
17. HAVING Clause

HAVING is used to filter the results of GROUP BY.

SELECT age, COUNT(*) FROM students GROUP BY age HAVING COUNT(*) > 1;
18. Aliases (AS)

Give temporary names to columns or tables using AS.

SELECT name AS 'Student Name', age AS 'Student Age' FROM students;
19. DISTINCT Keyword

Return only distinct (different) values.

SELECT DISTINCT age FROM students;
20. BETWEEN Operator

Find values within a range.

SELECT * FROM students WHERE age BETWEEN 18 AND 25;

MySQL Joins and Constraints

21. INNER JOIN

Returns records with matching values in both tables.

SELECT students.name, courses.course_name
FROM students
INNER JOIN courses ON students.course_id = courses.id;
22. LEFT JOIN

Returns all records from the left table and matched records from the right.

SELECT students.name, courses.course_name
FROM students
LEFT JOIN courses ON students.course_id = courses.id;
23. RIGHT JOIN

Returns all records from the right table and matched ones from the left.

SELECT students.name, courses.course_name
FROM students
RIGHT JOIN courses ON students.course_id = courses.id;
24. FULL OUTER JOIN (Simulated)

MySQL doesn’t support full outer join directly. Use UNION of LEFT and RIGHT joins.

SELECT * FROM A LEFT JOIN B ON A.id = B.id
UNION
SELECT * FROM A RIGHT JOIN B ON A.id = B.id;
25. PRIMARY KEY Constraint

Uniquely identifies each record in a table.

CREATE TABLE students (
  id INT PRIMARY KEY,
  name VARCHAR(50)
);
26. FOREIGN KEY Constraint

Links two tables by a common field.

CREATE TABLE orders (
  order_id INT PRIMARY KEY,
  student_id INT,
  FOREIGN KEY (student_id) REFERENCES students(id)
);
27. UNIQUE Constraint

Ensures all values in a column are different.

CREATE TABLE users (
  id INT,
  email VARCHAR(100) UNIQUE
);
28. NOT NULL Constraint

Ensures a column cannot have NULL values.

CREATE TABLE students (
  id INT,
  name VARCHAR(50) NOT NULL
);
29. DEFAULT Constraint

Provides a default value for a column when none is specified.

CREATE TABLE products (
  id INT,
  status VARCHAR(10) DEFAULT 'active'
);
30. CHECK Constraint

Ensures a column’s value satisfies a specific condition.

CREATE TABLE students (
  id INT,
  age INT CHECK (age >= 18)
);

MySQL Views, Indexes, and Transactions

31. Views

A view is a virtual table based on a SQL query. It does not store data but fetches results dynamically.

CREATE VIEW student_names AS
SELECT name, age FROM students;

SELECT * FROM student_names;
32. Indexes

Indexes improve the speed of data retrieval operations on a table.

CREATE INDEX idx_name ON students(name);
DROP INDEX idx_name ON students;
33. Stored Procedure

A stored procedure is a set of SQL statements saved to be reused.

DELIMITER //
CREATE PROCEDURE GetAllStudents()
BEGIN
  SELECT * FROM students;
END //
DELIMITER ;

CALL GetAllStudents();
34. Stored Function

Returns a value and can be used in SQL expressions.

DELIMITER //
CREATE FUNCTION Square(num INT) RETURNS INT
RETURN num * num; //
DELIMITER ;

SELECT Square(5);
35. Triggers

A trigger is a function that is automatically invoked before or after a specific event (INSERT, UPDATE, DELETE).

CREATE TRIGGER before_insert_student
BEFORE INSERT ON students
FOR EACH ROW
SET NEW.name = UPPER(NEW.name);
36. Transactions

A transaction is a group of SQL statements that are executed together to ensure data integrity.

START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
37. ROLLBACK

Used to undo transactions that are not yet committed.

START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
ROLLBACK;
38. COMMIT

Used to permanently save a transaction in the database.

START TRANSACTION;
UPDATE students SET age = age + 1;
COMMIT;
39. AUTO_INCREMENT

Automatically generates a unique number when a new record is inserted.

CREATE TABLE employees (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100)
);
40. ENUM and SET Data Types

ENUM allows a field to be one of several predefined values. SET allows multiple values.

CREATE TABLE user_roles (
  role ENUM('Admin', 'Editor', 'Viewer'),
  access SET('Read', 'Write', 'Delete')
);

MySQL Advanced and Administrative Topics

41. Backup Database (mysqldump)

Use the mysqldump command-line utility to back up your database into a .sql file.

mysqldump -u root -p college > college_backup.sql
42. Restore Database

Use the mysql client to restore a backup file into an existing database.

mysql -u root -p college < college_backup.sql
43. Create User

To create a new MySQL user:

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
44. Grant Privileges

Grant permissions to a user on a database or table.

GRANT ALL PRIVILEGES ON college.* TO 'newuser'@'localhost';
45. Revoke Privileges

Remove specific privileges from a user.

REVOKE SELECT, INSERT ON college.* FROM 'newuser'@'localhost';
46. Export Data (SELECT INTO OUTFILE)

Export table data to a CSV or text file.

SELECT * FROM students
INTO OUTFILE '/tmp/students.csv'
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';
47. Import CSV File

Import a CSV file into a table.

LOAD DATA INFILE '/tmp/students.csv'
INTO TABLE students
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';
48. CASE Statement

CASE is used for conditional logic in SQL queries (like IF...ELSE).

SELECT name,
  CASE
    WHEN age >= 18 THEN 'Adult'
    ELSE 'Minor'
  END AS status
FROM students;
49. DATE and TIME Functions

Useful for querying, formatting, and manipulating dates.

SELECT CURDATE(), NOW(), YEAR(NOW()), MONTH(NOW());
SELECT DATEDIFF('2025-12-31', '2025-01-01');
50. Information Schema

MySQL’s metadata tables used to get database/table/column information.

SELECT table_name FROM information_schema.tables
WHERE table_schema = 'college';

Reference Links for MySQL

Official MySQL Documentation

Comprehensive and authoritative reference for all MySQL features.

https://dev.mysql.com/doc/

W3Schools MySQL Tutorial

Beginner-friendly guide with interactive examples.

https://www.w3schools.com/mysql/

GeeksforGeeks MySQL Guide

Explanations, examples, and use-cases for developers and students.

https://www.geeksforgeeks.org/mysql-tutorial/

TutorialsPoint MySQL

Step-by-step MySQL tutorials and exercises.

https://www.tutorialspoint.com/mysql/index.htm

MySQL Functions Reference (SQL Fiddle)

Useful for trying SQL queries online and understanding function behavior.

https://sqlfiddle.com/