This reference provides an overview of essential MySQL commands for database administration, table management, data manipulation, and querying. It serves as a quick guide for both beginners and experienced users working with MySQL.
Use the mysql
client to connect to the MySQL server.
# Connect to MySQL with a username and prompt for a password
mysql -u username -p
# Connect to a specific database
mysql -u username -p database_name
# Connect to MySQL on a specific host and port
mysql -h hostname -P port_number -u username -p
CREATE DATABASE database_name;
DROP DATABASE database_name;
SHOW DATABASES;
USE database_name;
CREATE TABLE table_name (
column1 datatype [constraints],
column2 datatype [constraints],
...
);
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100),
salary DECIMAL(10,2),
hire_date DATE
);
SHOW TABLES;
DESCRIBE table_name;
# Or
EXPLAIN table_name;
# Or
SHOW COLUMNS FROM table_name;
Add a column:
ALTER TABLE table_name ADD COLUMN column_name datatype [constraints];
Modify a column:
ALTER TABLE table_name MODIFY COLUMN column_name new_datatype [new_constraints];
Rename a column:
ALTER TABLE table_name CHANGE old_column_name new_column_name datatype [constraints];
Drop a column:
ALTER TABLE table_name DROP COLUMN column_name;
RENAME TABLE old_table_name TO new_table_name;
DROP TABLE table_name;
Insert a single row:
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
Insert multiple rows:
INSERT INTO table_name (column1, column2, ...)
VALUES
(value1a, value2a, ...),
(value1b, value2b, ...),
...;
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
DELETE FROM table_name WHERE condition;
Note: Omitting the WHERE
clause will delete all rows in the table.
Remove all data from a table (cannot be rolled back):
TRUNCATE TABLE table_name;
Basic select:
SELECT column1, column2, ... FROM table_name;
Select all columns:
SELECT * FROM table_name;
SELECT * FROM table_name WHERE condition;
SELECT * FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
SELECT column1, COUNT(*)
FROM table_name
GROUP BY column1
HAVING condition;
SELECT * FROM table_name LIMIT offset, count;
Inner Join:
SELECT *
FROM table1
INNER JOIN table2 ON table1.column = table2.column;
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;
SELECT *
FROM table_name
WHERE column_name IN (SELECT column_name FROM another_table WHERE condition);
Manage transactions to ensure data integrity.
START TRANSACTION;
# Or
BEGIN;
COMMIT;
ROLLBACK;
CREATE USER 'username'@'host' IDENTIFIED BY 'password';
GRANT privileges ON database.table TO 'username'@'host';
# Examples
GRANT ALL PRIVILEGES ON *.* TO 'username'@'host' WITH GRANT OPTION;
GRANT SELECT, INSERT ON database.* TO 'username'@'host';
SHOW GRANTS FOR 'username'@'host';
REVOKE privileges ON database.table FROM 'username'@'host';
DROP USER 'username'@'host';
# From the command line
mysqldump -u username -p database_name > backup.sql
# From the command line
mysql -u username -p database_name < backup.sql
SELECT column1, column2, ...
FROM table_name
INTO OUTFILE '/path/to/file.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
LOAD DATA INFILE '/path/to/file.csv'
INTO TABLE table_name
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(column1, column2, ...);
CREATE INDEX index_name ON table_name (column1, column2, ...);
DROP INDEX index_name ON table_name;
SHOW INDEX FROM table_name;
DELIMITER //
CREATE PROCEDURE procedure_name (IN param1 datatype, OUT param2 datatype)
BEGIN
-- Procedure body
END //
DELIMITER ;
CALL procedure_name(param1_value, @param2_value);
# Retrieve OUT parameter
SELECT @param2_value;
DELIMITER //
CREATE FUNCTION function_name (param1 datatype, param2 datatype)
RETURNS return_datatype
DETERMINISTIC
BEGIN
-- Function body
RETURN some_value;
END //
DELIMITER ;
SELECT function_name(param1_value, param2_value);
CREATE TRIGGER trigger_name
{ BEFORE | AFTER } { INSERT | UPDATE | DELETE }
ON table_name FOR EACH ROW
BEGIN
-- Trigger body
END;
DROP TRIGGER trigger_name;
CREATE VIEW view_name AS
SELECT columns
FROM table_name
WHERE condition;
DROP VIEW view_name;
SHOW VARIABLES;
SHOW VARIABLES LIKE 'variable_name';
SET SESSION variable_name = value;
SET GLOBAL variable_name = value;
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'database_name';
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_schema = 'database_name'
AND table_name = 'table_name';
SELECT CURRENT_USER();
SELECT DATABASE();
SELECT VERSION();
EXIT;
# Or
QUIT;
;
). Don't forget to include it.\G
instead of ;
to display query results vertically.SHOW WARNINGS;
after a command to display any warnings.\c
to cancel the current command input.source /path/to/file.sql;
to execute SQL commands from a file.Data Type | Description |
---|---|
INT |
Integer numbers. |
DECIMAL(m,d) |
Fixed-point numbers with m digits and d decimals. |
VARCHAR(n) |
Variable-length character string up to n characters. |
CHAR(n) |
Fixed-length character string of n characters. |
TEXT |
Large text data. |
DATE |
Date value in YYYY-MM-DD format. |
DATETIME |
Date and time value in YYYY-MM-DD HH:MM:SS format. |
TIMESTAMP |
Timestamp value, typically used for tracking changes. |
BLOB |
Binary large objects, used to store binary data. |
ENUM |
Enumeration, a string object with a value chosen from a list of permitted values. |
=
Equal to<>
Not equal to>
Greater than<
Less than>=
Greater than or equal to<=
Less than or equal toBETWEEN
... AND
...IN
(value1, value2, ...)LIKE
'pattern%'IS NULL
, IS NOT NULL
AND
OR
NOT
COUNT(column)
SUM(column)
AVG(column)
MAX(column)
MIN(column)
NOW()
CURDATE()
CURTIME()
DATE_ADD(date, INTERVAL value unit)
DATEDIFF(date1, date2)
DATE_FORMAT(date, format)
CONCAT(str1, str2, ...)
SUBSTRING(str, pos, len)
REPLACE(str, from_str, to_str)
UPPER(str)
LOWER(str)
TRIM([remstr FROM] str)
SELECT *
; specify only the columns you need.EXPLAIN
to analyze query performance.