MySQL DML Cheat Sheet¶
Data Manipulation Language (DML) is used to manage data within tables: querying, inserting, updating, and deleting records.
SELECT¶
-- all columns
SELECT * FROM table;
SELECT * FROM table1, table2;
-- specific columns
SELECT field1, field2 FROM table1, table2;
-- basic select
SELECT ... FROM ... WHERE condition
SELECT ... FROM ... WHERE condition GROUP BY field;
SELECT ... FROM ... WHERE condition GROUP BY field HAVING condition2;
SELECT ... FROM ... WHERE condition ORDER BY field1, field2;
SELECT ... FROM ... WHERE condition ORDER BY field1, field2 DESC;
SELECT ... FROM ... WHERE condition LIMIT 10;
-- distinct values
SELECT DISTINCT field1 FROM table;
SELECT DISTINCT field1 FROM ...
SELECT DISTINCT field1, field2 FROM ...
Basic Select¶
All Columns¶
Aliases¶
WHERE Clause¶
Logical Operators¶
WHERE age > 25 AND city = 'London';
WHERE status = 'active' OR status = 'pending';
WHERE NOT gender = 'M';
ORDER BY¶
LIMIT¶
IN, BETWEEN, LIKE¶
INSERT¶
Single Row¶
Multiple Rows¶
Insert From Another Table¶
UPDATE¶
Basic Update¶
Multiple Columns¶
⚠️ Always use a
WHEREclause unless you're updating every row.
DELETE¶
Delete Rows¶
Delete All Rows¶
⚠️ This keeps the table structure but removes all records.
TIPS¶
NULL Handling¶
Conditional Expressions¶
Aggregate Functions¶
GROUP BY and HAVING¶
JOINs¶
-- INNER JOIN
SELECT a.col, b.col
FROM table_a a
JOIN table_b b ON a.id = b.a_id;
-- LEFT JOIN
SELECT *
FROM users u
LEFT JOIN orders o ON u.id = o.user_id;
Safe Practices¶
- always BACK UP before mass updates/deletes
- use
WHERE+LIMITwhen testing destructive operations - use transactions for multiple related DML operations