Post

MySQL Cheat Sheet

MySQL is one of the most popular relational database management systems (RDBMS) in the world. Whether you’re just starting out or you’re a seasoned developer, this cheat sheet will help you navigate MySQL more efficiently. This guide covers a broad spectrum of MySQL commands, functions, and tips that are essential for day-to-day database management.

Basic MySQL Commands

Create a Database

1
CREATE DATABASE db_name;

Select a Database

1
USE db_name;

Show Databases

1
SHOW DATABASES;

Drop a Database

1
DROP DATABASE db_name;

Show Tables in a Database

1
SHOW TABLES;

Describe the Structure of a Table

1
DESCRIBE tableName;

Table Operations

Create a Table

1
2
3
4
5
6
CREATE TABLE tableName (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100),
    age INT,
    email VARCHAR(100)
);

Show the Table Schema

1
SHOW CREATE TABLE tableName;

Drop a Table

1
DROP TABLE tableName;

Rename a Table

1
RENAME TABLE old_tableName TO newTableName;

Alter a Table

  • Add a column:

    1
    
    ALTER TABLE tableName ADD COLUMN columnName data_type;
    
  • Rename a column:

    1
    
    ALTER TABLE tableName RENAME COLUMN oldcolumnName TO newcolumnName;
    
  • Modify a column:

    1
    
    ALTER TABLE tableName MODIFY COLUMN columnName new_data_type;
    
  • Drop a column:

    1
    
    ALTER TABLE tableName DROP COLUMN columnName;
    

Truncate a Table

1
TRUNCATE TABLE tableName;

CRUD Operations

create, read, update and delete.

Insert Data

1
INSERT INTO tableName (column1, column2, column3) VALUES (value1, value2, value3);

Insert Multiple Rows

1
2
3
4
INSERT INTO tableName (column1, column2) VALUES 
(value1_1, value2_1),
(value1_2, value2_2),
(value1_3, value2_3);

Select Data

  • Select all columns:

    1
    
    SELECT * FROM tableName;
    
  • Select specific columns:

    1
    
    SELECT column1, column2 FROM tableName;
    

Update Data

1
UPDATE tableName SET column1 = value1, column2 = value2 WHERE condition;

Delete Data

1
DELETE FROM tableName WHERE condition;

Querying Data

WHERE Clause

1
SELECT * FROM tableName WHERE columnName = value;

AND, OR, NOT

1
SELECT * FROM tableName WHERE column1 = value1 AND (column2 = value2 OR column3 = value3);

ORDER BY Clause

1
2
SELECT * FROM tableName ORDER BY columnName ASC;
SELECT * FROM tableName ORDER BY columnName DESC;

LIMIT Clause

1
SELECT * FROM tableName LIMIT number_of_rows;

BETWEEN Clause

1
SELECT * FROM tableName WHERE columnName BETWEEN value1 AND value2;

LIKE and Wildcards

  • Find values that start with ‘a’:

    1
    
    SELECT * FROM tableName WHERE columnName LIKE 'a%';
    
  • Find values that end with ‘a’:

    1
    
    SELECT * FROM tableName WHERE columnName LIKE '%a';
    
  • Find values that contain ‘a’:

    1
    
    SELECT * FROM tableName WHERE columnName LIKE '%a%';
    

IN Clause

1
SELECT * FROM tableName WHERE columnName IN (value1, value2, value3);

DISTINCT Clause

1
SELECT DISTINCT columnName FROM tableName;

Advanced MySQL Queries

JOINS

  • Inner Join:

    1
    2
    
    SELECT columns FROM table1
    INNER JOIN table2 ON table1.column = table2.column;
    
  • Left Join:

    1
    2
    
    SELECT columns FROM table1
    LEFT JOIN table2 ON table1.column = table2.column;
    
  • Right Join:

    1
    2
    
    SELECT columns FROM table1
    RIGHT JOIN table2 ON table1.column = table2.column;
    

GROUP BY

