This cheatsheet covers basic MySQL queries for common database operations.
- Select Data
- Insert Data
- Update Data
- Delete Data
- Join Tables
- Aggregate Functions
- Group By and Having
Select Data
-- Select all columns from a table
SELECT * FROM table_name;
-- Select specific columns from a table
SELECT column1, column2 FROM table_name;
-- Select with a WHERE clause
SELECT * FROM table_name WHERE condition;
-- Select with ORDER BY
SELECT * FROM table_name ORDER BY column_name [ASC|DESC];
-- Select with LIMIT
SELECT * FROM table_name LIMIT number_of_rows;
-- Select distinct values
SELECT DISTINCT column_name FROM table_name;
Insert Data
-- Insert a single row
INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3);
-- Insert multiple rows
INSERT INTO table_name (column1, column2, column3)
VALUES
(value1, value2, value3),
(value4, value5, value6),
(value7, value8, value9);
Update Data
-- Update all rows
UPDATE table_name SET column1 = value1, column2 = value2;
-- Update with a WHERE clause
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;
Delete Data
-- Delete all rows from a table
DELETE FROM table_name;
-- Delete with a WHERE clause
DELETE FROM table_name WHERE condition;
Join Tables
-- Inner Join
SELECT *
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
-- Left Join
SELECT *
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
-- Right Join
SELECT *
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;
Aggregate Functions
-- Count rows
SELECT COUNT(*) FROM table_name;
-- Sum of a column
SELECT SUM(column_name) FROM table_name;
-- Average of a column
SELECT AVG(column_name) FROM table_name;
-- Maximum value in a column
SELECT MAX(column_name) FROM table_name;
-- Minimum value in a column
SELECT MIN(column_name) FROM table_name;
Group By and Having
-- Group By
SELECT column1, COUNT(*)
FROM table_name
GROUP BY column1;
-- Group By with Having
SELECT column1, COUNT(*)
FROM table_name
GROUP BY column1
HAVING COUNT(*) > 5;