Back Back

MySQL: Relational Database Management

MySQL is an open-source relational database management system (RDBMS) widely used for managing structured data. Known for its speed, reliability, and ease of use, MySQL powers applications like WordPress, Drupal, and enterprise systems.

Origin

Developed in 1995 by MySQL AB, now maintained by Oracle.

Features

SQL compliance, ACID transactions, replication, indexing.

Applications

Web apps, e-commerce, CMS, data analytics.

Why MySQL is Good and Easy?

Did You Know?

MySQL powers major websites like Facebook, YouTube, and Twitter.

Core MySQL Queries

Data Definition Language (DDL)

Manage database structure (e.g., CREATE, ALTER, DROP).


-- Create a table
CREATE TABLE employees (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    salary DECIMAL(10,2),
    hire_date DATE
);

-- Alter table to add column
ALTER TABLE employees ADD department VARCHAR(50);

-- Drop table
DROP TABLE employees;
                    

Tip: Use DESCRIBE employees; to view table structure.

Data Manipulation Language (DML)

Manage data within tables (e.g., INSERT, UPDATE, DELETE).


-- Insert data
INSERT INTO employees (name, salary, hire_date, department)
VALUES ('John Doe', 50000.00, '2023-01-15', 'IT');

-- Update data
UPDATE employees SET salary = 55000.00 WHERE id = 1;

-- Delete data
DELETE FROM employees WHERE id = 1;

-- Select data
SELECT * FROM employees WHERE department = 'IT';
                    

Tip: Always use WHERE to avoid unintended updates/deletes.

Data Control Language (DCL)

Manage permissions (e.g., GRANT, REVOKE).


-- Grant permissions
GRANT SELECT, INSERT ON employees TO 'user'@'localhost';

-- Revoke permissions
REVOKE INSERT ON employees FROM 'user'@'localhost';
                    

Tip: Use specific permissions for security.

Transaction Control Language (TCL)

Manage transactions (e.g., COMMIT, ROLLBACK).


-- Start transaction
START TRANSACTION;

-- Insert data
INSERT INTO employees (name, salary) VALUES ('Jane Doe', 60000.00);

-- Commit transaction
COMMIT;

-- Rollback example
START TRANSACTION;
INSERT INTO employees (name, salary) VALUES ('Bob Smith', 45000.00);
ROLLBACK;
                    

Tip: Use transactions for data integrity in critical operations.

DELETE vs TRUNCATE vs DROP

Understanding the differences between DELETE, TRUNCATE, and DROP is crucial for database management.

Operation Purpose Data Structure Transaction Log Speed
DELETE Remove specific rows Removes rows (with WHERE) Preserves table structure Logged, can be rolled back Slower
TRUNCATE Remove all rows Removes all rows Preserves table structure Minimally logged Faster
DROP Remove table/database Removes all data Removes table structure Logged, can be rolled back Fastest

-- DELETE example
DELETE FROM employees WHERE id = 1;

-- TRUNCATE example
TRUNCATE TABLE employees;

-- DROP example
DROP TABLE employees;
                

Tip: Use DELETE for selective removal, TRUNCATE for clearing all data, and DROP for removing the table entirely.

Database Design and Normalization

Database Design

Plan tables, relationships, and constraints for efficient data storage.


CREATE TABLE departments (
    dept_id INT PRIMARY KEY,
    dept_name VARCHAR(50)
);

CREATE TABLE employees (
    id INT PRIMARY KEY,
    name VARCHAR(100),
    dept_id INT,
    FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
);
                    

Tip: Use ER diagrams to visualize relationships.

Normalization

Organize data to eliminate redundancy (1NF, 2NF, 3NF).


-- Before normalization (redundant data)
CREATE TABLE orders (
    order_id INT,
    customer_name VARCHAR(100),
    customer_email VARCHAR(100),
    product VARCHAR(50)
);

-- After normalization (split into tables)
CREATE TABLE customers (
    customer_id INT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100)
);

CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    product VARCHAR(50),
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
                    

Tip: Aim for 3NF for most databases to balance performance and simplicity.

Joins in MySQL

INNER JOIN

Retrieve matching records from both tables.


SELECT e.name, d.dept_name
FROM employees e
INNER JOIN departments d ON e.dept_id = d.dept_id;
                    

LEFT JOIN

Retrieve all records from the left table, matching from the right.


SELECT e.name, d.dept_name
FROM employees e
LEFT JOIN departments d ON e.dept_id = d.dept_id;
                    

RIGHT JOIN

Retrieve all records from the right table, matching from the left.


SELECT e.name, d.dept_name
FROM employees e
RIGHT JOIN departments d ON e.dept_id = d.dept_id;
                    

FULL JOIN

Retrieve all records from both tables (MySQL uses UNION).


SELECT e.name, d.dept_name
FROM employees e
LEFT JOIN departments d ON e.dept_id = d.dept_id
UNION
SELECT e.name, d.dept_name
FROM employees e
RIGHT JOIN departments d ON e.dept_id = d.dept_id;
                    

Indexing

Creating and Using Indexes

Indexes improve query performance for large datasets.


-- Create an index
CREATE INDEX idx_name ON employees(name);

-- Use in query
SELECT * FROM employees WHERE name = 'John Doe';

-- Drop index
DROP INDEX idx_name ON employees;
                

Tip: Index frequently queried columns, but avoid over-indexing to save storage.