1
2
SELECT columnName, COUNT(*) FROM tableName
GROUP BY columnName;

HAVING Clause

1
2
3
SELECT columnName, COUNT(*) FROM tableName
GROUP BY columnName
HAVING COUNT(*) > 1;

Subqueries

  • Subquery in SELECT:

    1
    2
    
    SELECT columnName, (SELECT COUNT(*) FROM another_table WHERE condition) 
    FROM tableName;
    
  • Subquery in WHERE:

    1
    2
    
    SELECT columnName FROM tableName
    WHERE columnName IN (SELECT columnName FROM another_table WHERE condition);
    

UNION

1
2
3
SELECT columnName FROM table1
UNION
SELECT columnName FROM table2;

Indexes and Keys

Create an Index

1
CREATE INDEX index_name ON tableName (columnName);

Drop an Index

1
DROP INDEX index_name ON tableName;

Unique Index

1
CREATE UNIQUE INDEX index_name ON tableName (columnName);

Primary Key

1
ALTER TABLE tableName ADD PRIMARY KEY (columnName);

Foreign Key

1
2
ALTER TABLE tableName
ADD CONSTRAINT fk_name FOREIGN KEY (columnName) REFERENCES other_table(columnName);

Transactions

Start a Transaction

1
START TRANSACTION;

Commit a Transaction

1
COMMIT;

Rollback a Transaction

1
ROLLBACK;

Savepoints

1
2
SAVEPOINT savepoint_name;
ROLLBACK TO savepoint_name;

User Management and Security

Create a User

1
CREATE USER 'username'@'host' IDENTIFIED BY 'password';

Grant Privileges

1
GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'host';

Show Grants

1
SHOW GRANTS FOR 'username'@'host';

Revoke Privileges

1
REVOKE ALL PRIVILEGES ON database_name.* FROM 'username'@'host';

Drop a User

1
DROP USER 'username'@'host';

Change User Password

1
ALTER USER 'username'@'host' IDENTIFIED BY 'new_password';

Backup and Restore

Backup a Database

1
mysqldump -u username -p database_name > backup.sql

Restore a Database

1
mysql -u username -p database_name < backup.sql

Backup Specific Tables

1
mysqldump -u username -p database_name table1 table2 > backup.sql

Backup All Databases

1
mysqldump -u username -p --all-databases > all_databases_backup.sql

Optimization and Maintenance

Check Table for Errors

1
CHECK TABLE tableName;

Repair a Table

1
REPAIR TABLE tableName;

Optimize a Table

1
OPTIMIZE TABLE tableName;

Analyze a Table

1
ANALYZE TABLE tableName;

Viewing Server Status

1
SHOW STATUS;

Show Current Users

1
SELECT user, host FROM mysql.user;

MySQL Functions

String Functions

  • Concatenate Strings:

    1
    
    SELECT CONCAT('Hello', ' ', 'World!');
    
  • Length of a String:

    1
    
    SELECT LENGTH('Hello World!');
    
  • Substring:

    1
    
    SELECT SUBSTRING('Hello World!', 1, 5);
    

Date Functions

  • Current Date:

    1
    
    SELECT CURDATE();
    
  • Current Time:

    1
    
    SELECT CURTIME();
    
  • Add Date:

    1
    
    SELECT DATE_ADD('2024-08-10', INTERVAL 10 DAY);
    

Aggregate Functions

  • COUNT:

    1
    
    SELECT COUNT(*) FROM tableName;
    
  • SUM:

    1
    
    SELECT SUM(columnName)
    

    Continuing from where we left off:

1
SELECT SUM(columnName) FROM tableName;
  • AVG:

    1
    
    SELECT AVG(columnName) FROM tableName;
    
  • MIN:

    1
    
    SELECT MIN(columnName) FROM tableName;
    
  • MAX:

    1
    
    SELECT MAX(columnName) FROM tableName;
    

Stored Procedures and Functions

Creating a Stored Procedure

