MySQL Comprehensive Notes
1. Introduction to MySQL
MySQL is an open-source relational database management system (RDBMS) that uses Structured
Query Language (SQL).
It is widely used for web applications and supports CRUD operations, multi-user access, and
scalability.
2. Data Types
- Numeric: INT, FLOAT, DECIMAL, etc.
- String: CHAR, VARCHAR, TEXT, etc.
- Date/Time: DATE, TIME, DATETIME, TIMESTAMP.
- Spatial: GEOMETRY, POINT, etc.
3. DDL (Data Definition Language)
Commands:
- CREATE: To create databases or tables.
- ALTER: To modify table structure.
- DROP: To delete a database or table.
Example: CREATE TABLE users (id INT, name VARCHAR(100));
4. DML (Data Manipulation Language)
Commands:
- INSERT: To add data into a table.
- UPDATE: To modify existing data.
- DELETE: To remove data.
Example: INSERT INTO users (id, name) VALUES (1, 'Alice');
5. DQL (Data Query Language)
Command:
- SELECT: Used to retrieve data.
Example: SELECT name FROM users WHERE id = 1;
6. Joins and Subqueries
- Joins combine rows from two or more tables based on related columns.
Types: INNER, LEFT, RIGHT, FULL OUTER.
Example: SELECT * FROM users u JOIN orders o ON u.id = o.user_id;
- Subqueries are queries within queries.
Example: SELECT * FROM users WHERE id = (SELECT MAX(id) FROM users);
7. Indexes
Indexes improve query performance.
Syntax: CREATE INDEX idx_name ON table_name(column_name);
Example: CREATE INDEX idx_user_name ON users(name);
8. Views
Views are virtual tables based on a SELECT query.
Syntax: CREATE VIEW view_name AS SELECT column1, column2 FROM table_name;
Example: CREATE VIEW user_orders AS SELECT u.name, o.order_id FROM users u JOIN orders
o ON u.id = o.user_id;
9. Stored Procedures and Triggers
- Stored Procedures are reusable SQL code blocks.
Example: CREATE PROCEDURE GetUser(IN userId INT) BEGIN SELECT * FROM users
WHERE id = userId; END;
- Triggers execute automatically in response to events.
Example: CREATE TRIGGER before_insert_users BEFORE INSERT ON users FOR EACH ROW
SET NEW.name = UPPER(NEW.name);
10. Foreign Keys and Constraints
Foreign Keys enforce referential integrity.
Syntax: FOREIGN KEY (column_name) REFERENCES parent_table(column_name);
Example: CREATE TABLE orders (id INT PRIMARY KEY, user_id INT, FOREIGN KEY (user_id)
REFERENCES users(id));
11. Transactions
Transactions group multiple SQL commands into a single unit of work.
Commands: START TRANSACTION, COMMIT, ROLLBACK.
Example: START TRANSACTION; UPDATE users SET balance = balance - 100 WHERE id = 1;
COMMIT;
12. Advanced Topics
- Full-Text Search: CREATE FULLTEXT INDEX idx_text ON articles(content);
- Partitioning: Allows large tables to be divided into smaller parts.
- Replication: Enables copying data across multiple servers.