My simple library

..of useful code



Chapters

MySQL Cheat Sheet

Basics

Connect to MySQL
mysql -u username -p
Show databases
SHOW DATABASES;
Select a database
USE database_name;
Show tables in a database
SHOW TABLES;
Describe table structure
DESCRIBE table_name;
Show MySQL version
SELECT VERSION();

Database Management

Create a new database
CREATE DATABASE database_name;
Delete a database
DROP DATABASE database_name;

Table Management

Create a table
CREATE TABLE table_name (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    age INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Delete a table
DROP TABLE table_name;
Alter a table (add column)
ALTER TABLE table_name ADD column_name VARCHAR(255);
Alter a table (modify column)
ALTER TABLE table_name MODIFY column_name INT NOT NULL;
Delete a column
ALTER TABLE table_name DROP COLUMN column_name;

CRUD Operations

Insert Data
INSERT INTO table_name (name, age) VALUES ('Alice', 25);

Select Data

Select all columns
SELECT * FROM table_name;
Select specific columns
SELECT name, age FROM table_name;
Filter results
SELECT * FROM table_name WHERE age > 20;
Sort results
SELECT * FROM table_name ORDER BY age DESC;
Limit results
SELECT * FROM table_name LIMIT 5;
Update Data
UPDATE table_name SET age = 26 WHERE name = 'Alice';
Delete Data
DELETE FROM table_name WHERE name = 'Alice';

Joins

Inner Join
SELECT users.name, orders.amount FROM users
INNER JOIN orders ON users.id = orders.user_id;
Left Join
SELECT users.name, orders.amount FROM users
LEFT JOIN orders ON users.id = orders.user_id;
Right Join
SELECT users.name, orders.amount FROM users
RIGHT JOIN orders ON users.id = orders.user_id;

Indexing

Create an index
CREATE INDEX index_name ON table_name(column_name);
Delete an index
DROP INDEX index_name ON table_name;

Transactions

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

User Management

Create a new user
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
Grant privileges
GRANT ALL PRIVILEGES ON database_name.* TO 'newuser'@'localhost';
Revoke privileges
REVOKE ALL PRIVILEGES ON database_name.* FROM 'newuser'@'localhost';
Delete a user
DROP USER 'newuser'@'localhost';

Backup and Restore

Backup a database
mysqldump -u username -p database_name > backup.sql
Restore a database
mysql -u username -p database_name < backup.sql

Command Structure

COMMAND target_clause condition_clause;

Breakdown:

  • COMMAND – Specifies the operation (e.g., SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, etc.)
  • target_clause – Defines what the command acts upon (e.g., table name, column names)
  • condition_clause (optional) – Adds constraints or filters using WHERE, ORDER BY, LIMIT, etc.

Server Configuration

Show server variables
SHOW VARIABLES LIKE 'max_connections';
Set server variable
SET GLOBAL max_connections = 200;