mysql Cheat sheet
CLI
Connect to MySQL
Connect: mysql -u [username] -p -h [hostname] -P [port_number] [db_name]
Exit
Exit: exit;
Clauses
Connect to MySQL
FROM > WHERE > GROUP BY > HAVING > SELECT > DISTINCT > ORDER BY > LIMIT
Data Types
TINYINT: 1 byte -128 to +127 (unsigned: from 0 to 255)
TINYINT
SMALLINT: 2 bytes -32 768 to +32 767 (unsigned: from 0 to 65 535)
SMALLINT
MEDIUMINT: 3 bytes (3o: +-16 000 000)
MEDIUMINT
INT: 4 bytes (4o: +- 2 000 000 000)
INT
BIGINT: 8 bytes (8o: +-9.10^18)
BIGINT
FLOAT(M,D): Floating-Point
FLOAT
DOUBLE(M,D): Floating-Point
DOUBLE
DECIMAL(M,D): (Fixed-Point),
DECIMAL(M,D)
Fixed-Length String, max size=255
CHAR(M)
Variable-Length String, max size=255
VARCHAR(M)
Text: max size=65535
TEXT(M)
Binary Large Object: binary; max size=65535
BLOB
Date: YYYY-MM-DD
DATE
Time: (HH:MM:SS)
TIME
Date and Time: YYYY-MM-DD HH:MM:SS
DATETIME
(YYYY)
YEAR
Timestamp: TIMESTAMP (like DATETIME, but 1970->2038, compatible with Unix
TIMESTAMP
Boolean
BOOLEAN
Enumeration
ENUM('value1', 'value2', ...)
Set of Values
SET('option1', 'option2', ...)
M: total number of digits
"M" refers to the total number of digits you want to store
N: decimal point
"N" is the number of digits to be stored after the decimal point
Database Operations
Create a Database
CREATE DATABASE database_name [CHARACTER SET utf8];
Show databases
SHOW DATABASES;
Select database
USE database_name;
Delete a database
DROP DATABASE database_name;
Alter a database
ALTER DATABASE database_name CHARACTER SET utf8;
Table Operations
Create a Table
CREATE TABLE [IF NOT EXISTS] table_name (column1 datatype COMMENT 'string', ...);
Create a Table
CREATE TEMPORARY TABLE table;
Show tables
SHOW TABLES;
Describe table
DESCRIBE table_name;
Delete a table
DROP TABLE [IF EXISTS] table_name;
Rename table
ALTER TABLE table RENAME TO new_table_name
Rename column
ALTER TABLE table RENAME col1 TO col2
Add a Column
ALTER TABLE table ADD column_name datatype;
Add a Column
ALTER TABLE table ADD column_name datatype FIRST;
Add a Column
ALTER TABLE table ADD column_name datatype AFTER another_field;
DROP colum
ALTER TABLE table DROP column_name;
Alter table
ALTER TABLE table CHANGE field1 new_field_name datatype FIRST
Alter table
ALTER TABLE table CHANGE field1 new_field_name datatype NOT NULL ..
Alter table
ALTER TABLE table ALTER field1 SET DEFAULT ...
Alter table
ALTER TABLE table ALTER field1 DROP DEFAULT;
change the data type of a column
ALTER TABLE table MODIFY field1 datatype NOT NULL ...
Alter table
ALTER TABLE table MODIFY field1 type1 FIRST;
Alter table
ALTER TABLE table MODIFY field1 type1 AFTER another_field;
Constraints Operations
Constraint
CREATE TABLE table_name ( column1 datatype constraint, ...);
Full Constraint
CREATE TABLE table_name (
column_name datatype [ UNSIGNED ] [ NULL | NOT NULL ] [DEFAULT default_value] [AUTO_INCREMENT],
...);
Auto-Increment and Primary Key Constraint
CREATE TABLE table_name (
column_name INT AUTO_INCREMENT,
...,
PRIMARY KEY (column_name)
);
Foreign Key Constraint
CREATE TABLE table_name (
column_name INT,
FOREIGN KEY (column_name) REFERENCES other_table(other_column)
);
Unique Constraint: Ensures that all values in a column are different
CREATE TABLE table_name (
column1 INT,
column2 INT,
UNIQUE KEY `key_name` (column1, column2)
);
Check Constraint
CREATE TABLE table_name (
column_name INT,
CHECK (column_name > 10)
);
Check Constraint: DEFAULT CURRENT_DATE()
CREATE TABLE table_name (
City varchar(255) DEFAULT 'Danang'
);
UNSIGNED Constraint
CREATE TABLE table_name (
column_name datatype UNSIGNED,
);
Insert Operations
Insert Data into a Table
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
Insert Multiple Rows into a Table
INSERT INTO table_name (column1, column2, ...) VALUES
(value1, value2, ...),
(value1, value2, ...);
Update Operations
Update Data in a Table
UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;
Delete Operations
Delete all data from a Table
DELETE FROM table_name;
Delete Data from a Table
DELETE FROM table_name WHERE condition;
Delete Data from a Table
DELETE FROM table1, table2 WHERE table1.id1 = table2.id2 AND condition
Delete table records and reset increment
TRUNCATE table_name;
Select Operations
Select Data from a Table
SELECT * FROM table_name;
Select Alias Column
SELECT column_name AS alias_name FROM table_name;
Select Alias Table
SELECT c.OrderID FROM Customers AS c;
Select Data from a Table
SELECT * FROM table1, table2;
Select Data from a Table
SELECT column1, column2, ... FROM table_name;
Select Data from a Table
SELECT column1, column2, ... FROM table_name WHERE condition;
Select Data from a Table
SELECT ... FROM ... WHERE condition ORDER BY column1, column2;
Select Data from a Table
SELECT ... FROM ... WHERE condition ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];
Select Data from a Table
SELECT ... FROM ... WHERE condition LIMIT 10;
Select Data from a Table
SELECT ... FROM ... WHERE condition LIMIT [offset,] row_count;
Select Data from a Table
SELECT ... FROM ... WHERE condition LIMIT row_count OFFSET offset
Join Operations
Inner Join
SELECT * FROM table1 INNER JOIN table2 ON table1.column = table2.column;
Inner Join multiple conditions
SELECT * FROM table1 INNER JOIN table2 ON table1.column = table2.column AND table1.column2 = table2.column2;
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;
Union Operations
Inner Join
SELECT c1, c2 FROM table1 UNION[ALL] SELECT c1, c2 FROM t2;
Condition Operations
Simple Equality Condition
WHERE column_name = value;
Simple Not Equality Condition
WHERE column_name <> value;
Simple Not Equality Condition
WHERE column_name != value;
Greater Than Condition
WHERE column_name > value;
Less Than Condition
WHERE column_name < value;
Greater Than Condition
WHERE column_name >= value;
Greater Than Condition
WHERE column_name <= value;
Between Condition
WHERE column_name BETWEEN value1 AND value2;
IN Condition
WHERE column_name IN (value1, value2, ...);
IN Condition
WHERE column_name NOT IN (value1, value2, ...);
NULL Condition
WHERE column_name IS NULL;
NULL Condition
WHERE column_name IS NOT NULL;
Simple Equality Condition
WHERE column_name LIKE 'd%';
Simple Equality Condition
WHERE column_name LIKE '%d%';
Simple Equality Condition
WHERE column_name NOT LIKE 'd%';
AND Condition
WHERE column_name1 = value AND column_name2 = value;
AND Condition
WHERE column_name1 = value OR column_name2 = value;
Aggregate Function Operations
Aggregate Function Operations
SELECT COUNT(id) FROM table_name;
Aggregate Function Operations
SELECT MAX(age) FROM table_name;
Aggregate Function Operations
SELECT MIN(age) FROM table_name;
Aggregate Function Operations
SELECT SUM(age) FROM table_name;
Aggregate Function Operations
SELECT AVG(age) FROM table_name;
Aggregate Function Operations
SELECT UCASE(first_name), LCASE(first_name) FROM table_name;
Select Data from a Table
SELECT DISTINCT field1 FROM ...;
Select Data from a Table
SELECT DISTINCT field1, field2 FROM;
Function Operations
Simple Equality Condition
SELECT CONCAT(first_name, ' ', last_name) AS 'Name', dept FROM users;
DISTINCT
SELECT DISTINCT location FROM users;
NOW
SELECT NOW();
CURDATE
SELECT CURDATE();
CURTIME
SELECT CURTIME();
YEAR(NOW()),
SELECT YEAR(NOW());
TIMESTAMPDIFF
SELECT TIMESTAMPDIFF(MINUTE, '2023-01-01 12:00:00', NOW());
DATE_FORMAT
SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s');
Group By
Group By
SELECT age, COUNT(age) FROM users GROUP BY age;
Group By
SELECT age, COUNT(age) FROM users WHERE age > 20 GROUP BY age;
Group By
SELECT age, COUNT(age) FROM users GROUP BY age HAVING count(age) >=2;
Subquery Operations
Subquery in WHERE Clause
SELECT * FROM table1 WHERE column_name IN (SELECT column_name FROM table2 WHERE condition);
Group By with Aggregate Function
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name;
Index Operations
Create Index
CREATE INDEX index_name ON table_name (column_name);
Create Index
CREATE TABLE t1 (col1 VARCHAR(10), col2 VARCHAR(20), INDEX index_name (col1, col2)
Create Index
CREATE TABLE t1 (col1 VARCHAR(10), col2 VARCHAR(20), INDEX index_name (col1, col2(10))
Create Index on Multiple Columns
CREATE INDEX index_name ON table_name (column1, column2, ...);
Create Unique Index
CREATE UNIQUE INDEX index_name ON table_name (column_name);
Create Unique Index on Multiple Columns
CREATE UNIQUE INDEX index_name ON table_name (column1, column2, ...);
Drop Index
DROP INDEX index_name ON table_name;
Lock Operations
SELECT...FOR UPDATE
SELECT * FROM table_name FOR UPDATE;
SELECT...FOR SHARE
SELECT * FROM table_name FOR SHARE;
Lock Tables for READ
LOCK TABLES table_name READ;
Lock Tables for Write
LOCK TABLES table_name WRITE;
Unlock Tables
UNLOCK TABLES;
Transaction Operations
Start Transaction
START TRANSACTION;
Commit Transaction
COMMIT;
Rollback Transaction
ROLLBACK;
Auto commit
SET AUTOCOMMIT = 1;
Backup Database Operations
Backup
mysqldump -u Username -p dbNameYouWant > databasename_backup.sql
Import Database Operations
Import
mysql -u Username -p dbNameYouWant < databasename_backup.sql;
Users and Privileges
Users and Privileges
CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';
Users and Privileges
CREATE USER 'user'@'%';
List Users
SELECT * FROM mysql.user;
Users and Privileges
SELECT CURRENT_USER();
Users and Privileges
DROP USER 'user'@'host';
Users and Privileges
ALTER USER 'user'@'hostname' IDENTIFIED BY 'newPass';
Users and Privileges
UPDATE mysql.user SET Password=PASSWORD('new-password-here') WHERE USER='user-name-here' AND Host='host-name-here';
Users and Privileges
GRANT ALL PRIVILEGES ON base.* TO 'user'@'localhost' IDENTIFIED BY 'password';
SHOW GRANTS
SHOW GRANTS FOR 'someuser'@'localhost';
Users and Privileges
GRANT SELECT, INSERT, DELETE ON base.* TO 'user'@'localhost' IDENTIFIED BY 'password';
Users and Privileges
REVOKE ALL PRIVILEGES ON base.* FROM 'user'@'host'; -- one permission only
Users and Privileges
REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'user'@'host'; -- all permissions
Users and Privileges
FLUSH PRIVILEGES;
Other
Show you any queries that are currently running or in the queue to run
SHOW PROCESSLIST;
Show all connected threads
show status where `variable_name` = 'Threads_connected';
Show maximum number of allowed connections
show variables like 'max_connections';
Set new value for maximum connections (no restart needed but for permanent change update my.cnf)
SET GLOBAL max_connections = 150;