MySQL Cheat Sheet

Here’s a cheat sheet for MySQL, a popular relational database management system:

Basic Commands

Login to MySQL:

mysql -u username -p

Show Databases:

SHOW DATABASES;

Use a Database:

USE database_name;

Table Operations

Show Tables:

SHOW TABLES;

Create Table:

CREATE TABLE table_name (
  column1 datatype,
  column2 datatype,
  ...
);

Describe Table:

DESCRIBE table_name;

Insert Data:

INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);

Update Data:

UPDATE table_name SET column1 = value1 WHERE condition;

Delete Data:

DELETE FROM table_name WHERE condition;

Querying Data

Select All Records:

SELECT * FROM table_name;

Select Specific Columns:

SELECT column1, column2 FROM table_name;

Filter Records:

SELECT * FROM table_name WHERE condition;

Sort Records:

SELECT * FROM table_name ORDER BY column1 [ASC|DESC];

Limit Records:

SELECT * FROM table_name LIMIT count;

Aggregate Functions

Count Records:

SELECT COUNT(*) FROM table_name;

Sum Values:

SELECT SUM(column) FROM table_name;

Average Value:

SELECT AVG(column) FROM table_name;

Maximum Value:

SELECT MAX(column) FROM table_name;

Minimum Value:

SELECT MIN(column) FROM table_name;

Joins

Inner Join:

SELECT * FROM table1 INNER JOIN table2 ON table1.column = table2.column;

Left Join:

SELECT * FROM table1 LEFT JOIN table2 ON table1.column = table2.column;

Right Join:

SELECT * FROM table1 RIGHT JOIN table2 ON table1.column = table2.column;

Indexing

Create Index:

CREATE INDEX index_name ON table_name (column1, column2, ...);

Drop Index:

DROP INDEX index_name ON table_name;

Users and Privileges

Create User:

CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';

Grant Privileges:

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

Revoke Privileges:

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

Flush Privileges:

FLUSH PRIVILEGES;

Backup and Restore

Backup Database:

mysqldump -u username -p database_name > backup.sql

Restore Database:

mysql -u username -p database_name < backup.sql

This MySQL cheat sheet covers some fundamental commands and operations. Adjust commands based on your specific use case and MySQL version.