Mysql Cheat Sheet
Mysql Cheat Sheet
Mysql Cheat Sheet
Show Tables
SHOW TABLES;
Select
SELECT * FROM users;
SELECT first_name, last_name FROM users;
Where Clause
SELECT * FROM users WHERE location='Massachusetts';
SELECT * FROM users WHERE location='Massachusetts' AND dept='sales';
SELECT * FROM users WHERE is_admin = 1;
SELECT * FROM users WHERE is_admin > 0;
Delete Row
DELETE FROM users WHERE id = 6;
Update Row
UPDATE users SET email = 'freddy@gmail.com' WHERE id = 2;
Modify Column
ALTER TABLE users MODIFY COLUMN age INT(3);
Order By (Sort)
SELECT * FROM users ORDER BY last_name ASC;
SELECT * FROM users ORDER BY last_name DESC;
Concatenate Columns
SELECT CONCAT(first_name, ' ', last_name) AS 'Name', dept FROM users;
Like (Searching)
SELECT * FROM users WHERE dept LIKE 'd%';
SELECT * FROM users WHERE dept LIKE 'dev%';
SELECT * FROM users WHERE dept LIKE '%t';
SELECT * FROM users WHERE dept LIKE '%e%';
Not Like
SELECT * FROM users WHERE dept NOT LIKE 'd%';
IN
SELECT * FROM users WHERE dept IN ('design', 'sales');
INNER JOIN
SELECT
users.first_name,
users.last_name,
posts.title,
posts.publish_date
FROM users
INNER JOIN posts
ON users.id = posts.user_id
ORDER BY posts.title;
Left Join
SELECT
comments.body,
posts.title
FROM comments
LEFT JOIN posts ON posts.id = comments.post_id
ORDER BY posts.title;
Aggregate Functions
SELECT COUNT(id) FROM users;
SELECT MAX(age) FROM users;
SELECT MIN(age) FROM users;
SELECT SUM(age) FROM users;
SELECT UCASE(first_name), LCASE(last_name) FROM users;
Group By
SELECT age, COUNT(age) FROM users GROUP BY age;
SELECT age, COUNT(age) FROM users WHERE age > 20 GROUP BY age;
SELECT age, COUNT(age) FROM users GROUP BY age HAVING count(age) >=2;