Stored Procedures and Triggers

Stored Procedures

Reusable SQL scripts stored in the database.


DELIMITER //
CREATE PROCEDURE GetHighEarners()
BEGIN
    SELECT name, salary
    FROM employees
    WHERE salary > 50000;
END //
DELIMITER ;

-- Call procedure
CALL GetHighEarners();
                    

Triggers

Automatic actions on data changes.


DELIMITER //
CREATE TRIGGER before_employee_insert
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
    SET NEW.hire_date = CURDATE();
END //
DELIMITER ;

-- Insert triggers the action
INSERT INTO employees (name, salary, department)
VALUES ('Alice Brown', 60000.00, 'HR');
                    

Try our recommended online MySQL compiler:

Open MySQL Compiler

Download Basic MySQL Notes

View PDF Notes Download PDF Notes

Download Detailed MySQL 2 Notes

View PDF Notes Download PDF Notes

Important Questions and Answers

Test Your MySQL Knowledge

These Q&A cover key MySQL concepts for interviews and practical use.

1. What is the difference between CHAR and VARCHAR?

Answer: CHAR is fixed-length, padding with spaces (e.g., CHAR(10) always uses 10 bytes). VARCHAR is variable-length, storing only the actual data (e.g., VARCHAR(10) uses less space for shorter strings).

Example:


CREATE TABLE test (
    char_col CHAR(10),
    varchar_col VARCHAR(10)
);

INSERT INTO test VALUES ('abc', 'abc');
-- char_col: 'abc       ', varchar_col: 'abc'
                        

2. How does PRIMARY KEY differ from UNIQUE KEY?

Answer: PRIMARY KEY uniquely identifies rows, allows no NULLs, and only one per table. UNIQUE KEY ensures unique values, allows NULLs, and multiple per table.


CREATE TABLE users (
    id INT PRIMARY KEY,
    email VARCHAR(50) UNIQUE
);
                        

3. What is the purpose of GROUP BY?

Answer: GROUP BY groups rows with the same values in specified columns into summary rows, often used with aggregate functions like COUNT, SUM.


SELECT department, COUNT(*) as emp_count
FROM employees
GROUP BY department;
                        

4. What are the benefits of indexing?

Answer: Indexes speed up query performance by allowing faster data retrieval. However, they increase storage and slow down write operations (INSERT/UPDATE).


CREATE INDEX idx_salary ON employees(salary);
                        

5. How do you optimize a slow MySQL query?

Answer: Use EXPLAIN to analyze query execution, add indexes on frequently queried columns, avoid SELECT *, and optimize JOINs by ensuring proper indexing.


EXPLAIN SELECT * FROM employees WHERE salary > 50000;
                        

6. What is a foreign key, and why is it important?

Answer: A FOREIGN KEY is a field in one table that uniquely identifies a row in another table, enforcing referential integrity.


CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
                        

7. What is the difference between UNION and UNION ALL?

Answer: UNION combines result sets and removes duplicates, while UNION ALL combines result sets without removing duplicates, making it faster.


SELECT name FROM employees
UNION
SELECT name FROM contractors;
                        

8. What is a self-join, and when is it used?

Answer: A self-join joins a table with itself, useful for hierarchical data (e.g., employees and their managers).


SELECT e1.name AS employee, e2.name AS manager
FROM employees e1
LEFT JOIN employees e2 ON e1.manager_id = e2.id;
                        

MySQL Quiz

Test Your Knowledge

Answer these questions to reinforce your MySQL skills.

1. What does this query do?


SELECT department, AVG(salary)
FROM employees
GROUP BY department;
                        

Answer: Calculates average salary per department.

Explanation: GROUP BY groups rows by department, and AVG computes the average salary for each group.

2. What is wrong with this query?


DELETE FROM employees;
                        

Answer: Deletes all rows without a WHERE clause.

Explanation: Without WHERE, all data in the table is deleted, which may be unintentional.

3. What does this query return?


SELECT e.name, d.dept_name
FROM employees e
LEFT JOIN departments d ON e.dept_id = d.dept_id;
                        

Answer: All employees with their department names, including those without a department.

Explanation: LEFT JOIN includes all rows from employees, with NULL for unmatched departments.

4. What is the purpose of this statement?


CREATE INDEX idx_salary ON employees(salary);
                        

Answer: Creates an index to speed up salary-based queries.

Explanation: Indexes improve performance for WHERE and ORDER BY clauses on the salary column.

5. What does this trigger do?


CREATE TRIGGER update_timestamp
BEFORE UPDATE ON employees
FOR EACH ROW
SET NEW.last_updated = NOW();
                        

Answer: Sets last_updated to current timestamp before updating a row.

Explanation: The trigger automatically updates the last_updated column for each row modified.

6. What does this stored procedure do?


DELIMITER //
CREATE PROCEDURE GetHighEarners()
BEGIN
    SELECT name, salary
    FROM employees
    WHERE salary > 50000;
END //
DELIMITER ;
                        

Answer: Retrieves employees with salary greater than 50,000.

Explanation: The procedure encapsulates a query for reuse, improving maintainability.

7. What is the output of this query?


SELECT name
FROM employees
WHERE salary > 50000
ORDER BY salary DESC
LIMIT 1;
                        

Answer: Returns the name of the highest-paid employee with salary > 50,000.

Explanation: ORDER BY salary DESC sorts in descending order, and LIMIT 1 returns only the top result.