1
2
3
4
5
6
7
DELIMITER //
CREATE PROCEDURE procedure_name (IN param1 datatype, OUT param2 datatype)
BEGIN
    -- SQL statements
    SELECT columnName INTO param2 FROM tableName WHERE condition;
END //
DELIMITER ;

Executing a Stored Procedure

1
2
CALL procedure_name(param1, @param2);
SELECT @param2;

Dropping a Stored Procedure

1
DROP PROCEDURE procedure_name;

Creating a Stored Function

1
2
3
4
5
6
7
DELIMITER //
CREATE FUNCTION function_name (param1 datatype) RETURNS datatype
BEGIN
    -- SQL statements
    RETURN expression;
END //
DELIMITER ;

Dropping a Stored Function

1
DROP FUNCTION function_name;

Triggers

Creating a Trigger

1
2
3
4
5
6
CREATE TRIGGER trigger_name
BEFORE/AFTER INSERT/UPDATE/DELETE
ON tableName FOR EACH ROW
BEGIN
    -- SQL statements
END;

Dropping a Trigger

1
DROP TRIGGER trigger_name;

Views

Creating a View

1
2
CREATE VIEW view_name AS
SELECT columns FROM tableName WHERE condition;

Selecting from a View

1
SELECT * FROM view_name;

Dropping a View

1
DROP VIEW view_name;

Replication and High Availability

Setting Up Master-Slave Replication

  1. On the Master:
    • Edit the MySQL configuration file (usually my.cnf or my.ini):

      1
      2
      3
      
      [mysqld]
      server-id=1
      log-bin=mysql-bin
      
    • Restart the MySQL server:

      1
      
      sudo systemctl restart mysql
      
    • Grant Replication Privileges:

      1
      2
      
      GRANT REPLICATION SLAVE ON *.* TO 'replica_user'@'%' IDENTIFIED BY 'password';
      FLUSH PRIVILEGES;
      
    • Get the binary log file and position:

      1
      
      SHOW MASTER STATUS;
      
  2. On the Slave:
    • Edit the MySQL configuration file:

      1
      2
      
      [mysqld]
      server-id=2
      
    • Restart the MySQL server:

      1
      
      sudo systemctl restart mysql
      
    • Configure the Slave:

      1
      2
      3
      4
      5
      6
      
      CHANGE MASTER TO
      MASTER_HOST='master_ip',
      MASTER_USER='replica_user',
      MASTER_PASSWORD='password',
      MASTER_LOG_FILE='mysql-bin.000001',
      MASTER_LOG_POS=12345;
      
    • Start the Slave:

      1
      
      START SLAVE;
      

Checking Replication Status

1
SHOW SLAVE STATUS\G;

Stopping and Starting Replication

  • Stop the Slave:

    1
    
    STOP SLAVE;
    
  • Start the Slave:

    1
    
    START SLAVE;
    

MySQL Best Practices

Use Consistent Naming Conventions

  • Stick to lowercase letters, underscores for spaces, and singular names for tables (e.g., user, order_item).

Normalize Your Database

  • Ensure your database is normalized to at least the third normal form (3NF) to reduce redundancy and improve data integrity.

Backup Regularly

  • Set up automated backups and always test your backup recovery process.

Monitor Performance

  • Use tools like mysqltuner to monitor and optimize the performance of MySQL database.

Secure Your MySQL Installation

  • Run mysql_secure_installation after setting up MySQL to enhance security.

Index Appropriately

  • Index columns that are frequently used in WHERE, JOIN, and ORDER BY clauses, but avoid over-indexing as it can slow down INSERT, UPDATE, and DELETE operations.

Regularly Update MySQL

  • Keep MySQL version up to date with the latest security patches and performance improvements.

Conclusion

This MySQL cheat sheet provides a solid foundation for managing databases efficiently. Whether you’re working on a small project or a large-scale application, understanding these commands, functions, and best practices will help you get the most out of MySQL. Keep this guide handy as you develop and maintain your databases to ensure smooth and effective database management.

This post is licensed under CC BY 4.0 by the author.