MySQL 101: Everything You Need to Know
Table of Contents
- 1. Basic Concepts
- 2. Data Definition Language (DDL)
- 3. Data Manipulation Language (DML)
- 4. Data Control Language (DCL)
- 5. Advanced SQL Queries
- 6. Data Integrity and Constraints
- 7. Transactions and Concurrency
- 8. Performance Optimization
- 9. Backup and Recovery
- 10. Stored Procedures and Triggers
- 11. Database Design and Normalization
- 12. Useful MySQL Tools
- Resources
A comprehensive guide to MySQL and SQL -- from basic concepts and DDL/DML to advanced queries, data integrity, transactions, and performance optimization. SQL (Structured Query Language) is the standard language for managing and manipulating relational databases. MySQL is an open-source relational database management system that uses SQL as its query language. Together they power the majority of the web -- from WordPress blogs to Facebook-scale applications. This guide covers everything from the basics to advanced topics. Bookmark it and come back as you need each section. A Database Management System (DBMS) is software that provides a structured way to store, retrieve, and manage data. Different systems are optimised for different use cases: A relational database organises data into tables with defined relationships between them. This structure ensures data integrity, enables complex queries, and scales reliably for large datasets. SQL provides a standardised set of commands for interacting with relational databases: creating structures, inserting data, querying records, and managing access. It divides into four sublanguages: For detailed guides: Ubuntu | Windows DDL commands define and manage database structure -- tables, indexes, constraints, and schemas. DML commands manipulate the data within tables. DCL manages permissions and access rights. When a parent record is updated or deleted, cascading actions define what happens to child records: Transactions group SQL statements into a single atomic unit. MySQL supports ACID properties: Use Key things to check in EXPLAIN output: General tips: index columns used in Good database design prevents data duplication and anomalies. The normal forms: A well-normalised schema is easier to maintain and produces cleaner queries. Over-normalization can hurt read performance -- in that case, selective denormalization with good indexing is the answer.![]()
1. Basic Concepts
What is a DBMS?
DBMS Best For MySQL Web applications, CMS, e-commerce PostgreSQL GIS, scientific research, advanced SQL Oracle Enterprise finance, healthcare, manufacturing Microsoft SQL Server Enterprise BI, data warehousing MongoDB Unstructured data, IoT, real-time analytics Relational Databases
SQL -- Structured Query Language
MySQL Features
Feature Description Scalability Handles large datasets and high traffic loads Speed Fast query processing and optimised indexing Reliability ACID-compliant, stable and robust Security Encryption, user authentication, access control Replication Redundant copies for backup and fault tolerance Extensibility User-defined functions, custom types, plugins Cost Open-source and free to use Installation (Linux/Ubuntu)
# Update package lists
sudo apt update
# Install MySQL server
sudo apt install mysql-server
# Verify the service is running
sudo systemctl status mysql
# Enable on boot
sudo systemctl enable mysql
# Secure the installation
sudo mysql_secure_installation
# Access the MySQL shell
mysql -u root -p 2. Data Definition Language (DDL)
Statement Description CREATECreates a database, table, view, or index ALTERModifies an existing database object DROPDeletes a database object TRUNCATERemoves all data from a table, keeps structure RENAMERenames a database object SHOWRetrieves info about objects or server config Creating a Database and Tables
-- Create a database
CREATE DATABASE mystore;
USE mystore;
-- Products table
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(8,2) NOT NULL,
description TEXT
);
-- Orders table
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(100) NOT NULL,
order_date DATE,
total_amount DECIMAL(10,2)
); Modifying Tables
-- Add a column
ALTER TABLE products
ADD COLUMN quantity INT;
-- Modify a column type
ALTER TABLE products
MODIFY COLUMN price DECIMAL(10,2);
-- Rename a column
ALTER TABLE products
CHANGE COLUMN description product_description TEXT;
-- Drop a column
ALTER TABLE products
DROP COLUMN quantity; Constraints
-- Primary key and unique constraint
CREATE TABLE customers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE
);
-- Foreign key constraint
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT,
order_date DATE,
total_amount DECIMAL(10,2),
FOREIGN KEY (customer_id) REFERENCES customers(id)
); Index Types
Index Type Description Primary Key Unique index on the primary key column Unique Prevents duplicate values in indexed columns Clustered Determines physical order of data in the table Non-Clustered Sorted copy of columns for faster lookups Composite Index on multiple columns for combined queries Full-Text Optimised for keyword search in text columns Spatial Optimised for geographic and geometric queries 3. Data Manipulation Language (DML)
Statement Description INSERTAdds new records into a table SELECTRetrieves data from one or more tables UPDATEModifies existing records DELETERemoves records from a table TRUNCATERemoves all data, keeps table structure COMMITSaves transaction changes permanently ROLLBACKDiscards transaction changes Inserting Data
INSERT INTO products (id, name, price, description)
VALUES
(1, 'Product A', 10.99, 'This is product A'),
(2, 'Product B', 19.99, 'This is product B'),
(3, 'Product C', 5.99, 'This is product C'); Selecting Data
-- All records
SELECT * FROM products;
/*
+----+-----------+---------+-------------------+
| id | name | price | description |
+----+-----------+---------+-------------------+
| 1 | Product A | 10.9900 | This is product A |
| 2 | Product B | 19.9900 | This is product B |
| 3 | Product C | 5.9900 | This is product C |
+----+-----------+---------+-------------------+
*/
-- Filter with WHERE
SELECT name, price FROM products WHERE price < 10.00;
/*
+-----------+--------+
| name | price |
+-----------+--------+
| Product C | 5.9900 |
+-----------+--------+
*/ Updating and Deleting
-- Update a record
UPDATE products
SET price = 12.99
WHERE id = 1;
-- Delete a record
DELETE FROM products
WHERE id = 2; Sorting with ORDER BY
-- Ascending
SELECT * FROM products ORDER BY price ASC;
-- Descending
SELECT * FROM products ORDER BY price DESC;
-- Multiple columns
SELECT * FROM products ORDER BY price ASC, name DESC; Joins
Join Type Description INNER JOIN Returns only matching rows from both tables LEFT JOIN All rows from left table, matching from right RIGHT JOIN All rows from right table, matching from left FULL JOIN All rows from both tables CROSS JOIN Cartesian product of both tables SELF JOIN Table joined to itself -- INNER JOIN
SELECT *
FROM products
INNER JOIN orders ON products.id = orders.id;
-- LEFT JOIN
SELECT *
FROM products
LEFT JOIN orders ON products.id = orders.id;
-- RIGHT JOIN
SELECT *
FROM products
RIGHT JOIN orders ON products.id = orders.id;
-- FULL JOIN (MySQL doesn't support FULL JOIN directly -- use UNION)
SELECT * FROM products LEFT JOIN orders ON products.id = orders.id
UNION
SELECT * FROM products RIGHT JOIN orders ON products.id = orders.id; 4. Data Control Language (DCL)
Command Description GRANTGrants privileges to a user REVOKERemoves privileges from a user CREATE USERCreates a new user account ALTER USERModifies an existing user account DROP USERRemoves a user account SHOW GRANTSDisplays privileges for a user Managing Users
-- Create a user
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword';
-- Grant specific privileges
GRANT SELECT ON mystore.products TO 'myuser'@'localhost';
GRANT INSERT, UPDATE ON mystore.customers TO 'myuser'@'localhost';
GRANT ALL PRIVILEGES ON mystore.* TO 'myuser'@'localhost';
-- Revoke privileges
REVOKE SELECT ON mystore.products FROM 'myuser'@'localhost';
REVOKE ALL PRIVILEGES ON mystore.* FROM 'myuser'@'localhost';
-- Change password
ALTER USER 'myuser'@'localhost' IDENTIFIED BY 'newpassword';
-- View user privileges
SHOW GRANTS FOR 'myuser'@'localhost';
-- Drop user
DROP USER 'myuser'@'localhost'; 5. Advanced SQL Queries
Aggregate and Grouping
-- Total sales per customer
SELECT customer_id, SUM(amount) AS total_sales
FROM orders
GROUP BY customer_id;
-- Average salary per department
SELECT department_id, AVG(salary) AS average_salary
FROM employees
GROUP BY department_id;
-- Top 5 products by sales
SELECT product_id, SUM(quantity) AS total_sales
FROM order_details
GROUP BY product_id
ORDER BY total_sales DESC
LIMIT 5; Subqueries
-- Customers who ordered in the last 30 days
SELECT customer_id, customer_name
FROM customers
WHERE customer_id IN (
SELECT DISTINCT customer_id
FROM orders
WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
);
-- Customers with no orders
SELECT customer_id, customer_name
FROM customers
WHERE customer_id NOT IN (
SELECT DISTINCT customer_id FROM orders
); Date and Time Queries
-- Monthly revenue for 2023
SELECT MONTH(order_date) AS month, SUM(total_amount) AS revenue
FROM orders
WHERE YEAR(order_date) = 2023
GROUP BY MONTH(order_date); Window Functions
-- Cumulative sales per product over time
SELECT
order_date,
product_id,
SUM(quantity) OVER (
PARTITION BY product_id
ORDER BY order_date
) AS cumulative_sales
FROM order_details; UNION
-- Combine employee and customer names into one list
SELECT employee_name AS name FROM employees
UNION
SELECT customer_name AS name FROM customers; 6. Data Integrity and Constraints
Constraint Description PRIMARY KEY Unique, non-null identifier for each row FOREIGN KEY Enforces referential integrity between tables UNIQUE Prevents duplicate values in a column NOT NULL Prevents null values in a column CHECK Custom condition that column values must satisfy DEFAULT Fallback value when no value is provided -- Primary key
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(50) NOT NULL,
department_id INT
);
-- Foreign key
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
-- Unique constraint
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(50),
sku VARCHAR(20) UNIQUE
);
-- Check constraint
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
salary DECIMAL(10,2),
CONSTRAINT chk_salary CHECK (salary >= 0)
);
-- Default value
CREATE TABLE orders (
order_id INT PRIMARY KEY,
order_date DATE DEFAULT CURRENT_DATE
); Cascading Actions
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
FOREIGN KEY (customer_id)
REFERENCES customers(customer_id)
ON DELETE CASCADE
);
CREATE TABLE order_items (
item_id INT PRIMARY KEY,
order_id INT,
product_id INT,
quantity INT,
FOREIGN KEY (order_id)
REFERENCES orders(order_id)
ON DELETE CASCADE
); 7. Transactions and Concurrency
START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
-- All good, save changes
COMMIT;
-- Something went wrong, undo everything
ROLLBACK; Isolation Levels
Level Description READ UNCOMMITTED Can read uncommitted changes from other transactions READ COMMITTED Only reads committed changes REPEATABLE READ Same query returns same results within a transaction (MySQL default) SERIALIZABLE Full isolation, transactions run sequentially SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ; 8. Performance Optimization
Indexing Strategy
-- Add an index on a frequently queried column
CREATE INDEX idx_customer_email ON customers(email);
-- Composite index for multi-column queries
CREATE INDEX idx_order_date_customer ON orders(order_date, customer_id);
-- Check existing indexes
SHOW INDEX FROM orders;
-- Drop an unused index
DROP INDEX idx_customer_email ON customers; Query Optimization Tips
EXPLAIN to analyse how MySQL executes a query:EXPLAIN SELECT * FROM orders
WHERE customer_id = 5
ORDER BY order_date DESC;type should be ref or eq_ref not ALL (full scan), rows should be as low as possible, Extra should not show Using filesort or Using temporary if avoidable.WHERE, JOIN, and ORDER BY clauses; avoid SELECT * in production queries; use LIMIT for pagination; avoid functions on indexed columns in WHERE clauses. 9. Backup and Recovery
# Full database backup
mysqldump -u root -p mystore > mystore_backup.sql
# Backup specific table
mysqldump -u root -p mystore products > products_backup.sql
# Restore from backup
mysql -u root -p mystore < mystore_backup.sql
# Compressed backup
mysqldump -u root -p mystore | gzip > mystore_backup.sql.gz
# Restore compressed backup
gunzip < mystore_backup.sql.gz | mysql -u root -p mystore 10. Stored Procedures and Triggers
Stored Procedure
-- Procedure to get orders for a customer
DELIMITER //
CREATE PROCEDURE GetCustomerOrders(IN cust_id INT)
BEGIN
SELECT * FROM orders
WHERE customer_id = cust_id
ORDER BY order_date DESC;
END //
DELIMITER ;
-- Call it
CALL GetCustomerOrders(5); Trigger
-- Automatically set updated_at timestamp on row update
DELIMITER //
CREATE TRIGGER before_product_update
BEFORE UPDATE ON products
FOR EACH ROW
BEGIN
SET NEW.updated_at = NOW();
END //
DELIMITER ; 11. Database Design and Normalization
12. Useful MySQL Tools
Tool Purpose MySQL CLI Direct command-line access to MySQL MySQL Workbench GUI for design, querying, and administration phpMyAdmin Web-based database management interface mysqldump Command-line backup and export tool mysqlcheck Table check, repair, and optimization pt-query-digest Percona tool for query performance analysis Resources