You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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;
Select distinct rows
SELECT DISTINCT location FROM users;
Between (select inclusive range)
SELECT*FROM users WHERE age BETWEEN 20AND25;
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');
New table with foreign key (posts)
CREATETABLEposts (
id INT AUTO_INCREMENT,
user_id INT,
title VARCHAR(100),
body TEXT,
publish_date DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES users(id)
);
Add data to posts table
INSERT INTO posts (user_id, title, body) VALUES (1, 'Post One', 'This is post one'), (3, 'Post Two', 'This is post two'), (1, 'Post Three', 'This is post three'), (2, 'Post Four', 'This is post four'), (5, 'Post Five', 'This is post five'), (4, 'Post Six', 'This is post six'), (2, 'Post Seven', 'This is post seven'), (1, 'Post Eight', 'This is post eight'), (3, 'Post Nine', 'This is post none'), (4, 'Post Ten', 'This is post ten');
CREATETABLEcomments (
id INT AUTO_INCREMENT,
post_id INT,
user_id INT,
body TEXT,
publish_date DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (post_id) REFERENCES posts(id)
);
Add data to comments table
INSERT INTO comments (post_id, user_id, body) VALUES (1, 3, 'This is comment one'), (2, 1, 'This is comment two'), (5, 3, 'This is comment three'), (2, 4, 'This is comment four'), (1, 2, 'This is comment five'), (3, 1, 'This is comment six'), (3, 2, 'This is comment six'), (5, 4, 'This is comment seven'), (2, 3, 'This is comment seven');
Left join
SELECTcomments.body,
posts.titleFROM comments
LEFT JOIN posts ONposts.id=comments.post_idORDER BYposts.title;
Join multiple tables
SELECTc.body,
p.title,
u.first_name,
u.last_nameFROM comments c
JOIN posts p onp.id=c.post_idJOIN users u onu.id=c.user_idORDER BYp.title;
Aggregate functions
SELECTCOUNT(id) FROM users;
SELECTMAX(age) FROM users;
SELECTMIN(age) FROM users;
SELECTSUM(age) FROM users;
SELECTUPPER(first_name), LOWER(last_name) FROM users;
Group by
SELECT age, COUNT(age) FROM users GROUP BY age;
SELECT age, COUNT(age) FROM users WHERE age >20GROUP BY age;
SELECT age, COUNT(age) FROM users GROUP BY age HAVINGcount(age) >=2;
Import / export database
mysql -u user -p database < database_import.sql
mysqldump -u user -p database > database_export.sql